@typeonce/ritmo-devtools 0.14.0 → 0.16.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.
- package/CHANGELOG.md +283 -0
- package/README.md +303 -55
- package/dist/Desync.d.ts +23 -3
- package/dist/Desync.d.ts.map +1 -1
- package/dist/Desync.js +17 -15
- package/dist/Desync.js.map +1 -1
- package/dist/Determinism.d.ts +20 -6
- package/dist/Determinism.d.ts.map +1 -1
- package/dist/Determinism.js +11 -3
- package/dist/Determinism.js.map +1 -1
- package/dist/Format.d.ts +43 -8
- package/dist/Format.d.ts.map +1 -1
- package/dist/Format.js +66 -31
- package/dist/Format.js.map +1 -1
- package/dist/Fuzz.d.ts +275 -0
- package/dist/Fuzz.d.ts.map +1 -0
- package/dist/Fuzz.js +362 -0
- package/dist/Fuzz.js.map +1 -0
- package/dist/Invariant.d.ts +9 -2
- package/dist/Invariant.d.ts.map +1 -1
- package/dist/Invariant.js.map +1 -1
- package/dist/Lint.d.ts +11 -5
- package/dist/Lint.d.ts.map +1 -1
- package/dist/Lint.js.map +1 -1
- package/dist/PlaywrightEngine.d.ts +29 -0
- package/dist/PlaywrightEngine.d.ts.map +1 -0
- package/dist/PlaywrightEngine.js +196 -0
- package/dist/PlaywrightEngine.js.map +1 -0
- package/dist/Replay.d.ts +47 -23
- package/dist/Replay.d.ts.map +1 -1
- package/dist/Replay.js +26 -30
- package/dist/Replay.js.map +1 -1
- package/dist/ReplayNodeSink.d.ts.map +1 -1
- package/dist/ReplayNodeSink.js +4 -1
- package/dist/ReplayNodeSink.js.map +1 -1
- package/dist/ReplayVitePlugin.d.ts +1 -0
- package/dist/ReplayVitePlugin.d.ts.map +1 -1
- package/dist/ReplayVitePlugin.js.map +1 -1
- package/dist/Session.d.ts +224 -18
- package/dist/Session.d.ts.map +1 -1
- package/dist/Session.js +571 -58
- package/dist/Session.js.map +1 -1
- package/dist/Verify.d.ts +150 -0
- package/dist/Verify.d.ts.map +1 -0
- package/dist/Verify.js +154 -0
- package/dist/Verify.js.map +1 -0
- package/dist/cli.js +157 -16
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/internal/dependencyScan.d.ts +44 -0
- package/dist/internal/dependencyScan.d.ts.map +1 -0
- package/dist/internal/dependencyScan.js +313 -0
- package/dist/internal/dependencyScan.js.map +1 -0
- package/dist/internal/fuzzNetwork.d.ts +56 -0
- package/dist/internal/fuzzNetwork.d.ts.map +1 -0
- package/dist/internal/fuzzNetwork.js +96 -0
- package/dist/internal/fuzzNetwork.js.map +1 -0
- package/dist/internal/simulationCoverage.d.ts.map +1 -1
- package/dist/internal/simulationCoverage.js +2 -1
- package/dist/internal/simulationCoverage.js.map +1 -1
- package/dist/internal/skillLink.d.ts +14 -0
- package/dist/internal/skillLink.d.ts.map +1 -0
- package/dist/internal/skillLink.js +46 -0
- package/dist/internal/skillLink.js.map +1 -0
- package/dist/internal/values.d.ts +9 -1
- package/dist/internal/values.d.ts.map +1 -1
- package/dist/internal/values.js +11 -1
- package/dist/internal/values.js.map +1 -1
- package/dist/internal/verifyRunner.d.ts +19 -0
- package/dist/internal/verifyRunner.d.ts.map +1 -0
- package/dist/internal/verifyRunner.js +47 -0
- package/dist/internal/verifyRunner.js.map +1 -0
- package/dist/internal/version.d.ts +1 -1
- package/dist/internal/version.js +1 -1
- package/package.json +28 -3
- package/src/Desync.ts +40 -17
- package/src/Determinism.ts +49 -11
- package/src/Format.ts +101 -34
- package/src/Fuzz.ts +551 -0
- package/src/Invariant.ts +9 -2
- package/src/Lint.ts +11 -5
- package/src/PlaywrightEngine.ts +232 -0
- package/src/Replay.ts +100 -47
- package/src/ReplayNodeSink.ts +4 -1
- package/src/ReplayVitePlugin.ts +1 -0
- package/src/Session.ts +816 -73
- package/src/Verify.ts +276 -0
- package/src/cli.ts +150 -15
- package/src/index.ts +3 -2
- package/src/internal/dependencyScan.ts +356 -0
- package/src/internal/fuzzNetwork.ts +130 -0
- package/src/internal/simulationCoverage.ts +2 -1
- package/src/internal/skillLink.ts +53 -0
- package/src/internal/values.ts +20 -1
- package/src/internal/verifyRunner.ts +46 -0
- package/src/internal/version.ts +1 -1
- package/dist/Monitor.d.ts +0 -101
- package/dist/Monitor.d.ts.map +0 -1
- package/dist/Monitor.js +0 -602
- package/dist/Monitor.js.map +0 -1
- package/dist/internal/monitor.d.ts +0 -126
- package/dist/internal/monitor.d.ts.map +0 -1
- package/dist/internal/monitor.js +0 -279
- package/dist/internal/monitor.js.map +0 -1
- package/src/Monitor.ts +0 -713
- package/src/internal/monitor.ts +0 -370
package/src/Session.ts
CHANGED
|
@@ -7,30 +7,51 @@
|
|
|
7
7
|
* - `run(name, { frames, until })` ticks a schedule frame by frame and stops
|
|
8
8
|
* at the first system failure, thrown defect, or violated invariant (an
|
|
9
9
|
* invariant that throws stops it as `invariant-threw`).
|
|
10
|
+
* - `step(name)` begins one frame and runs it a step at a time
|
|
11
|
+
* (`until(System)`, `next()`, `finish()`), for a value that goes wrong
|
|
12
|
+
* between two systems of one frame. `journal`, `why`, and `dump` show the
|
|
13
|
+
* partial frame.
|
|
10
14
|
* - `journal(filter)` lists what happened, one fact per line, filtered by
|
|
11
15
|
* frames, entity, component, resource, event, machine, system, or kind.
|
|
12
16
|
* - `why(entity, component)` lists the latest changes to one component, and
|
|
13
|
-
* the systems whose declared `spawns` could have spawned the entity.
|
|
17
|
+
* the systems whose declared `spawns` could have spawned the entity. With
|
|
18
|
+
* `depth` above 1 it follows each change back through what the writing
|
|
19
|
+
* system declared it reads, one level per step (see {@link WhyOptions}).
|
|
14
20
|
* - `system(name)` shows one system's declared access and recent activity.
|
|
15
21
|
* - `describe()`, `dump(filter)`, `streams()` render the core debug handle.
|
|
16
22
|
* - `report()` summarizes per-system timing and warnings accumulated while
|
|
17
23
|
* tracing: failed systems, missed reads, commands and next states still
|
|
18
24
|
* pending at the end of a frame, failed transitions, skipped systems that
|
|
19
25
|
* discarded messages, sent events no system reads, NaN or infinite numbers
|
|
20
|
-
* written anywhere,
|
|
26
|
+
* written anywhere, numbers written outside a field's declared `range`
|
|
27
|
+
* (the descriptor's `meta` option), entity counts that keep growing through a run, and
|
|
21
28
|
* failed tick results nobody read.
|
|
22
29
|
*
|
|
23
30
|
* Everything returns a `Rendered` value that prints as text.
|
|
24
31
|
*
|
|
32
|
+
* With `labels`, every entity in that text prints as `player e12` instead of
|
|
33
|
+
* `e12`: journal and `why` lines, `dump`, report warnings, and invariant
|
|
34
|
+
* messages. Labels are evaluated after every frame of a `run`, so a line
|
|
35
|
+
* shows the label its entity had at the end of the line's frame; an entity
|
|
36
|
+
* despawned by then keeps the last label it had.
|
|
37
|
+
*
|
|
25
38
|
* @module Session
|
|
26
39
|
* @docGroup devtools
|
|
27
40
|
*
|
|
28
41
|
* @example
|
|
29
42
|
* ```ts
|
|
43
|
+
* const PlayerInsideWorld = Invariant.fromInspector(Game.Inspector("player inside world", {
|
|
44
|
+
* queries: { players: Game.Query({ selection: { position: Game.Query.read(Position) }, with: [Player] }) }
|
|
45
|
+
* }, ({ queries }) => queries.players.each().some(({ data }) => data.position.get().x < 0) ? "left the world" : undefined))
|
|
46
|
+
* const Labels = Game.Inspector("labels", {
|
|
47
|
+
* queries: { players: Game.Query({ selection: { position: Game.Query.read(Position) }, with: [Player] }) }
|
|
48
|
+
* }, ({ queries }) => new Map(queries.players.each().map((match) => [match.entity.id, "player"] as const)))
|
|
49
|
+
* // ---cut---
|
|
30
50
|
* const session = Session.make(runtime, {
|
|
31
51
|
* hostClock: HostClock.test(),
|
|
32
|
-
* schedules: { setup
|
|
33
|
-
* invariants: [PlayerInsideWorld]
|
|
52
|
+
* schedules: { setup, update },
|
|
53
|
+
* invariants: [PlayerInsideWorld],
|
|
54
|
+
* labels: Labels
|
|
34
55
|
* })
|
|
35
56
|
* session.run("setup")
|
|
36
57
|
* console.log(session.run("update", { frames: 300 }))
|
|
@@ -38,19 +59,19 @@
|
|
|
38
59
|
* console.log(session.journal({ frames: [180, 185], entity: 1 }))
|
|
39
60
|
* ```
|
|
40
61
|
*/
|
|
41
|
-
import { HostClock } from "@typeonce/ritmo"
|
|
62
|
+
import { HostClock, Result } from "@typeonce/ritmo"
|
|
42
63
|
import type * as Debug from "@typeonce/ritmo/Debug"
|
|
43
64
|
import type * as Inspector from "@typeonce/ritmo/Inspector"
|
|
44
65
|
import type * as Machine from "@typeonce/ritmo/Machine"
|
|
45
|
-
import type * as Result from "@typeonce/ritmo/Result"
|
|
46
66
|
import type * as Runtime from "@typeonce/ritmo/Runtime"
|
|
47
67
|
import type { AnyScheduleOrder, ExecutableScheduleDefinition } from "@typeonce/ritmo/Schedule"
|
|
48
68
|
import type { Schema } from "@typeonce/ritmo/Schema"
|
|
69
|
+
import type { SystemDefinition } from "@typeonce/ritmo/System"
|
|
49
70
|
|
|
50
71
|
import * as Format from "./Format.ts"
|
|
51
72
|
import type { Invariant } from "./Invariant.ts"
|
|
52
73
|
import * as Rendered from "./Rendered.ts"
|
|
53
|
-
import { nonFinitePath } from "./internal/values.ts"
|
|
74
|
+
import { nonFinitePath, rangesOf } from "./internal/values.ts"
|
|
54
75
|
|
|
55
76
|
/**
|
|
56
77
|
* What a session needs from a runtime: its debug handle, the dynamic
|
|
@@ -97,12 +118,59 @@ export type ValidateInvariants<
|
|
|
97
118
|
? unknown
|
|
98
119
|
: { readonly __fixInvariantRequirements__: InvariantRequirementErrors<Invariants, Services, Resources, Machines> }
|
|
99
120
|
|
|
121
|
+
/**
|
|
122
|
+
* Names entities in devtools text: a `Game.Inspector` returning a
|
|
123
|
+
* `ReadonlyMap<number, string>` from entity id to label (`player`,
|
|
124
|
+
* `enemy:slime`). It reads the world like an invariant does and is checked
|
|
125
|
+
* the same way; {@link ValidateLabels} rejects one returning anything else.
|
|
126
|
+
* It runs only in a debug session: the game and its runtime never call it.
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```ts
|
|
130
|
+
* const Labels = Game.Inspector("labels", {
|
|
131
|
+
* queries: { players: Game.Query({ selection: { position: Game.Query.read(Position) }, with: [Player] }) }
|
|
132
|
+
* }, ({ queries }) => new Map(queries.players.each().map((match) => [match.entity.id, "player"] as const)))
|
|
133
|
+
* Session.make(runtime, { hostClock: HostClock.test(), schedules: { update }, labels: Labels })
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
export type LabelsInspector<Root = any> = Inspector.InspectorDefinition<any, unknown, Root, any, any>
|
|
137
|
+
|
|
138
|
+
type LabelsRequirementErrors<
|
|
139
|
+
Labels extends Inspector.Inspector.Any,
|
|
140
|
+
Services extends Record<string, unknown>,
|
|
141
|
+
Resources extends object,
|
|
142
|
+
Machines extends Record<string, unknown>
|
|
143
|
+
> = Runtime.ValidateInspector<Labels, Services, Resources, Machines> extends {
|
|
144
|
+
readonly __fixRuntimeRequirements__: infer Errors
|
|
145
|
+
}
|
|
146
|
+
? Errors
|
|
147
|
+
: never
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Rejects a `labels` inspector that does not return a
|
|
151
|
+
* `ReadonlyMap<number, string>`, or that reads a resource, service, or
|
|
152
|
+
* machine the runtime does not provide (named like invariants' are).
|
|
153
|
+
*/
|
|
154
|
+
export type ValidateLabels<
|
|
155
|
+
Labels extends Inspector.Inspector.Any,
|
|
156
|
+
Services extends Record<string, unknown>,
|
|
157
|
+
Resources extends object,
|
|
158
|
+
Machines extends Record<string, unknown>
|
|
159
|
+
> = [Labels] extends [never]
|
|
160
|
+
? unknown
|
|
161
|
+
: [Inspector.Inspector.Value<Labels>] extends [ReadonlyMap<number, string>]
|
|
162
|
+
? [LabelsRequirementErrors<Labels, Services, Resources, Machines>] extends [never]
|
|
163
|
+
? unknown
|
|
164
|
+
: { readonly __fixLabelsRequirements__: LabelsRequirementErrors<Labels, Services, Resources, Machines> }
|
|
165
|
+
: { readonly __fixLabels__: "labels must return a ReadonlyMap<number, string> from entity id to label" }
|
|
166
|
+
|
|
100
167
|
/** What `Session.make` drives and checks, and how it prints. */
|
|
101
168
|
export interface Options<
|
|
102
169
|
S extends Schema.Any,
|
|
103
170
|
Root,
|
|
104
171
|
Names extends string,
|
|
105
|
-
Invariants extends ReadonlyArray<Invariant<Invariant.CheckInspector>> = readonly []
|
|
172
|
+
Invariants extends ReadonlyArray<Invariant<Invariant.CheckInspector>> = readonly [],
|
|
173
|
+
Labels extends LabelsInspector<Root> = never
|
|
106
174
|
> {
|
|
107
175
|
/** The schedules `run` can drive, by name. Also names them in traces. */
|
|
108
176
|
readonly schedules: Readonly<Record<Names, ExecutableScheduleDefinition<S, any, Root, any, any, AnyScheduleOrder>>>
|
|
@@ -124,6 +192,14 @@ export interface Options<
|
|
|
124
192
|
* stops the run. Built with `Invariant.fromInspector(Game.Inspector(...))`.
|
|
125
193
|
*/
|
|
126
194
|
readonly invariants?: Invariants
|
|
195
|
+
/**
|
|
196
|
+
* Names entities in all text output (`player e12`), from a
|
|
197
|
+
* {@link LabelsInspector}. Evaluated after every frame of a `run` (and
|
|
198
|
+
* when a query finds frames ticked outside `run`), so journal lines show
|
|
199
|
+
* the label from the end of their frame; despawned entities keep their
|
|
200
|
+
* last label.
|
|
201
|
+
*/
|
|
202
|
+
readonly labels?: Labels
|
|
127
203
|
/** Frames of trace history kept for `journal` and `why`. Defaults to 600. */
|
|
128
204
|
readonly history?: number
|
|
129
205
|
/**
|
|
@@ -156,6 +232,8 @@ export type Stop =
|
|
|
156
232
|
| { readonly reason: "invariant"; readonly frame: number; readonly invariant: string; readonly message: string }
|
|
157
233
|
/** The invariant itself threw: a bug in the check, not a violation. Fix the check, then run again. */
|
|
158
234
|
| { readonly reason: "invariant-threw"; readonly frame: number; readonly invariant: string; readonly error: unknown }
|
|
235
|
+
/** The `labels` inspector threw: a bug in it. Fix it, then run again. */
|
|
236
|
+
| { readonly reason: "labels-threw"; readonly frame: number; readonly error: unknown }
|
|
159
237
|
/**
|
|
160
238
|
* A failed tick result nobody read (for example a setup tick the game ran
|
|
161
239
|
* before this run): `frame` is the failed tick's, `skipped` the systems
|
|
@@ -229,6 +307,48 @@ export interface JournalFilter<S extends Schema.Any> {
|
|
|
229
307
|
readonly verbose?: boolean
|
|
230
308
|
}
|
|
231
309
|
|
|
310
|
+
/**
|
|
311
|
+
* How far `why` and `whyResource` look back.
|
|
312
|
+
*
|
|
313
|
+
* The trace records what systems wrote, not what they read, so a level
|
|
314
|
+
* past the first comes from declarations: under each change, one indented
|
|
315
|
+
* `read` line per read the writing system declares, each with the latest
|
|
316
|
+
* traced fact that could have produced the value it saw then:
|
|
317
|
+
*
|
|
318
|
+
* - an event: what was published to it since the system's previous run,
|
|
319
|
+
* and by which system (or `runtime.send`);
|
|
320
|
+
* - a component of the written entity, read in the query that wrote it: the
|
|
321
|
+
* latest write, spawn, or insert of it on that entity before the run;
|
|
322
|
+
* - a component of any other query: only how many entities match it now,
|
|
323
|
+
* since the trace does not say which ones the system read;
|
|
324
|
+
* - a resource: its latest write before the run;
|
|
325
|
+
* - a machine: its latest transition or field update before the run.
|
|
326
|
+
*
|
|
327
|
+
* Every such line ends in `(declared)`: a possible cause, not an observed
|
|
328
|
+
* read. A system already in the chain is printed with `(cycle: not
|
|
329
|
+
* followed)` and not followed again.
|
|
330
|
+
*
|
|
331
|
+
* @example
|
|
332
|
+
* ```ts
|
|
333
|
+
* const session = Session.make(runtime, { hostClock: HostClock.test(), schedules: { update } })
|
|
334
|
+
* // ---cut---
|
|
335
|
+
* session.why(12, Health, { depth: 3 })
|
|
336
|
+
* // f181 update Game/ApplyDamage write e12 Game/Health 70 -> 40
|
|
337
|
+
* // read Game/Damage [{amount:30}] (declared), emitted by Game/Hitscan at f181
|
|
338
|
+
* // read e12 Game/Aim {target:7} (declared), written by Game/AimAtNewest at f180
|
|
339
|
+
* ```
|
|
340
|
+
*/
|
|
341
|
+
export interface WhyOptions {
|
|
342
|
+
/** Changes listed, and reads listed under each change. Defaults to 5. */
|
|
343
|
+
readonly limit?: number
|
|
344
|
+
/**
|
|
345
|
+
* Levels printed: 1 (the default) lists the changes alone; 2 adds what
|
|
346
|
+
* each writing system declared it reads and who produced it; 3 adds the
|
|
347
|
+
* reads of those producers, and so on.
|
|
348
|
+
*/
|
|
349
|
+
readonly depth?: number
|
|
350
|
+
}
|
|
351
|
+
|
|
232
352
|
/** One system's runs and timing over the session, in `report()` and `system(name)`. */
|
|
233
353
|
export interface SystemStats {
|
|
234
354
|
readonly system: string
|
|
@@ -257,6 +377,7 @@ export interface Warning {
|
|
|
257
377
|
| "sent-event-unread"
|
|
258
378
|
| "system-failed"
|
|
259
379
|
| "non-finite-value"
|
|
380
|
+
| "out-of-range"
|
|
260
381
|
| "population-growing"
|
|
261
382
|
| "ignored-failure"
|
|
262
383
|
readonly message: string
|
|
@@ -286,16 +407,122 @@ export interface SystemActivity {
|
|
|
286
407
|
readonly recent: ReadonlyArray<Format.Line>
|
|
287
408
|
}
|
|
288
409
|
|
|
410
|
+
type AnySystem = SystemDefinition<any, any, any, any, any>
|
|
411
|
+
|
|
412
|
+
/** The systems a schedule runs as its own steps: nested schedules included, transition schedules (run inside a marker) not. */
|
|
413
|
+
type StepSystemsIn<Entry> =
|
|
414
|
+
Entry extends AnySystem ? Entry
|
|
415
|
+
: Entry extends { readonly kind: "applyStateTransitions" } ? never
|
|
416
|
+
: Entry extends { readonly __order?: (_: never) => infer Order extends AnyScheduleOrder } ? StepSystemsIn<Order["entries"][number]>
|
|
417
|
+
: never
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* The systems `frame.until(...)` accepts for one schedule: the systems it
|
|
421
|
+
* runs as steps, so a system of another schedule does not compile. A
|
|
422
|
+
* schedule whose type was widened accepts any system, and `until` reports
|
|
423
|
+
* one it does not run as `notAhead`.
|
|
424
|
+
*/
|
|
425
|
+
export type StepSystem<Schedule> = [StepSystemsIn<Schedule>] extends [never] ? AnySystem : StepSystemsIn<Schedule>
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Why a step call did not get where it was asked to.
|
|
429
|
+
*
|
|
430
|
+
* - `frameEnded`: the frame already ended (its last step ran, or a system
|
|
431
|
+
* failed); nothing ran. `finish()` reports the frame.
|
|
432
|
+
* - `notAhead`: the system is not among the steps left (it already ran
|
|
433
|
+
* this frame, or the schedule does not run it as a step); nothing ran.
|
|
434
|
+
* - `failure` / `defect`: a system returned a failure or a step threw; the
|
|
435
|
+
* steps after it do not run this frame, and the frame ended.
|
|
436
|
+
* - `missingRequirements` / `tickOrder`: the frame never began, as `run`
|
|
437
|
+
* reports them.
|
|
438
|
+
*/
|
|
439
|
+
export type StepStop =
|
|
440
|
+
| { readonly reason: "frameEnded"; readonly frame: number }
|
|
441
|
+
| { readonly reason: "notAhead"; readonly frame: number; readonly system: string; readonly remaining: ReadonlyArray<Debug.StepDescription> }
|
|
442
|
+
| Extract<Stop, { readonly reason: "failure" | "defect" | "missingRequirements" | "tickOrder" }>
|
|
443
|
+
|
|
444
|
+
/** Where `frame.until(system)` stopped: before `system`, which has not run yet. */
|
|
445
|
+
export interface StepReached {
|
|
446
|
+
readonly frame: number
|
|
447
|
+
readonly system: string
|
|
448
|
+
/** The steps this call ran, in order (empty when `system` was already next). */
|
|
449
|
+
readonly ran: ReadonlyArray<Debug.StepDescription>
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** The step `frame.next()` ran. */
|
|
453
|
+
export interface StepRan {
|
|
454
|
+
readonly frame: number
|
|
455
|
+
readonly step: Debug.StepDescription
|
|
456
|
+
/** `true` when it was the last step: the frame ended, and `finish()` evaluates it. */
|
|
457
|
+
readonly ended: boolean
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** A violated or throwing invariant found by `frame.check()`. */
|
|
461
|
+
export type CheckStop = Extract<Stop, { readonly reason: "invariant" | "invariant-threw" }>
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* One frame of a schedule run a step at a time, begun by `session.step(name)`.
|
|
465
|
+
* Each system run still commits at its end, markers apply at their position,
|
|
466
|
+
* and reader cursors advance as in `run`: only the pauses are new. While it
|
|
467
|
+
* is open, `run`, `step`, and the runtime's `tick`, `send`, `snapshot`,
|
|
468
|
+
* `restore`, `checkpoint`, and `rewind` are refused; `finish()` it first.
|
|
469
|
+
*/
|
|
470
|
+
export interface SteppedFrame<System> {
|
|
471
|
+
/**
|
|
472
|
+
* Runs the steps (systems and markers) before `system` and stops before
|
|
473
|
+
* it. Takes the system value placed in the schedule, so names that repeat
|
|
474
|
+
* across schedules stay unambiguous and a system the schedule does not
|
|
475
|
+
* run does not compile.
|
|
476
|
+
*/
|
|
477
|
+
readonly until: (system: System) => Rendered.Rendered<Result.Result<StepReached, StepStop>>
|
|
478
|
+
/** Runs exactly one step. */
|
|
479
|
+
readonly next: () => Rendered.Rendered<Result.Result<StepRan, StepStop>>
|
|
480
|
+
/** The steps not run yet, in order; empty once the frame has ended. */
|
|
481
|
+
readonly remaining: () => Rendered.Rendered<ReadonlyArray<Debug.StepDescription>>
|
|
482
|
+
/**
|
|
483
|
+
* Evaluates the session's invariants now, between two steps. An invariant
|
|
484
|
+
* may legitimately fail mid-frame (a marker later in the frame applies the
|
|
485
|
+
* commands that restore it), so this is only an explicit question:
|
|
486
|
+
* `finish()` checks the invariants at the end of the frame, as `run` does.
|
|
487
|
+
* Like labels, it reads the world through inspectors, which advances the
|
|
488
|
+
* world's change tick: tick numbers in this frame then differ from an
|
|
489
|
+
* unstepped run's.
|
|
490
|
+
*/
|
|
491
|
+
readonly check: () => Rendered.Rendered<Result.Result<void, CheckStop>>
|
|
492
|
+
/**
|
|
493
|
+
* Runs the rest of the frame and reports it as `run(name, { frames: 1 })`
|
|
494
|
+
* would: the same `RunResult`, with labels and invariants evaluated at the
|
|
495
|
+
* end of the frame. A system failure or defect during an earlier step is
|
|
496
|
+
* its stop. Calling it again returns the same result.
|
|
497
|
+
*/
|
|
498
|
+
readonly finish: () => Rendered.Rendered<RunResult>
|
|
499
|
+
}
|
|
500
|
+
|
|
289
501
|
/** A debug session made by `Session.make`; see the module description for each query. */
|
|
290
|
-
export interface Session<
|
|
502
|
+
export interface Session<
|
|
503
|
+
S extends Schema.Any,
|
|
504
|
+
Names extends string,
|
|
505
|
+
Schedules extends Readonly<Record<Names, unknown>> = Readonly<Record<Names, ExecutableScheduleDefinition<S, any, any, any, any, AnyScheduleOrder>>>
|
|
506
|
+
> {
|
|
291
507
|
/** Ticks the named schedule frame by frame; stops at the first failure, defect, or violated invariant. */
|
|
292
508
|
readonly run: (name: Names, options?: RunOptions) => Rendered.Rendered<RunResult>
|
|
509
|
+
/**
|
|
510
|
+
* Begins one frame of the named schedule, to run it a step at a time (see
|
|
511
|
+
* {@link SteppedFrame}). Use it when a value goes wrong between two systems
|
|
512
|
+
* of one frame; use `run` for whole frames.
|
|
513
|
+
*/
|
|
514
|
+
readonly step: <Name extends Names>(name: Name) => SteppedFrame<StepSystem<Schedules[Name]>>
|
|
293
515
|
/** What happened in the kept history, one fact per line. */
|
|
294
516
|
readonly journal: (filter?: JournalFilter<S>) => Rendered.Rendered<ReadonlyArray<Format.Line>>
|
|
295
|
-
/**
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
517
|
+
/**
|
|
518
|
+
* Latest changes to one entity's component, and the systems whose `spawns`
|
|
519
|
+
* could have spawned it; with `depth` above 1, what each writing system
|
|
520
|
+
* declared it reads, under each change ({@link WhyOptions}). Use
|
|
521
|
+
* `whyResource` for resources.
|
|
522
|
+
*/
|
|
523
|
+
readonly why: (entity: number, component: Schema.ComponentDescriptor<S>, options?: WhyOptions) => Rendered.Rendered<ReadonlyArray<Format.Line>>
|
|
524
|
+
/** Latest changes to one resource and the systems that made them; `depth` as for `why`. */
|
|
525
|
+
readonly whyResource: (resource: Schema.ResourceDescriptor<S>, options?: WhyOptions) => Rendered.Rendered<ReadonlyArray<Format.Line>>
|
|
299
526
|
/** One system's declared access and recent activity. */
|
|
300
527
|
readonly system: (name: string, options?: { readonly limit?: number }) => Rendered.Rendered<SystemActivity>
|
|
301
528
|
/** `debug.describe()`, lints first. */
|
|
@@ -315,8 +542,13 @@ export interface Session<S extends Schema.Any, Names extends string> {
|
|
|
315
542
|
interface FrameRecord {
|
|
316
543
|
readonly frame: number
|
|
317
544
|
readonly events: Array<Debug.TraceEvent>
|
|
545
|
+
/** The labels at the end of this frame, when they were evaluated then. */
|
|
546
|
+
labels?: ReadonlyMap<number, string>
|
|
318
547
|
}
|
|
319
548
|
|
|
549
|
+
/** `e12` tokens in free text (not `&e12` handles), as an invariant writes them. */
|
|
550
|
+
const entityToken = /(?<![\w&])e(\d+)\b/g
|
|
551
|
+
|
|
320
552
|
const inRange = (frame: number, frames: number | readonly [number, number] | undefined): boolean =>
|
|
321
553
|
frames === undefined ? true
|
|
322
554
|
: typeof frames === "number" ? frame === frames
|
|
@@ -342,6 +574,16 @@ const growsSteadily = (samples: ReadonlyArray<number>): boolean => {
|
|
|
342
574
|
return true
|
|
343
575
|
}
|
|
344
576
|
|
|
577
|
+
/** The stop for a failed tick or step result, as `run` reports it. */
|
|
578
|
+
const failureStop = (failure: unknown, frame: number): Extract<Stop, { readonly reason: "failure" | "missingRequirements" | "tickOrder" }> => {
|
|
579
|
+
const error = describeError(failure)
|
|
580
|
+
return error.kind === "MissingRuntimeRequirements"
|
|
581
|
+
? { reason: "missingRequirements", frame, requirements: error.requirements }
|
|
582
|
+
: error.kind === "TickOrderViolation"
|
|
583
|
+
? { reason: "tickOrder", frame, issues: (error.issues ?? []).map((issue) => issue.message) }
|
|
584
|
+
: { reason: "failure", frame, system: typeof error.system === "string" ? error.system : "(unknown)", error: error.error }
|
|
585
|
+
}
|
|
586
|
+
|
|
345
587
|
const describeError = (error: unknown): { readonly kind?: unknown; readonly system?: unknown; readonly error?: unknown; readonly requirements?: unknown; readonly issues?: ReadonlyArray<{ readonly message: string }> } =>
|
|
346
588
|
typeof error === "object" && error !== null ? error : {}
|
|
347
589
|
|
|
@@ -358,12 +600,18 @@ export const make = <
|
|
|
358
600
|
Resources extends object,
|
|
359
601
|
Machines extends Record<string, unknown>,
|
|
360
602
|
const Names extends string,
|
|
361
|
-
const
|
|
603
|
+
const Schedules extends Readonly<Record<Names, ExecutableScheduleDefinition<S, any, Root, any, any, AnyScheduleOrder>>>,
|
|
604
|
+
const Invariants extends ReadonlyArray<Invariant<Inspector.InspectorDefinition<any, string | undefined, Root, any, any>>> = readonly [],
|
|
605
|
+
const Labels extends LabelsInspector<Root> = never
|
|
362
606
|
>(
|
|
363
607
|
runtime: Target<S, Root, Services, Resources, Machines>,
|
|
364
|
-
options:
|
|
365
|
-
|
|
366
|
-
|
|
608
|
+
options:
|
|
609
|
+
& Options<S, Root, Names, Invariants, Labels>
|
|
610
|
+
& { readonly schedules: Schedules }
|
|
611
|
+
& ValidateInvariants<Invariants, Services, Resources, Machines>
|
|
612
|
+
& ValidateLabels<Labels, Services, Resources, Machines>
|
|
613
|
+
): Session<S, Names, Schedules> => {
|
|
614
|
+
const inspect = runtime.inspect as (inspector: Inspector.Inspector.Any) => unknown
|
|
367
615
|
const debug = runtime.debug
|
|
368
616
|
const capacity = options.history ?? 600
|
|
369
617
|
const format = options.format ?? {}
|
|
@@ -385,8 +633,45 @@ export const make = <
|
|
|
385
633
|
}
|
|
386
634
|
return entry
|
|
387
635
|
}
|
|
388
|
-
const
|
|
389
|
-
|
|
636
|
+
const labelsInspector = options.labels as LabelsInspector | undefined
|
|
637
|
+
/** Each labelled entity's latest label; a despawned entity keeps its last one. */
|
|
638
|
+
const lastLabels = new Map<number, string>()
|
|
639
|
+
/** The labels of the last evaluation. */
|
|
640
|
+
let latestLabels: ReadonlyMap<number, string> = new Map()
|
|
641
|
+
/** Evaluates the labels for the frame that just ended and stamps it on its record. */
|
|
642
|
+
const evaluateLabels = (): void => {
|
|
643
|
+
if (labelsInspector === undefined) return
|
|
644
|
+
const labels = inspect(labelsInspector) as ReadonlyMap<number, string>
|
|
645
|
+
const dropped = [...latestLabels.keys()].filter((id) => !labels.has(id))
|
|
646
|
+
// An entity that lost its label while alive has none now; a despawned one keeps it.
|
|
647
|
+
if (dropped.length > 0) for (const alive of debug.dump({ entities: dropped }).entities) lastLabels.delete(alive.id)
|
|
648
|
+
for (const [id, label] of labels) lastLabels.set(id, label)
|
|
649
|
+
latestLabels = labels
|
|
650
|
+
current.labels = labels
|
|
651
|
+
}
|
|
652
|
+
/** Evaluates labels when frames ran outside `run` (queries print the latest world). */
|
|
653
|
+
const refreshLabels = (): void => {
|
|
654
|
+
if (labelsInspector === undefined || current.labels !== undefined) return
|
|
655
|
+
try {
|
|
656
|
+
evaluateLabels()
|
|
657
|
+
} catch {
|
|
658
|
+
// A throwing labels inspector stops `run` as `labels-threw`; queries print ids alone.
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
/** The labels for a line of `frame`: that frame's (or the next evaluated one's), then each entity's last. */
|
|
662
|
+
const labelsAt = (frame: number): Format.Labels | undefined => {
|
|
663
|
+
if (labelsInspector === undefined) return undefined
|
|
664
|
+
const own = history.find((entry) => entry.frame >= frame && entry.labels !== undefined)?.labels
|
|
665
|
+
return { get: (id) => own?.get(id) ?? lastLabels.get(id) }
|
|
666
|
+
}
|
|
667
|
+
const nowLabels = (): Format.Labels | undefined => {
|
|
668
|
+
refreshLabels()
|
|
669
|
+
return labelsAt(debug.frame())
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
type WarningMessage = string | ((labels: Format.Labels | undefined) => string)
|
|
673
|
+
const warnings = new Map<string, { code: Warning["code"]; message: WarningMessage; count: number; firstFrame: number; lastFrame: number }>()
|
|
674
|
+
const warn = (code: Warning["code"], key: string, message: WarningMessage, frame: number) => {
|
|
390
675
|
const existing = warnings.get(key)
|
|
391
676
|
if (existing) {
|
|
392
677
|
existing.count += 1
|
|
@@ -428,11 +713,34 @@ export const make = <
|
|
|
428
713
|
warn(
|
|
429
714
|
"non-finite-value",
|
|
430
715
|
`nonfinite:${system}:${subject}`,
|
|
431
|
-
`${system} wrote a NaN or infinite number to ${entity === undefined ? "" :
|
|
716
|
+
(labels) => `${system} wrote a NaN or infinite number to ${entity === undefined ? "" : `${Format.entity(entity, labels)} `}${subject}${path} (first at f${frame}; why() shows its history)`,
|
|
432
717
|
frame
|
|
433
718
|
)
|
|
434
719
|
}
|
|
435
720
|
|
|
721
|
+
/** The declared ranges of every component and resource field, by descriptor name, read from `describe()` on the first write. */
|
|
722
|
+
let ranges: ReturnType<typeof rangesOf> | undefined
|
|
723
|
+
const checkRange = (kind: "component" | "resource", system: string, subject: string, value: unknown, frame: number, entity?: number) => {
|
|
724
|
+
ranges ??= rangesOf(debug.describe())
|
|
725
|
+
const fields = ranges[kind].get(subject)
|
|
726
|
+
if (fields === undefined || typeof value !== "object" || value === null) return
|
|
727
|
+
for (const [field, min, max] of fields) {
|
|
728
|
+
const written = (value as Readonly<Record<string, unknown>>)[field]
|
|
729
|
+
// NaN and infinities are `non-finite-value` warnings.
|
|
730
|
+
if (typeof written !== "number" || !Number.isFinite(written) || (written >= min && written <= max)) continue
|
|
731
|
+
warn(
|
|
732
|
+
"out-of-range",
|
|
733
|
+
`range:${system}:${subject}.${field}`,
|
|
734
|
+
(labels) => `${entity === undefined ? "" : `${Format.entity(entity, labels)} `}${subject}.${field} written as ${Format.value(written)}, declared range [${Format.value(min)}, ${Format.value(max)}] by ${system} at frame ${frame}`,
|
|
735
|
+
frame
|
|
736
|
+
)
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
const checkComponent = (system: string, subject: string, value: unknown, frame: number, entity: number) => {
|
|
740
|
+
checkFinite(system, subject, value, frame, entity)
|
|
741
|
+
checkRange("component", system, subject, value, frame, entity)
|
|
742
|
+
}
|
|
743
|
+
|
|
436
744
|
const record = (event: Debug.TraceEvent) => {
|
|
437
745
|
if (event.type === "frame") {
|
|
438
746
|
checkPending(current.frame)
|
|
@@ -452,8 +760,11 @@ export const make = <
|
|
|
452
760
|
warn("system-failed", `failed:${event.system}`, `${event.system} ${event.outcome === "defect" ? "threw" : "failed"}: ${Format.value(event.error, format)}`, event.frame)
|
|
453
761
|
} else {
|
|
454
762
|
if (event.commands.length > 0) pending.set(event.system, (pending.get(event.system) ?? 0) + event.commands.length)
|
|
455
|
-
for (const write of event.writes)
|
|
456
|
-
for (const write of event.resources)
|
|
763
|
+
for (const write of event.writes) checkComponent(event.system, write.component, write.after, event.frame, write.entity)
|
|
764
|
+
for (const write of event.resources) {
|
|
765
|
+
checkFinite(event.system, write.resource, write.after, event.frame)
|
|
766
|
+
checkRange("resource", event.system, write.resource, write.after, event.frame)
|
|
767
|
+
}
|
|
457
768
|
for (const emit of event.events) checkFinite(event.system, emit.event, emit.values, event.frame)
|
|
458
769
|
for (const next of event.nextStates) {
|
|
459
770
|
if (next.value === undefined) pendingStates.delete(next.machine)
|
|
@@ -493,13 +804,13 @@ export const make = <
|
|
|
493
804
|
for (const effect of command.effects) {
|
|
494
805
|
switch (effect.kind) {
|
|
495
806
|
case "spawn":
|
|
496
|
-
for (const [component, value] of Object.entries(effect.components))
|
|
807
|
+
for (const [component, value] of Object.entries(effect.components)) checkComponent(command.system, component, value, event.frame, effect.entity)
|
|
497
808
|
break
|
|
498
809
|
case "insert":
|
|
499
|
-
|
|
810
|
+
checkComponent(command.system, effect.component, effect.value, event.frame, effect.entity)
|
|
500
811
|
break
|
|
501
812
|
case "overwrite":
|
|
502
|
-
|
|
813
|
+
checkComponent(command.system, effect.component, effect.after, event.frame, effect.entity)
|
|
503
814
|
break
|
|
504
815
|
}
|
|
505
816
|
}
|
|
@@ -531,12 +842,50 @@ export const make = <
|
|
|
531
842
|
return first === undefined ? undefined : [first.frame, history[history.length - 1]!.frame]
|
|
532
843
|
}
|
|
533
844
|
|
|
845
|
+
/** The first invariant violated (or throwing) now, in order. */
|
|
846
|
+
const checkInvariants = (frame: number): CheckStop | undefined => {
|
|
847
|
+
for (const invariant of options.invariants ?? []) {
|
|
848
|
+
let message: string | undefined
|
|
849
|
+
try {
|
|
850
|
+
message = inspect(invariant.inspector) as string | undefined
|
|
851
|
+
} catch (error) {
|
|
852
|
+
return { reason: "invariant-threw", frame, invariant: invariant.name, error }
|
|
853
|
+
}
|
|
854
|
+
if (message !== undefined) return { reason: "invariant", frame, invariant: invariant.name, message }
|
|
855
|
+
}
|
|
856
|
+
return undefined
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** What a run compares against: taken before its first frame begins. */
|
|
860
|
+
const startRun = () => {
|
|
861
|
+
takeIgnored()
|
|
862
|
+
return {
|
|
863
|
+
started: options.hostClock.now(),
|
|
864
|
+
warningsBefore: new Map([...warnings].map(([key, warning]) => [key, warning.count])),
|
|
865
|
+
initial: debug.population()
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/** The frame `session.step` has open, if any. */
|
|
870
|
+
let stepping: { readonly name: string; readonly frame: number } | undefined
|
|
871
|
+
const refuseWhileStepping = (call: string): void => {
|
|
872
|
+
if (stepping !== undefined) throw new Error(`${call} was called while frame f${stepping.frame} of ${stepping.name} is being stepped: call finish() on it first`)
|
|
873
|
+
}
|
|
874
|
+
|
|
534
875
|
const run = (name: Names, runOptions: RunOptions = {}): Rendered.Rendered<RunResult> => {
|
|
876
|
+
refuseWhileStepping(`session.run(${name})`)
|
|
535
877
|
const schedule = schedules[name]!
|
|
878
|
+
return runFrames(name, runOptions, startRun(), () => runtime.tryTick(schedule))
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/** Ticks `frames` frames with `tickFrame` and reports them; `run` and `finish()` share it. */
|
|
882
|
+
const runFrames = (
|
|
883
|
+
name: string,
|
|
884
|
+
runOptions: RunOptions,
|
|
885
|
+
{ started, warningsBefore, initial }: ReturnType<typeof startRun>,
|
|
886
|
+
tickFrame: () => Result.Result<void, unknown>
|
|
887
|
+
): Rendered.Rendered<RunResult> => {
|
|
536
888
|
const frames = runOptions.frames ?? 1
|
|
537
|
-
const started = options.hostClock.now()
|
|
538
|
-
const warningsBefore = new Map([...warnings].map(([key, warning]) => [key, warning.count]))
|
|
539
|
-
const initial = debug.population()
|
|
540
889
|
const entityCounts: Array<number> = []
|
|
541
890
|
const componentCounts = new Map<string, Array<number>>(Object.keys(initial.components).map((name) => [name, []]))
|
|
542
891
|
const sample = () => {
|
|
@@ -547,11 +896,10 @@ export const make = <
|
|
|
547
896
|
let first: number | undefined
|
|
548
897
|
let last: number | undefined
|
|
549
898
|
let stop: Stop = { reason: "completed" }
|
|
550
|
-
takeIgnored()
|
|
551
899
|
for (let index = 0; index < frames; index++) {
|
|
552
900
|
let result: Result.Result<void, unknown>
|
|
553
901
|
try {
|
|
554
|
-
result =
|
|
902
|
+
result = tickFrame()
|
|
555
903
|
} catch (defect) {
|
|
556
904
|
const frame = debug.frame()
|
|
557
905
|
first ??= frame
|
|
@@ -570,28 +918,16 @@ export const make = <
|
|
|
570
918
|
break
|
|
571
919
|
}
|
|
572
920
|
if (!result.ok) {
|
|
573
|
-
|
|
574
|
-
stop = error.kind === "MissingRuntimeRequirements"
|
|
575
|
-
? { reason: "missingRequirements", frame, requirements: error.requirements }
|
|
576
|
-
: error.kind === "TickOrderViolation"
|
|
577
|
-
? { reason: "tickOrder", frame, issues: (error.issues ?? []).map((issue) => issue.message) }
|
|
578
|
-
: { reason: "failure", frame, system: typeof error.system === "string" ? error.system : "(unknown)", error: error.error }
|
|
921
|
+
stop = failureStop(result.error, frame)
|
|
579
922
|
break
|
|
580
923
|
}
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
} catch (error) {
|
|
587
|
-
checked = { reason: "invariant-threw", frame, invariant: invariant.name, error }
|
|
588
|
-
break
|
|
589
|
-
}
|
|
590
|
-
if (message !== undefined) {
|
|
591
|
-
checked = { reason: "invariant", frame, invariant: invariant.name, message }
|
|
592
|
-
break
|
|
593
|
-
}
|
|
924
|
+
try {
|
|
925
|
+
evaluateLabels()
|
|
926
|
+
} catch (error) {
|
|
927
|
+
stop = { reason: "labels-threw", frame, error }
|
|
928
|
+
break
|
|
594
929
|
}
|
|
930
|
+
const checked = checkInvariants(frame)
|
|
595
931
|
if (checked) {
|
|
596
932
|
stop = checked
|
|
597
933
|
break
|
|
@@ -645,21 +981,163 @@ export const make = <
|
|
|
645
981
|
const warningText = raisedCodes.length === 0
|
|
646
982
|
? ""
|
|
647
983
|
: `\nwarnings during the run (see report()): ${raisedCodes.map(([code, count]) => `${code} x${count}`).join(", ")}`
|
|
648
|
-
return Rendered.make(data, renderRun(data, format) + lintText + warningText)
|
|
984
|
+
return Rendered.make(data, renderRun(data, format, labelsAt(debug.frame())) + lintText + warningText)
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
const step = (name: Names): SteppedFrame<AnySystem> => {
|
|
988
|
+
refuseWhileStepping(`session.step(${name})`)
|
|
989
|
+
const schedule = schedules[name]!
|
|
990
|
+
const start = startRun()
|
|
991
|
+
const begun = debug.beginFrame(schedule)
|
|
992
|
+
const frame = debug.frame()
|
|
993
|
+
const cursor = begun.ok ? begun.value : undefined
|
|
994
|
+
/** Why the frame never began (missing requirements, `thisTick` order). */
|
|
995
|
+
const notBegun = begun.ok ? undefined : failureStop(begun.error, frame) as StepStop
|
|
996
|
+
/** How the frame ended before `finish()`: a failed system's result, or a thrown defect. */
|
|
997
|
+
let ended: { readonly result: Result.Result<void, unknown> } | { readonly defect: unknown } | undefined
|
|
998
|
+
let finished: Rendered.Rendered<RunResult> | undefined
|
|
999
|
+
if (cursor !== undefined && cursor.remaining().length > 0) stepping = { name, frame }
|
|
1000
|
+
|
|
1001
|
+
const head = notBegun === undefined ? `step ${name} f${frame}` : `step ${name}`
|
|
1002
|
+
const stopText = (stop: StepStop): string => {
|
|
1003
|
+
switch (stop.reason) {
|
|
1004
|
+
case "frameEnded":
|
|
1005
|
+
return `${head}: the frame has ended; finish() reports it`
|
|
1006
|
+
case "notAhead":
|
|
1007
|
+
return `${head}: ${stop.system} is not ahead (it already ran this frame, or ${name} does not run it as a step); nothing ran. Remaining: ${stop.remaining.length === 0 ? "(none)" : stop.remaining.map(Format.step).join(", ")}`
|
|
1008
|
+
case "failure":
|
|
1009
|
+
return `${head}: ${stop.system} FAILED: ${Format.value(stop.error, format)}; the frame ended, finish() reports it`
|
|
1010
|
+
case "defect":
|
|
1011
|
+
return `${head}: DEFECT: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`
|
|
1012
|
+
case "missingRequirements":
|
|
1013
|
+
return `${head}: NOT BEGUN: missing runtime requirements ${Format.value(stop.requirements, format)}`
|
|
1014
|
+
case "tickOrder":
|
|
1015
|
+
return `${head}: NOT BEGUN: ${stop.issues.join("; ")}`
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
const remainingSteps = (): ReadonlyArray<Debug.StepDescription> =>
|
|
1019
|
+
cursor === undefined || ended !== undefined ? [] : cursor.remaining()
|
|
1020
|
+
const nextText = (): string => {
|
|
1021
|
+
const left = remainingSteps()
|
|
1022
|
+
return left.length === 0 ? "the frame ended, finish() reports it" : `next: ${Format.step(left[0]!)}`
|
|
1023
|
+
}
|
|
1024
|
+
const unavailable = (): StepStop | undefined =>
|
|
1025
|
+
notBegun ?? (remainingSteps().length === 0 ? { reason: "frameEnded", frame } : undefined)
|
|
1026
|
+
|
|
1027
|
+
/** Runs one step; a failure or defect ends the frame. */
|
|
1028
|
+
const advance = (): Result.Result<Debug.StepOutcome, StepStop> => {
|
|
1029
|
+
const stop = unavailable()
|
|
1030
|
+
if (stop !== undefined) return Result.failure(stop)
|
|
1031
|
+
let result: Result.Result<Debug.StepOutcome, unknown>
|
|
1032
|
+
try {
|
|
1033
|
+
result = cursor!.next()
|
|
1034
|
+
} catch (defect) {
|
|
1035
|
+
ended = { defect }
|
|
1036
|
+
stepping = undefined
|
|
1037
|
+
return Result.failure({ reason: "defect", frame, error: defect })
|
|
1038
|
+
} finally {
|
|
1039
|
+
// Labels evaluated mid-frame are evaluated again for the world after this step.
|
|
1040
|
+
if (current.frame === frame) delete current.labels
|
|
1041
|
+
}
|
|
1042
|
+
if (!result.ok) {
|
|
1043
|
+
ended = { result: Result.failure(result.error) }
|
|
1044
|
+
stepping = undefined
|
|
1045
|
+
return Result.failure(failureStop(result.error, frame) as StepStop)
|
|
1046
|
+
}
|
|
1047
|
+
if (result.value.ended) stepping = undefined
|
|
1048
|
+
return Result.success(result.value)
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
const stepped: SteppedFrame<AnySystem> = {
|
|
1052
|
+
until: (system) => {
|
|
1053
|
+
const unavailableStop = unavailable()
|
|
1054
|
+
const left = remainingSteps()
|
|
1055
|
+
const offset = schedule.steps
|
|
1056
|
+
.slice(schedule.steps.length - left.length)
|
|
1057
|
+
.findIndex((entry) => "ordering" in entry && entry.ordering.key === system.ordering.key)
|
|
1058
|
+
const stop: StepStop | undefined = unavailableStop
|
|
1059
|
+
?? (offset === -1 ? { reason: "notAhead", frame, system: system.name, remaining: left } : undefined)
|
|
1060
|
+
if (stop !== undefined) return Rendered.make(Result.failure(stop), stopText(stop))
|
|
1061
|
+
const ran: Array<Debug.StepDescription> = []
|
|
1062
|
+
for (let index = 0; index < offset; index++) {
|
|
1063
|
+
const result = advance()
|
|
1064
|
+
if (!result.ok) return Rendered.make(Result.failure(result.error), stopText(result.error))
|
|
1065
|
+
ran.push(result.value.step)
|
|
1066
|
+
}
|
|
1067
|
+
const reached: StepReached = { frame, system: system.name, ran }
|
|
1068
|
+
return Rendered.make(
|
|
1069
|
+
Result.success(reached),
|
|
1070
|
+
`${head}: stopped before ${system.name}; ${ran.length === 0 ? "nothing ran" : `ran ${ran.map(Format.step).join(", ")}`}`
|
|
1071
|
+
)
|
|
1072
|
+
},
|
|
1073
|
+
next: () => {
|
|
1074
|
+
const result = advance()
|
|
1075
|
+
if (!result.ok) return Rendered.make(Result.failure(result.error), stopText(result.error))
|
|
1076
|
+
const ran: StepRan = { frame, step: result.value.step, ended: result.value.ended }
|
|
1077
|
+
return Rendered.make(Result.success(ran), `${head}: ran ${Format.step(ran.step)}; ${nextText()}`)
|
|
1078
|
+
},
|
|
1079
|
+
remaining: () => {
|
|
1080
|
+
const left = remainingSteps()
|
|
1081
|
+
return Rendered.make(left, left.length === 0
|
|
1082
|
+
? `${head}: no steps left; ${finished === undefined ? "finish() reports the frame" : "finished"}`
|
|
1083
|
+
: `${head}: ${left.length} steps left: ${left.map(Format.step).join(", ")}`)
|
|
1084
|
+
},
|
|
1085
|
+
check: () => {
|
|
1086
|
+
const at = remainingSteps()
|
|
1087
|
+
const where = at.length === 0 ? "at the end of the frame" : `before ${Format.step(at[0]!)}`
|
|
1088
|
+
const stop = checkInvariants(frame)
|
|
1089
|
+
if (stop === undefined) return Rendered.make(Result.success(undefined), `${head}: invariants hold ${where}`)
|
|
1090
|
+
const text = stop.reason === "invariant"
|
|
1091
|
+
? `${head}: INVARIANT "${stop.invariant}" violated ${where}: ${stop.message.replace(entityToken, (_token, id: string) => Format.entity(Number(id), nowLabels()))} (it may hold again by the end of the frame)`
|
|
1092
|
+
: `${head}: INVARIANT "${stop.invariant}" threw ${where}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`
|
|
1093
|
+
return Rendered.make(Result.failure(stop), text)
|
|
1094
|
+
},
|
|
1095
|
+
finish: () => {
|
|
1096
|
+
finished ??= runFrames(name, {}, start, () => {
|
|
1097
|
+
if (!begun.ok) return begun
|
|
1098
|
+
if (ended !== undefined) {
|
|
1099
|
+
if ("defect" in ended) throw ended.defect
|
|
1100
|
+
return ended.result
|
|
1101
|
+
}
|
|
1102
|
+
try {
|
|
1103
|
+
while (cursor!.remaining().length > 0) {
|
|
1104
|
+
const result = cursor!.next()
|
|
1105
|
+
if (!result.ok) return result
|
|
1106
|
+
}
|
|
1107
|
+
return Result.success(undefined)
|
|
1108
|
+
} finally {
|
|
1109
|
+
stepping = undefined
|
|
1110
|
+
}
|
|
1111
|
+
})
|
|
1112
|
+
return finished
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
return stepped
|
|
649
1116
|
}
|
|
650
1117
|
|
|
651
1118
|
/** Lines hidden by the last `collectLines` call because they record no change. */
|
|
652
1119
|
let hidden = 0
|
|
653
1120
|
|
|
654
|
-
const collectLines = (filter: JournalFilter<S>): Array<Format.Line> =>
|
|
1121
|
+
const collectLines = (filter: JournalFilter<S>): Array<Format.Line> => collectSourced(filter).map((entry) => entry.line)
|
|
1122
|
+
|
|
1123
|
+
/** The journal lines of `filter`, each with its event's position in {@link flatTrace}. */
|
|
1124
|
+
const collectSourced = (filter: JournalFilter<S>): Array<{ readonly line: Format.Line; readonly at: number }> => {
|
|
655
1125
|
hidden = 0
|
|
1126
|
+
refreshLabels()
|
|
656
1127
|
const subject = filter.component?.name ?? filter.resource?.name ?? filter.event?.name ?? filter.machine?.name
|
|
657
|
-
|
|
658
|
-
const
|
|
659
|
-
|
|
660
|
-
|
|
1128
|
+
// `slice(-last)` keeps the journal's meaning of `last` (0 keeps everything).
|
|
1129
|
+
const first = filter.last === undefined ? 0 : history.length - history.slice(-filter.last).length
|
|
1130
|
+
const result: Array<{ readonly line: Format.Line; readonly at: number }> = []
|
|
1131
|
+
let at = 0
|
|
1132
|
+
for (const [index, entry] of history.entries()) {
|
|
1133
|
+
if (index < first || !inRange(entry.frame, filter.frames)) {
|
|
1134
|
+
at += entry.events.length
|
|
1135
|
+
continue
|
|
1136
|
+
}
|
|
1137
|
+
const labels = labelsAt(entry.frame)
|
|
661
1138
|
for (const event of entry.events) {
|
|
662
|
-
|
|
1139
|
+
const position = at++
|
|
1140
|
+
for (const line of Format.lines(event, format, labels)) {
|
|
663
1141
|
if (filter.entity !== undefined && line.entity !== filter.entity) continue
|
|
664
1142
|
if (subject !== undefined && line.subject !== subject && !(line.kind === "effect" && line.subject === undefined && filter.entity !== undefined)) continue
|
|
665
1143
|
if (filter.system !== undefined && line.system !== filter.system) continue
|
|
@@ -669,7 +1147,7 @@ export const make = <
|
|
|
669
1147
|
hidden += 1
|
|
670
1148
|
continue
|
|
671
1149
|
}
|
|
672
|
-
result.push(line)
|
|
1150
|
+
result.push({ line, at: position })
|
|
673
1151
|
}
|
|
674
1152
|
}
|
|
675
1153
|
}
|
|
@@ -690,21 +1168,23 @@ export const make = <
|
|
|
690
1168
|
return Rendered.make(lines, renderLines(`journal: ${lines.length} lines (${rangeText()}${hiddenText})`, lines))
|
|
691
1169
|
}
|
|
692
1170
|
|
|
693
|
-
const why = (entity: number, component: Schema.ComponentDescriptor<S>, whyOptions:
|
|
694
|
-
const
|
|
1171
|
+
const why = (entity: number, component: Schema.ComponentDescriptor<S>, whyOptions: WhyOptions = {}) => {
|
|
1172
|
+
const sourced = collectSourced({ entity, component, kinds: ["write", "effect"], limit: whyOptions.limit ?? 5 })
|
|
1173
|
+
const lines = followReads(sourced, whyOptions)
|
|
695
1174
|
const currentValue = debug.dump({ entities: [entity] }).entities[0]
|
|
1175
|
+
const name = Format.entity(entity, nowLabels())
|
|
696
1176
|
const now = currentValue === undefined
|
|
697
|
-
?
|
|
1177
|
+
? `${name} is not alive`
|
|
698
1178
|
: component.name in currentValue.components
|
|
699
|
-
?
|
|
700
|
-
:
|
|
701
|
-
const changes =
|
|
1179
|
+
? `${name} ${component.name} is now ${Format.value(currentValue.components[component.name], format)}`
|
|
1180
|
+
: `${name} has no ${component.name} now`
|
|
1181
|
+
const changes = sourced.length === 0
|
|
702
1182
|
? `${now}; no change to it in ${rangeText()}`
|
|
703
|
-
: `${now}; last ${
|
|
1183
|
+
: `${now}; last ${sourced.length} changes (oldest first):`
|
|
704
1184
|
const spawners = spawnersOf(currentValue === undefined ? [component.name] : Object.keys(currentValue.components), component.name)
|
|
705
1185
|
const header = `${changes}\n${spawners.length === 0
|
|
706
1186
|
? `no described system declares spawns of ${component.name}`
|
|
707
|
-
: `could have spawned it: ${spawners.join(", ")}`}`
|
|
1187
|
+
: `could have spawned it: ${spawners.join(", ")}`}${readsNote(lines)}`
|
|
708
1188
|
return Rendered.make(lines, renderLines(header, lines))
|
|
709
1189
|
}
|
|
710
1190
|
|
|
@@ -722,18 +1202,275 @@ export const make = <
|
|
|
722
1202
|
.map((system) => system.name)
|
|
723
1203
|
}
|
|
724
1204
|
|
|
725
|
-
const whyResource = (resource: Schema.ResourceDescriptor<S>, whyOptions:
|
|
726
|
-
const lines =
|
|
1205
|
+
const whyResource = (resource: Schema.ResourceDescriptor<S>, whyOptions: WhyOptions = {}) => {
|
|
1206
|
+
const lines = followReads(collectSourced({ resource, kinds: ["resource"], limit: whyOptions.limit ?? 5 }), whyOptions)
|
|
727
1207
|
const resources = debug.dump({ limit: 0 }).resources
|
|
728
1208
|
const now = resource.name in resources
|
|
729
1209
|
? `${resource.name} is now ${Format.value(resources[resource.name], format)}`
|
|
730
1210
|
: `${resource.name} has no value now`
|
|
731
|
-
const
|
|
1211
|
+
const changes = lines.filter((line) => line.depth === 0).length
|
|
1212
|
+
const header = changes === 0
|
|
732
1213
|
? `${now}; no change to it in ${rangeText()}`
|
|
733
|
-
: `${now}; last ${
|
|
1214
|
+
: `${now}; last ${changes} changes (oldest first):${readsNote(lines)}`
|
|
734
1215
|
return Rendered.make(lines, renderLines(header, lines))
|
|
735
1216
|
}
|
|
736
1217
|
|
|
1218
|
+
/** The header note `why` adds when it printed declared reads. */
|
|
1219
|
+
const readsNote = (lines: ReadonlyArray<Format.Line>): string =>
|
|
1220
|
+
lines.some((line) => line.depth > 0)
|
|
1221
|
+
? "\nindented: what each writing system declared it reads, and the latest fact that could have produced it (declared: possible causes, not observed reads)"
|
|
1222
|
+
: ""
|
|
1223
|
+
|
|
1224
|
+
/** Every kept trace event, oldest first; {@link collectSourced} positions index into it. */
|
|
1225
|
+
const flatTrace = (): ReadonlyArray<Debug.TraceEvent> => history.flatMap((entry) => entry.events)
|
|
1226
|
+
|
|
1227
|
+
/**
|
|
1228
|
+
* The changes `why` lists, each followed (with `depth` above 1) by the
|
|
1229
|
+
* reads its system declared, depth first. Positions are in trace order, so
|
|
1230
|
+
* "before the run" is what the system could have seen.
|
|
1231
|
+
*/
|
|
1232
|
+
const followReads = (sourced: ReadonlyArray<{ readonly line: Format.Line; readonly at: number }>, whyOptions: WhyOptions): Array<Format.Line> => {
|
|
1233
|
+
const depth = whyOptions.depth ?? 1
|
|
1234
|
+
const limit = whyOptions.limit ?? 5
|
|
1235
|
+
if (depth <= 1 || sourced.length === 0) return sourced.map((entry) => entry.line)
|
|
1236
|
+
const trace = flatTrace()
|
|
1237
|
+
const systems = new Map(debug.describe().systems.map((entry) => [entry.name, entry] as const))
|
|
1238
|
+
let world: ReadonlyArray<Debug.EntityDump> | undefined
|
|
1239
|
+
const worldNow = () => (world ??= debug.dump().entities)
|
|
1240
|
+
|
|
1241
|
+
/** The latest committed run of `system` before `before`. */
|
|
1242
|
+
const runBefore = (system: string, before: number): { readonly at: number; readonly run: Debug.SystemEvent } | undefined => {
|
|
1243
|
+
for (let at = before - 1; at >= 0; at--) {
|
|
1244
|
+
const event = trace[at]!
|
|
1245
|
+
if (event.type === "system" && event.system === system && event.outcome === "ok") return { at, run: event }
|
|
1246
|
+
}
|
|
1247
|
+
return undefined
|
|
1248
|
+
}
|
|
1249
|
+
/** Where the stream reads of the run at `at` start: after the system's previous run, or the discarding skip. */
|
|
1250
|
+
const readsSince = (system: string, at: number): number => {
|
|
1251
|
+
for (let index = at - 1; index >= 0; index--) {
|
|
1252
|
+
const event = trace[index]!
|
|
1253
|
+
if ((event.type === "system" && event.system === system) || (event.type === "system.skipped" && event.system === system && !event.held)) return index + 1
|
|
1254
|
+
}
|
|
1255
|
+
return 0
|
|
1256
|
+
}
|
|
1257
|
+
const latest = <A>(before: number, find: (event: Debug.TraceEvent, at: number) => A | undefined): A | undefined => {
|
|
1258
|
+
for (let at = before - 1; at >= 0; at--) {
|
|
1259
|
+
const found = find(trace[at]!, at)
|
|
1260
|
+
if (found !== undefined) return found
|
|
1261
|
+
}
|
|
1262
|
+
return undefined
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
/** A run whose reads can be followed: the entity and component (or resource) it wrote, which its own reads skip. */
|
|
1266
|
+
interface Cause {
|
|
1267
|
+
readonly at: number
|
|
1268
|
+
readonly run: Debug.SystemEvent
|
|
1269
|
+
readonly entity: number | undefined
|
|
1270
|
+
readonly subject: string | undefined
|
|
1271
|
+
}
|
|
1272
|
+
interface Read {
|
|
1273
|
+
readonly frame: number
|
|
1274
|
+
readonly schedule: string
|
|
1275
|
+
readonly system: string | undefined
|
|
1276
|
+
readonly entity: number | undefined
|
|
1277
|
+
readonly subject: string
|
|
1278
|
+
readonly text: string
|
|
1279
|
+
readonly next: Cause | undefined
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
const readsOf = (cause: Cause): Array<Read> => {
|
|
1283
|
+
const { run } = cause
|
|
1284
|
+
const description = systems.get(run.system)
|
|
1285
|
+
const here = { frame: run.frame, schedule: run.schedule, system: undefined, entity: undefined, next: undefined }
|
|
1286
|
+
if (description === undefined) {
|
|
1287
|
+
return [{ ...here, subject: run.system, text: `${run.system} is in no named or described schedule: its declared reads are unknown` }]
|
|
1288
|
+
}
|
|
1289
|
+
const reads: Array<Read> = []
|
|
1290
|
+
const since = readsSince(run.system, cause.at)
|
|
1291
|
+
for (const name of description.events.reads) {
|
|
1292
|
+
const before = reads.length
|
|
1293
|
+
for (let at = since; at < cause.at; at++) {
|
|
1294
|
+
const event = trace[at]!
|
|
1295
|
+
if (event.type === "runtime.sent" && event.event === name) {
|
|
1296
|
+
reads.push({ ...here, frame: event.frame, schedule: "", subject: name, text: `read ${name} ${Format.value([event.value], format)} (declared), sent by runtime.send at f${event.frame}` })
|
|
1297
|
+
}
|
|
1298
|
+
if (event.type === "system" && event.outcome === "ok") {
|
|
1299
|
+
for (const emitted of event.events) {
|
|
1300
|
+
if (emitted.event !== name) continue
|
|
1301
|
+
reads.push({
|
|
1302
|
+
frame: event.frame,
|
|
1303
|
+
schedule: event.schedule,
|
|
1304
|
+
system: event.system,
|
|
1305
|
+
entity: undefined,
|
|
1306
|
+
subject: name,
|
|
1307
|
+
text: `read ${name} ${Format.value(emitted.values, format)} (declared), emitted by ${event.system} at f${event.frame}`,
|
|
1308
|
+
next: { at, run: event, entity: undefined, subject: undefined }
|
|
1309
|
+
})
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
if (reads.length === before) {
|
|
1314
|
+
reads.push({ ...here, subject: name, text: `read ${name} (declared): nothing published to it since ${run.system}'s previous run` })
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
for (const query of description.queries) {
|
|
1318
|
+
const components = [...query.reads, ...query.writes, ...query.optional]
|
|
1319
|
+
if (cause.entity !== undefined && cause.subject !== undefined && query.writes.includes(cause.subject)) {
|
|
1320
|
+
const entity = cause.entity
|
|
1321
|
+
for (const name of components.filter((component) => component !== cause.subject)) {
|
|
1322
|
+
reads.push(componentRead(cause, entity, name))
|
|
1323
|
+
}
|
|
1324
|
+
} else if (components.length > 0) {
|
|
1325
|
+
const required = [...query.reads, ...query.writes, ...query.with]
|
|
1326
|
+
const count = worldNow().filter((dumped) =>
|
|
1327
|
+
required.every((name) => name in dumped.components) && !query.without.some((name) => name in dumped.components)).length
|
|
1328
|
+
reads.push({
|
|
1329
|
+
...here,
|
|
1330
|
+
subject: components[0]!,
|
|
1331
|
+
text: `read ${components.join(", ")} of ${count} matching ${count === 1 ? "entity" : "entities"} now (declared; the trace does not say which it read)`
|
|
1332
|
+
})
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
for (const name of new Set([...description.resources.reads, ...description.resources.writes])) {
|
|
1336
|
+
if (name === cause.subject && cause.entity === undefined) continue
|
|
1337
|
+
const found = latest(cause.at, (event, at) => {
|
|
1338
|
+
if (event.type !== "system" || event.outcome !== "ok") return undefined
|
|
1339
|
+
// An equal-value write did not produce the value; the change before it did.
|
|
1340
|
+
const write = event.resources.find((entry) => entry.resource === name && !Format.sameValue(entry.before, entry.after))
|
|
1341
|
+
return write === undefined ? undefined : { at, event, write }
|
|
1342
|
+
})
|
|
1343
|
+
reads.push(found === undefined
|
|
1344
|
+
? { ...here, subject: name, text: `read resource ${name} (declared): no change to it in ${rangeText()}` }
|
|
1345
|
+
: {
|
|
1346
|
+
frame: found.event.frame,
|
|
1347
|
+
schedule: found.event.schedule,
|
|
1348
|
+
system: found.event.system,
|
|
1349
|
+
entity: undefined,
|
|
1350
|
+
subject: name,
|
|
1351
|
+
text: `read resource ${name} ${Format.value(found.write.after, format)} (declared), written by ${found.event.system} at f${found.event.frame}`,
|
|
1352
|
+
next: { at: found.at, run: found.event, entity: undefined, subject: name }
|
|
1353
|
+
})
|
|
1354
|
+
}
|
|
1355
|
+
for (const name of new Set([...description.machines.reads, ...description.machines.updates])) {
|
|
1356
|
+
const found = latest(cause.at, (event, at): Read | undefined => {
|
|
1357
|
+
if (event.type === "transition" && event.machine === name && (event.outcome === "applied" || event.outcome === "enterFailed")) {
|
|
1358
|
+
return { ...here, frame: event.frame, schedule: event.schedule, subject: name, text: `read machine ${name} (declared): transition ${Format.transition(event)} ${event.outcome} at f${event.frame}` }
|
|
1359
|
+
}
|
|
1360
|
+
if (event.type !== "system" || event.outcome !== "ok" || event.system === run.system) return undefined
|
|
1361
|
+
const write = event.machines.find((entry) => entry.machine === name)
|
|
1362
|
+
return write === undefined ? undefined : {
|
|
1363
|
+
frame: event.frame,
|
|
1364
|
+
schedule: event.schedule,
|
|
1365
|
+
system: event.system,
|
|
1366
|
+
entity: undefined,
|
|
1367
|
+
subject: name,
|
|
1368
|
+
text: `read machine ${name} ${Format.change(write.before, write.after, format)} (declared), updated by ${event.system} at f${event.frame}`,
|
|
1369
|
+
next: { at, run: event, entity: undefined, subject: undefined }
|
|
1370
|
+
}
|
|
1371
|
+
})
|
|
1372
|
+
reads.push(found ?? { ...here, subject: name, text: `read machine ${name} (declared): no transition in ${rangeText()}` })
|
|
1373
|
+
}
|
|
1374
|
+
if (reads.length === 0) reads.push({ ...here, subject: run.system, text: `${run.system} declares no other reads (declared)` })
|
|
1375
|
+
return reads
|
|
1376
|
+
}
|
|
1377
|
+
|
|
1378
|
+
/** The latest value of `component` on `entity` before the cause's run, and what produced it. */
|
|
1379
|
+
const componentRead = (cause: Cause, entity: number, component: string): Read => {
|
|
1380
|
+
const name = Format.entity(entity, labelsAt(cause.run.frame))
|
|
1381
|
+
const found = latest(cause.at, (event, at): Read | undefined => {
|
|
1382
|
+
if (event.type === "system" && event.outcome === "ok") {
|
|
1383
|
+
const write = event.writes.find((entry) => entry.entity === entity && entry.component === component && !Format.sameValue(entry.before, entry.after))
|
|
1384
|
+
return write === undefined ? undefined : {
|
|
1385
|
+
frame: event.frame,
|
|
1386
|
+
schedule: event.schedule,
|
|
1387
|
+
system: event.system,
|
|
1388
|
+
entity,
|
|
1389
|
+
subject: component,
|
|
1390
|
+
text: `read ${name} ${component} ${Format.value(write.after, format)} (declared), written by ${event.system} at f${event.frame}`,
|
|
1391
|
+
next: { at, run: event, entity, subject: component }
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
if (event.type !== "deferred") return undefined
|
|
1395
|
+
for (const command of [...event.commands].reverse()) {
|
|
1396
|
+
for (const effect of [...command.effects].reverse()) {
|
|
1397
|
+
if (effect.entity !== entity) continue
|
|
1398
|
+
const value = effect.kind === "spawn" ? (component in effect.components ? { found: effect.components[component] } : undefined)
|
|
1399
|
+
: effect.kind === "insert" && effect.component === component ? { found: effect.value }
|
|
1400
|
+
: effect.kind === "overwrite" && effect.component === component ? { found: effect.after }
|
|
1401
|
+
: undefined
|
|
1402
|
+
if (value === undefined) continue
|
|
1403
|
+
const queued = runBefore(command.system, at)
|
|
1404
|
+
return {
|
|
1405
|
+
frame: event.frame,
|
|
1406
|
+
schedule: event.schedule,
|
|
1407
|
+
system: command.system,
|
|
1408
|
+
entity,
|
|
1409
|
+
subject: component,
|
|
1410
|
+
text: `read ${name} ${component} ${Format.value(value.found, format)} (declared), ${effect.kind === "spawn" ? "spawned" : "inserted"} by ${command.system} at f${event.frame}`,
|
|
1411
|
+
next: queued === undefined ? undefined : { ...queued, entity: undefined, subject: undefined }
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
return undefined
|
|
1416
|
+
})
|
|
1417
|
+
return found ?? { frame: cause.run.frame, schedule: cause.run.schedule, system: undefined, entity, subject: component, text: `read ${name} ${component} (declared): no change to it in ${rangeText()}`, next: undefined }
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
const toLine = (read: Read, level: number, suffix: string): Format.Line => {
|
|
1421
|
+
const label = read.entity === undefined ? undefined : labelsAt(read.frame)?.get(read.entity)
|
|
1422
|
+
return {
|
|
1423
|
+
kind: "read",
|
|
1424
|
+
frame: read.frame,
|
|
1425
|
+
schedule: read.schedule,
|
|
1426
|
+
system: read.system,
|
|
1427
|
+
entity: read.entity,
|
|
1428
|
+
label: label === "" ? undefined : label,
|
|
1429
|
+
subject: read.subject,
|
|
1430
|
+
text: `${read.text}${suffix}`,
|
|
1431
|
+
noop: false,
|
|
1432
|
+
depth: level
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
const out: Array<Format.Line> = []
|
|
1437
|
+
const follow = (cause: Cause, level: number, chain: ReadonlySet<string>) => {
|
|
1438
|
+
const reads = readsOf(cause)
|
|
1439
|
+
for (const read of reads.slice(0, limit)) {
|
|
1440
|
+
const cycle = read.next !== undefined && chain.has(read.next.run.system)
|
|
1441
|
+
out.push(toLine(read, level, cycle ? " (cycle: not followed)" : ""))
|
|
1442
|
+
if (read.next !== undefined && !cycle && level + 1 < depth) follow(read.next, level + 1, new Set([...chain, read.next.run.system]))
|
|
1443
|
+
}
|
|
1444
|
+
if (reads.length > limit) {
|
|
1445
|
+
out.push({
|
|
1446
|
+
kind: "read",
|
|
1447
|
+
frame: cause.run.frame,
|
|
1448
|
+
schedule: cause.run.schedule,
|
|
1449
|
+
system: undefined,
|
|
1450
|
+
entity: undefined,
|
|
1451
|
+
label: undefined,
|
|
1452
|
+
subject: undefined,
|
|
1453
|
+
text: `…+${reads.length - limit} more declared reads of ${cause.run.system} (raise limit to see them)`,
|
|
1454
|
+
noop: false,
|
|
1455
|
+
depth: level
|
|
1456
|
+
})
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
/** The run behind a listed change: the writing run, or for an applied command the run that queued it. */
|
|
1460
|
+
const causeOf = (line: Format.Line, at: number): Cause | undefined => {
|
|
1461
|
+
const event = trace[at]
|
|
1462
|
+
if (event?.type === "system") return { at, run: event, entity: line.entity, subject: line.subject }
|
|
1463
|
+
const queued = event?.type === "deferred" && line.system !== undefined ? runBefore(line.system, at) : undefined
|
|
1464
|
+
return queued === undefined ? undefined : { ...queued, entity: undefined, subject: undefined }
|
|
1465
|
+
}
|
|
1466
|
+
for (const { line, at } of sourced) {
|
|
1467
|
+
out.push(line)
|
|
1468
|
+
const cause = causeOf(line, at)
|
|
1469
|
+
if (cause !== undefined) follow(cause, 1, new Set([cause.run.system]))
|
|
1470
|
+
}
|
|
1471
|
+
return out
|
|
1472
|
+
}
|
|
1473
|
+
|
|
737
1474
|
const statsFor = (system: string): SystemStats | undefined => {
|
|
738
1475
|
const entry = stats.get(system)
|
|
739
1476
|
return entry === undefined ? undefined : { system, ...entry }
|
|
@@ -766,7 +1503,10 @@ export const make = <
|
|
|
766
1503
|
frames: debug.frame(),
|
|
767
1504
|
history: historyRange(),
|
|
768
1505
|
systems,
|
|
769
|
-
warnings: [...warnings.values()].map((warning) => ({
|
|
1506
|
+
warnings: [...warnings.values()].map((warning) => ({
|
|
1507
|
+
...warning,
|
|
1508
|
+
message: typeof warning.message === "string" ? warning.message : warning.message(labelsAt(warning.firstFrame))
|
|
1509
|
+
})),
|
|
770
1510
|
streams: debug.streams().filter((stream) => stream.heldBy !== undefined || stream.readers.some((reader) => reader.lagged)),
|
|
771
1511
|
lints: debug.describe().lints,
|
|
772
1512
|
population: debug.population()
|
|
@@ -790,6 +1530,7 @@ export const make = <
|
|
|
790
1530
|
|
|
791
1531
|
return {
|
|
792
1532
|
run,
|
|
1533
|
+
step: step as Session<S, Names, Schedules>["step"],
|
|
793
1534
|
journal,
|
|
794
1535
|
why,
|
|
795
1536
|
whyResource,
|
|
@@ -800,7 +1541,7 @@ export const make = <
|
|
|
800
1541
|
},
|
|
801
1542
|
dump: (filter) => {
|
|
802
1543
|
const dumped = debug.dump(filter)
|
|
803
|
-
return Rendered.make(dumped, Format.dump(dumped, format))
|
|
1544
|
+
return Rendered.make(dumped, Format.dump(dumped, format, nowLabels()))
|
|
804
1545
|
},
|
|
805
1546
|
streams: () => {
|
|
806
1547
|
const status = debug.streams()
|
|
@@ -815,7 +1556,7 @@ export const make = <
|
|
|
815
1556
|
}
|
|
816
1557
|
}
|
|
817
1558
|
|
|
818
|
-
const renderRun = (result: RunResult, format: Format.ValueOptions): string => {
|
|
1559
|
+
const renderRun = (result: RunResult, format: Format.ValueOptions, labels: Format.Labels | undefined): string => {
|
|
819
1560
|
const frames = result.range === undefined ? "no frames" : `f${result.range[0]}-f${result.range[1]}`
|
|
820
1561
|
const head = `run ${result.schedule}: ${result.frames} frames (${frames}) in ${Format.value(result.ms)}ms`
|
|
821
1562
|
const stop = result.stop
|
|
@@ -831,9 +1572,11 @@ const renderRun = (result: RunResult, format: Format.ValueOptions): string => {
|
|
|
831
1572
|
case "defect":
|
|
832
1573
|
return `${head}, DEFECT at f${stop.frame}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`
|
|
833
1574
|
case "invariant":
|
|
834
|
-
return `${head}, INVARIANT "${stop.invariant}" violated at f${stop.frame}: ${stop.message}`
|
|
1575
|
+
return `${head}, INVARIANT "${stop.invariant}" violated at f${stop.frame}: ${stop.message.replace(entityToken, (_token, id: string) => Format.entity(Number(id), labels))}`
|
|
835
1576
|
case "invariant-threw":
|
|
836
1577
|
return `${head}, INVARIANT "${stop.invariant}" threw at f${stop.frame}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`
|
|
1578
|
+
case "labels-threw":
|
|
1579
|
+
return `${head}, LABELS threw at f${stop.frame}: ${stop.error instanceof Error ? stop.error.stack ?? stop.error.message : Format.value(stop.error, format)}`
|
|
837
1580
|
case "tickOrder":
|
|
838
1581
|
return `${head}, NOT RUN after f${stop.frame}: ${stop.issues.join("; ")}`
|
|
839
1582
|
case "ignored-failure":
|