@operad-io/dev 0.1.1 → 0.2.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/src/schedule.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  * plan is finished. Scheduling lives here, not in the kernel (ADR 0002 D1).
5
5
  */
6
6
 
7
+ import { isRecord, messageOf } from "@operad-io/engine";
7
8
  import { DEFAULT_POOL } from "@operad-io/pool";
8
9
  import { readFileSync } from "node:fs";
9
10
  import { join } from "node:path";
@@ -16,7 +17,7 @@ import {
16
17
  type TickContext,
17
18
  } from "@operad-io/engine";
18
19
  import {
19
- bareId,
20
+ idOfKey,
20
21
  changeClock,
21
22
  dependencyKey,
22
23
  dependencyLabel,
@@ -50,6 +51,7 @@ import {
50
51
  import { loadProjectFlows, PROJECT_FLOWS_DIR } from "./project-flows.ts";
51
52
  import { collectFollowups } from "./followups.ts";
52
53
  import { missingPlugins } from "./standing.ts";
54
+ import { checkHostWarning } from "./check-host.ts";
53
55
  import {
54
56
  compileDevFlow,
55
57
  DEFAULT_FLOW_NAME,
@@ -68,6 +70,8 @@ import {
68
70
  /** Where a scheduler change goes: the kernel loop's output. */
69
71
  export const schedulerTestHooks: {
70
72
  write?: ((line: string) => void) | undefined;
73
+ /** Called before a generated flow is handed to the kernel; a test counts them. */
74
+ declare?: ((flow: FlowDefinition) => void) | undefined;
71
75
  } = {};
72
76
 
73
77
  export function writeSchedulerLine(line: string): void {
@@ -97,6 +101,76 @@ interface RepositoryFlows {
97
101
  readonly refused: ReadonlyMap<string, string>;
98
102
  }
99
103
 
104
+ /** The compiled settings flows of one repository, keyed by the settings' content. */
105
+ interface CompiledFlows {
106
+ readonly starts: ReadonlyMap<string, StartFlow>;
107
+ }
108
+
109
+ /** The compiled settings flows of each store's repositories, by repository name. */
110
+ const compiledFlows = new WeakMap<ObjectStore, Map<string, { readonly key: string; readonly value: CompiledFlows }>>();
111
+
112
+ /** The content-addressed flow names this process already declared in a store. */
113
+ const declaredFlowNames = new WeakMap<ObjectStore, Set<string>>();
114
+
115
+ function settingsKey(settings: DevSettings): string {
116
+ return JSON.stringify(settings);
117
+ }
118
+
119
+ /** Compiles a repository's settings flows once for each settings text. */
120
+ function compiledSettingsFlows(
121
+ store: ObjectStore,
122
+ repository: RepositoryData,
123
+ settings: DevSettings,
124
+ ): CompiledFlows {
125
+ let byRepository = compiledFlows.get(store);
126
+ if (byRepository === undefined) {
127
+ byRepository = new Map();
128
+ compiledFlows.set(store, byRepository);
129
+ }
130
+ const key = `${repository.name}\n${settingsKey(settings)}`;
131
+ const kept = byRepository.get(repository.name);
132
+ if (kept !== undefined && kept.key === key) return kept.value;
133
+ const starts = new Map<string, StartFlow>();
134
+ for (const [flowName, spec] of Object.entries(settings.flows)) {
135
+ const name = flowNameFor(repository.name, flowName, spec);
136
+ starts.set(flowName, {
137
+ name,
138
+ graph: compileDevFlow(name, spec.stages, { gradingName: flowName }),
139
+ });
140
+ }
141
+ const value = { starts };
142
+ byRepository.set(repository.name, { key, value });
143
+ return value;
144
+ }
145
+
146
+ /** A generated name carries a hash of its graph; the built-in `dev` does not. */
147
+ function contentAddressed(name: string): boolean {
148
+ return /^dev\/[^/]+\/[^/]+\/[0-9a-f]{12}$/.test(name);
149
+ }
150
+
151
+ /**
152
+ * Declares a content-addressed flow once per store in this process. The set
153
+ * lives beside the store object, so it serves an in-memory store as well as a
154
+ * file store; a later process starts its own set.
155
+ */
156
+ function declareFlowOnce(ctx: TickContext, graph: FlowDefinition): void {
157
+ const name = graph.name;
158
+ if (contentAddressed(name)) {
159
+ let declared = declaredFlowNames.get(ctx.store);
160
+ if (declared?.has(name)) return;
161
+ schedulerTestHooks.declare?.(graph);
162
+ ctx.declareFlow(graph);
163
+ if (declared === undefined) {
164
+ declared = new Set();
165
+ declaredFlowNames.set(ctx.store, declared);
166
+ }
167
+ declared.add(name);
168
+ return;
169
+ }
170
+ schedulerTestHooks.declare?.(graph);
171
+ ctx.declareFlow(graph);
172
+ }
173
+
100
174
  /**
101
175
  * Declares every flow the repository sets. A repository that writes no `flows`
102
176
  * runs the built-in `dev` flow, so its old runs and tests keep their ids.
@@ -110,24 +184,20 @@ async function declareRepositoryFlows(
110
184
  let fallback: StartFlow = { name: DEFAULT_FLOW_NAME };
111
185
  const project = await loadProjectFlows(repository.path, repository.name, settings);
112
186
  const refused = new Map(project.refused);
113
- for (const [flowName, spec] of Object.entries(settings.flows)) {
187
+ const compiled = compiledSettingsFlows(ctx.store, repository, settings);
188
+ for (const [flowName, start] of compiled.starts) {
114
189
  if (refused.has(flowName)) continue;
115
- const name = flowNameFor(repository.name, flowName, spec);
116
- const start = {
117
- name,
118
- graph: compileDevFlow(name, spec.stages, { gradingName: flowName }),
119
- };
120
- ctx.declareFlow(start.graph);
190
+ if (start.graph !== undefined) declareFlowOnce(ctx, start.graph);
121
191
  named.set(flowName, start);
122
192
  if (flowName === "default") fallback = start;
123
193
  }
124
194
  for (const [flowName, graph] of project.flows) {
125
195
  try {
126
- ctx.declareFlow(graph);
196
+ declareFlowOnce(ctx, graph);
127
197
  } catch (error) {
128
198
  refused.set(
129
199
  flowName,
130
- `${PROJECT_FLOWS_DIR}/${flowName}.flow.ts: ${error instanceof Error ? error.message : String(error)}`,
200
+ `${PROJECT_FLOWS_DIR}/${flowName}.flow.ts: ${messageOf(error)}`,
131
201
  );
132
202
  continue;
133
203
  }
@@ -162,15 +232,48 @@ function reportFlowProblem(
162
232
  if (reportedFlowProblems.get(id) === wanted) return;
163
233
  reportedFlowProblems.set(id, wanted);
164
234
  writeSchedulerLine(
165
- `${bareId(id)} ready -> ready (${refused ?? `no flow "${wanted}" in dev.json`})`,
235
+ `${idOfKey(id)} ready -> ready (${refused ?? `no flow "${wanted}" in dev.json`})`,
166
236
  );
167
237
  }
168
238
 
169
- /** Re-declares the graph every task started with, so a fresh process resumes it. */
239
+ /** What the scheduler last said about each task whose recorded graph is refused. */
240
+ const reportedStoredFlows = new Map<string, string>();
241
+
242
+ /**
243
+ * Declares the graph a task started with. False when the task has none, or
244
+ * when today's steps refuse it: a graph recorded by an older dev may lack an
245
+ * edge for a result a step has since gained. The refusal is said once per
246
+ * task and reason, and only that task loses its recorded graph; the
247
+ * repository's other tasks are still scheduled.
248
+ */
249
+ function declareStoredFlow(ctx: TickContext, object: StoredObject): boolean {
250
+ const graph = taskData(object.data).flowGraph;
251
+ if (graph === undefined) return false;
252
+ try {
253
+ declareFlowOnce(ctx, graph);
254
+ reportedStoredFlows.delete(object.id);
255
+ return true;
256
+ } catch (error) {
257
+ const reason = messageOf(error);
258
+ if (reportedStoredFlows.get(object.id) !== reason) {
259
+ reportedStoredFlows.set(object.id, reason);
260
+ writeSchedulerLine(
261
+ `${idOfKey(object.id)} keeps no recorded flow: ${reason}; a new start uses the repository's flow`,
262
+ );
263
+ }
264
+ return false;
265
+ }
266
+ }
267
+
268
+ /**
269
+ * Re-declares the graph every open task started with, so a fresh process
270
+ * resumes it. A merged or cancelled task runs nothing again.
271
+ */
170
272
  function declareStoredFlows(ctx: TickContext, tasks: readonly StoredObject[]): void {
171
273
  for (const object of tasks) {
172
- const graph = taskData(object.data).flowGraph;
173
- if (graph !== undefined) ctx.declareFlow(graph);
274
+ const phase = taskData(object.data).phase;
275
+ if (phase === "merged" || phase === "cancelled") continue;
276
+ declareStoredFlow(ctx, object);
174
277
  }
175
278
  }
176
279
 
@@ -194,7 +297,7 @@ function plansOf(
194
297
 
195
298
  /**
196
299
  * Whether a task's flow has a configured human stage that no review stage
197
- * comes before, and the work and check before it finished well: the wait the
300
+ * comes before, and the code and test before it finished well: the wait the
198
301
  * task is in is that stage. A review before the human stage is answered
199
302
  * through its pass; a review after it has not run yet at that wait.
200
303
  */
@@ -286,7 +389,7 @@ function orderPlans(plans: readonly StoredObject[]): readonly StoredObject[] {
286
389
  const byPriority =
287
390
  priorityIndex(leftPlan.priority) - priorityIndex(rightPlan.priority);
288
391
  if (byPriority !== 0) return byPriority;
289
- return bareId(left.id).localeCompare(bareId(right.id));
392
+ return idOfKey(left.id).localeCompare(idOfKey(right.id));
290
393
  });
291
394
  }
292
395
 
@@ -331,10 +434,7 @@ function storedGraphPool(graph: FlowDefinition | undefined): string | undefined
331
434
  if (typeof outer !== "object" || outer === null) continue;
332
435
  const { use, params } = outer as { use?: unknown; params?: unknown };
333
436
  if (use !== "dev/work") continue;
334
- const pool: unknown =
335
- typeof params === "object" && params !== null
336
- ? (params as { flowPool?: unknown }).flowPool
337
- : undefined;
437
+ const pool: unknown = isRecord(params) ? params.flowPool : undefined;
338
438
  return typeof pool === "string" ? pool : DEFAULT_POOL;
339
439
  }
340
440
  return undefined;
@@ -359,8 +459,11 @@ async function startOne(
359
459
  fallbackFlow: StartFlow = { name: DEFAULT_FLOW_NAME },
360
460
  ): Promise<boolean> {
361
461
  const stored = taskData(object.data);
462
+ // A recorded graph today's steps refuse cannot run; the start takes the
463
+ // repository's flow and records that one instead.
362
464
  const flow =
363
- stored.flowName !== undefined
465
+ stored.flowName !== undefined &&
466
+ (stored.flowGraph === undefined || declareStoredFlow(ctx, object))
364
467
  ? { name: stored.flowName, graph: stored.flowGraph }
365
468
  : fallbackFlow;
366
469
  // A task that started before the repository's flow changed keeps the graph
@@ -399,7 +502,8 @@ async function startOne(
399
502
  async function reportIntegrationResults(
400
503
  store: ObjectStore,
401
504
  tasks: readonly StoredObject[],
402
- ): Promise<void> {
505
+ ): Promise<boolean> {
506
+ let changed = false;
403
507
  for (const object of tasks) {
404
508
  const task = taskData(object.data);
405
509
  const attempt = task.attempt;
@@ -414,8 +518,10 @@ async function reportIntegrationResults(
414
518
  else if (result === "conflict" || result === "fail") phase = "running";
415
519
  if (phase === undefined) continue;
416
520
  if (!(await recordMergeReported(store, object.id, attempt.number))) continue;
417
- writeSchedulerLine(`${bareId(object.id)} integrating -> ${phase}`);
521
+ changed = true;
522
+ writeSchedulerLine(`${idOfKey(object.id)} integrating -> ${phase}`);
418
523
  }
524
+ return changed;
419
525
  }
420
526
 
421
527
  /** Marks a plan finished once, when every task has merged or been cancelled. */
@@ -429,7 +535,7 @@ async function reportFinishedPlans(
429
535
  if (plan.status !== "confirmed" || plan.finishedReported === true) {
430
536
  continue;
431
537
  }
432
- const mine = planTasks(tasks, bareId(object.id));
538
+ const mine = planTasks(tasks, idOfKey(object.id));
433
539
  if (mine.length === 0) continue;
434
540
  const finished = mine.every((task) => {
435
541
  const phase = taskData(task.data).phase;
@@ -437,7 +543,7 @@ async function reportFinishedPlans(
437
543
  });
438
544
  if (!finished) continue;
439
545
  if (!(await recordPlanFinishedReported(store, object.id))) continue;
440
- writeSchedulerLine(`${bareId(object.id)} confirmed -> finished`);
546
+ writeSchedulerLine(`${idOfKey(object.id)} confirmed -> finished`);
441
547
  }
442
548
  }
443
549
 
@@ -479,9 +585,10 @@ async function reconcileTaskRuns(
479
585
  tasks: readonly StoredObject[],
480
586
  canStartWork: boolean,
481
587
  flows: RepositoryFlows,
482
- ): Promise<void> {
588
+ ): Promise<boolean> {
483
589
  const runs = ctx.runLookup;
484
- if (runs === undefined) return;
590
+ if (runs === undefined) return false;
591
+ let changed = false;
485
592
  for (const object of tasksOf(tasks, repository)) {
486
593
  const task = taskData(object.data);
487
594
  if (task.phase !== "waiting" && task.phase !== "running" && task.phase !== "review") {
@@ -497,7 +604,8 @@ async function reconcileTaskRuns(
497
604
  run: run.runId,
498
605
  });
499
606
  if (moved === undefined) continue;
500
- writeSchedulerLine(`${bareId(object.id)} ${task.phase} -> waiting`);
607
+ changed = true;
608
+ writeSchedulerLine(`${idOfKey(object.id)} ${task.phase} -> waiting`);
501
609
  }
502
610
  continue;
503
611
  }
@@ -511,7 +619,8 @@ async function reconcileTaskRuns(
511
619
  const plan = await ctx.store.get("plan", storeKey(task.repository, task.plan));
512
620
  const requested = task.flow ?? (plan === undefined ? undefined : planData(plan.data).flow);
513
621
  const selected =
514
- task.flowName !== undefined
622
+ task.flowName !== undefined &&
623
+ (task.flowGraph === undefined || declareStoredFlow(ctx, object))
515
624
  ? { name: task.flowName, graph: task.flowGraph }
516
625
  : flowFor(flows, requested);
517
626
  if (selected === undefined) {
@@ -526,22 +635,25 @@ async function reconcileTaskRuns(
526
635
  run: null,
527
636
  });
528
637
  if (moved !== undefined) {
529
- writeSchedulerLine(`${bareId(object.id)} ${task.phase} -> waiting (${reason})`);
638
+ changed = true;
639
+ writeSchedulerLine(`${idOfKey(object.id)} ${task.phase} -> waiting (${reason})`);
530
640
  }
531
641
  }
532
642
  continue;
533
643
  }
534
644
  if ((await reopenTask(ctx.store, object.id)) === undefined) continue;
645
+ changed = true;
535
646
  try {
536
647
  if (await startOne(ctx, object, { runStoppedAt: step ?? "the run" }, false, selected)) {
537
648
  writeSchedulerLine(
538
- `${bareId(object.id)} ${task.phase} -> waiting (run stopped during ${step ?? "the run"})`,
649
+ `${idOfKey(object.id)} ${task.phase} -> waiting (run stopped during ${step ?? "the run"})`,
539
650
  );
540
651
  }
541
652
  } catch (error) {
542
653
  if (!(error instanceof ActiveRunError)) throw error;
543
654
  }
544
655
  }
656
+ return changed;
545
657
  }
546
658
 
547
659
  /** What the scheduler last said about each repository's settings file. */
@@ -572,12 +684,68 @@ function reportSettingsProblem(repository: RepositoryData): void {
572
684
  console.error(`dev: repository "${repository.name}": ${problem}`);
573
685
  }
574
686
 
687
+ /** What the scheduler last said about each repository's test host. */
688
+ const reportedCheckHosts = new Map<string, string>();
689
+
690
+ /**
691
+ * Says once per change that a repository's check commands use
692
+ * `remote-check.sh` while no test host is set. The commands run here,
693
+ * so a person must know before the checks do; a host that is set later clears
694
+ * the line, and losing it again says it once more.
695
+ */
696
+ function reportCheckHostProblem(
697
+ ctx: TickContext,
698
+ repository: RepositoryData,
699
+ settings: DevSettings,
700
+ ): void {
701
+ const warning = checkHostWarning(repository.name, settings, ctx.settings);
702
+ if (warning === undefined) {
703
+ reportedCheckHosts.delete(repository.path);
704
+ return;
705
+ }
706
+ if (reportedCheckHosts.get(repository.path) === warning) return;
707
+ reportedCheckHosts.set(repository.path, warning);
708
+ console.error(`dev: ${warning}`);
709
+ }
710
+
711
+ /** The tasks and plans one pass reads, and the tasks it refreshes after a write. */
712
+ interface PassSnapshot {
713
+ readonly store: ObjectStore;
714
+ tasks: StoredObject[];
715
+ readonly plans: readonly StoredObject[];
716
+ }
717
+
718
+ /** Replaces one repository's tasks in the pass snapshot; other repositories stay as read. */
719
+ async function refreshRepositoryTasks(
720
+ snapshot: PassSnapshot,
721
+ repository: string,
722
+ ): Promise<void> {
723
+ const fresh = await listAll(snapshot.store, "task", { repository });
724
+ snapshot.tasks = [
725
+ ...snapshot.tasks.filter(
726
+ (object) => taskData(object.data).repository !== repository,
727
+ ),
728
+ ...fresh,
729
+ ];
730
+ }
731
+
732
+ /** The versions of a plan's tasks, so an unchanged finished plan is left alone. */
733
+ const planTaskSignatures = new WeakMap<ObjectStore, Map<string, string>>();
734
+
735
+ function taskSignature(tasks: readonly StoredObject[]): string {
736
+ return tasks
737
+ .map((object) => `${object.id}:${object.version}`)
738
+ .sort()
739
+ .join("\n");
740
+ }
741
+
575
742
  async function scheduleRepository(
576
743
  ctx: TickContext,
577
744
  repository: RepositoryData,
578
- initialTasks: readonly StoredObject[],
579
- initialPlans: readonly StoredObject[],
745
+ snapshot: PassSnapshot,
580
746
  ): Promise<void> {
747
+ let dirty = false;
748
+ const initialTasks = tasksOf(snapshot.tasks, repository.name);
581
749
  reportSettingsProblem(repository);
582
750
  // A cancelled task's run ends whether or not the settings can be read.
583
751
  if (ctx.runLookup !== undefined) {
@@ -591,6 +759,7 @@ async function scheduleRepository(
591
759
  // here may touch the repository's running steps.
592
760
  return;
593
761
  }
762
+ reportCheckHostProblem(ctx, repository, settings);
594
763
  // Work needs the plugins dev runs its steps through; without them a task
595
764
  // stays ready instead of failing.
596
765
  const canStartWork = missingPlugins(ctx.loaded).length === 0;
@@ -599,11 +768,18 @@ async function scheduleRepository(
599
768
  // and a graph recorded there is declared again below so a fresh process
600
769
  // resumes a running attempt on the graph it started with.
601
770
  const flows = await declareRepositoryFlows(ctx, repository, settings);
602
- declareStoredFlows(ctx, initialTasks);
771
+ declareStoredFlows(ctx, tasksOf(snapshot.tasks, repository.name));
603
772
 
604
773
  // Repair a run that ended without an edge, or one whose phase was left
605
774
  // behind, before the scheduler reads phases and starts anything else.
606
- await reconcileTaskRuns(ctx, repository.name, initialTasks, canStartWork, flows);
775
+ dirty =
776
+ (await reconcileTaskRuns(
777
+ ctx,
778
+ repository.name,
779
+ tasksOf(snapshot.tasks, repository.name),
780
+ canStartWork,
781
+ flows,
782
+ )) || dirty;
607
783
 
608
784
  // A claim is not durable until the kernel records the run. A task left
609
785
  // running with no run is a start that never landed (a crash or a kernel
@@ -613,7 +789,7 @@ async function scheduleRepository(
613
789
  // A claim whose run the kernel already holds is a start still landing: the
614
790
  // run's first step records its id moments later. Releasing it would cancel
615
791
  // that run and start another one on the next tick, forever.
616
- for (const object of tasksOf(initialTasks, repository.name)) {
792
+ for (const object of tasksOf(snapshot.tasks, repository.name)) {
617
793
  const task = taskData(object.data);
618
794
  if ((task.phase !== "running" && task.phase !== "review") || task.run !== null) continue;
619
795
  if (
@@ -623,28 +799,37 @@ async function scheduleRepository(
623
799
  continue;
624
800
  }
625
801
  if ((await releaseTaskClaim(ctx.store, object.id)) === undefined) continue;
626
- writeSchedulerLine(`${bareId(object.id)} running -> ready`);
802
+ dirty = true;
803
+ writeSchedulerLine(`${idOfKey(object.id)} running -> ready`);
627
804
  }
628
805
 
629
806
  // Findings that did not fail a review become one follow-up task once the
630
807
  // plan has no open task; this runs before a plan can be reported finished.
631
- await collectFollowups(ctx.store, repository.name, settings);
808
+ const followupsPending = snapshot.tasks.some((object) => {
809
+ const task = taskData(object.data);
810
+ return task.repository === repository.name && task.followups?.state === "collect";
811
+ });
812
+ await collectFollowups(ctx.store, repository.name, settings, snapshot.tasks);
813
+ if (followupsPending) dirty = true;
632
814
 
633
815
  // A recovered claim changes the store; read the phases again before counting.
634
- const allCurrent = await listAll(ctx.store, "task");
635
- const current = tasksOf(allCurrent, repository.name);
636
- const plans = orderPlans(plansOf(initialPlans, repository.name));
816
+ if (dirty) {
817
+ await refreshRepositoryTasks(snapshot, repository.name);
818
+ dirty = false;
819
+ }
820
+ const current = tasksOf(snapshot.tasks, repository.name);
821
+ const plans = orderPlans(plansOf(snapshot.plans, repository.name));
637
822
  const tasksById = new Map(
638
- allCurrent.map((object) => [object.id, taskData(object.data)]),
823
+ snapshot.tasks.map((object) => [object.id, taskData(object.data)]),
639
824
  );
640
825
  declareStoredFlows(ctx, current);
641
826
 
642
- await reportIntegrationResults(ctx.store, current);
827
+ dirty = (await reportIntegrationResults(ctx.store, current)) || dirty;
643
828
  await reportFinishedPlans(ctx.store, plans, current);
644
829
 
645
830
  const planActive = new Map<string, number>();
646
831
  for (const planObject of plans) {
647
- const id = bareId(planObject.id);
832
+ const id = idOfKey(planObject.id);
648
833
  planActive.set(
649
834
  id,
650
835
  planTasks(current, id).filter((object) =>
@@ -656,7 +841,7 @@ async function scheduleRepository(
656
841
  isActive(taskData(object.data)),
657
842
  ).length;
658
843
  // A task counts against the pool of the flow it runs.
659
- const plansByName = new Map(plans.map((object) => [bareId(object.id), planData(object.data)]));
844
+ const plansByName = new Map(plans.map((object) => [idOfKey(object.id), planData(object.data)]));
660
845
  // A task that has started runs the graph it started with, so its pool is
661
846
  // that graph's; dev.json changing meanwhile does not move it.
662
847
  const poolOf = (task: TaskData): string =>
@@ -675,7 +860,7 @@ async function scheduleRepository(
675
860
  for (const object of current) {
676
861
  const task = taskData(object.data);
677
862
  if (task.area !== undefined && isActive(task) && !areaActive.has(task.area)) {
678
- areaActive.set(task.area, bareId(object.id));
863
+ areaActive.set(task.area, idOfKey(object.id));
679
864
  }
680
865
  }
681
866
 
@@ -683,17 +868,17 @@ async function scheduleRepository(
683
868
  const oldestPlanHeld = new Set<string>();
684
869
  const lastStarted = new Map<string, number>(
685
870
  plans.map((object) => [
686
- bareId(object.id),
871
+ idOfKey(object.id),
687
872
  planData(object.data).lastStartedAt ?? 0,
688
873
  ]),
689
874
  );
690
875
  const turnOf = (object: StoredObject): number =>
691
- lastStarted.get(bareId(object.id)) ?? 0;
876
+ lastStarted.get(idOfKey(object.id)) ?? 0;
692
877
  const byUrgency = (left: StoredObject, right: StoredObject): number =>
693
878
  priorityIndex(planData(left.data).priority) -
694
879
  priorityIndex(planData(right.data).priority);
695
880
  const byId = (left: StoredObject, right: StoredObject): number =>
696
- bareId(left.id).localeCompare(bareId(right.id));
881
+ idOfKey(left.id).localeCompare(idOfKey(right.id));
697
882
  /** Priority first; within one priority the plan that started longest ago. */
698
883
  const turnOrder = (): readonly StoredObject[] =>
699
884
  [...plans].sort(
@@ -751,7 +936,7 @@ async function scheduleRepository(
751
936
  const scoped = (planObject: StoredObject): readonly StoredObject[] => {
752
937
  const plan = planData(planObject.data);
753
938
  if (plan.status !== "confirmed") return [];
754
- return planTasks(current, bareId(planObject.id))
939
+ return planTasks(current, idOfKey(planObject.id))
755
940
  .filter((object) => {
756
941
  const task = taskData(object.data);
757
942
  return task.phase === "ready" && inScope(task, plan);
@@ -776,7 +961,8 @@ async function scheduleRepository(
776
961
  if (
777
962
  await startOne(ctx, object, { blockedBy: dependencies.cancelled }, false, selected)
778
963
  ) {
779
- writeSchedulerLine(`${bareId(object.id)} ready -> waiting`);
964
+ dirty = true;
965
+ writeSchedulerLine(`${idOfKey(object.id)} ready -> waiting`);
780
966
  started.add(object.id);
781
967
  }
782
968
  }
@@ -788,7 +974,7 @@ async function scheduleRepository(
788
974
  let progress = false;
789
975
  for (const planObject of order) {
790
976
  const plan = planData(planObject.data);
791
- const planId = bareId(planObject.id);
977
+ const planId = idOfKey(planObject.id);
792
978
  const pick = scoped(planObject).find(
793
979
  (object) =>
794
980
  !failed.has(object.id) && canStart(object, plan, planId),
@@ -806,13 +992,14 @@ async function scheduleRepository(
806
992
  failed.add(pick.id);
807
993
  break;
808
994
  }
995
+ dirty = true;
809
996
  const task = taskData(pick.data);
810
- writeSchedulerLine(`${bareId(pick.id)} ready -> running`);
997
+ writeSchedulerLine(`${idOfKey(pick.id)} ready -> running`);
811
998
  planActive.set(planId, (planActive.get(planId) ?? 0) + 1);
812
999
  repositoryActive += 1;
813
1000
  const startedPool = poolOf(task);
814
1001
  poolActive.set(startedPool, (poolActive.get(startedPool) ?? 0) + 1);
815
- if (task.area !== undefined) areaActive.set(task.area, bareId(pick.id));
1002
+ if (task.area !== undefined) areaActive.set(task.area, idOfKey(pick.id));
816
1003
  started.add(pick.id);
817
1004
  if (useOldestPlan) oldestPlanHeld.add(pick.id);
818
1005
  const at = changeClock.now();
@@ -828,7 +1015,7 @@ async function scheduleRepository(
828
1015
  const plan = planData(planObject.data);
829
1016
  if (plan.status !== "confirmed" || plan.auto !== "merge") continue;
830
1017
 
831
- for (const object of planTasks(current, bareId(planObject.id))) {
1018
+ for (const object of planTasks(current, idOfKey(planObject.id))) {
832
1019
  const task = taskData(object.data);
833
1020
  const attempt = task.attempt;
834
1021
  if (!autoMergeWaits(task) || attempt === undefined || task.run === null) {
@@ -842,7 +1029,8 @@ async function scheduleRepository(
842
1029
  continue;
843
1030
  }
844
1031
  await recordAutoMerge(ctx.store, object.id, attempt.number);
845
- writeSchedulerLine(`${bareId(object.id)} waiting -> integrating`);
1032
+ dirty = true;
1033
+ writeSchedulerLine(`${idOfKey(object.id)} waiting -> integrating`);
846
1034
  }
847
1035
  }
848
1036
 
@@ -850,7 +1038,7 @@ async function scheduleRepository(
850
1038
  for (const object of current) {
851
1039
  const task = taskData(object.data);
852
1040
  if (task.oldestPlanSlot === true && !isActive(task)) {
853
- await clearOldestPlanSlot(ctx.store, object.id);
1041
+ dirty = (await clearOldestPlanSlot(ctx.store, object.id)) || dirty;
854
1042
  }
855
1043
  }
856
1044
 
@@ -862,6 +1050,14 @@ async function scheduleRepository(
862
1050
  flows,
863
1051
  );
864
1052
 
1053
+ // Starts and repairs changed the tasks; read them once before the notes and
1054
+ // counts below. A pass that changed nothing keeps the snapshot it read.
1055
+ if (dirty) {
1056
+ await refreshRepositoryTasks(snapshot, repository.name);
1057
+ dirty = false;
1058
+ }
1059
+ const latest = tasksOf(snapshot.tasks, repository.name);
1060
+
865
1061
  // The queue of each area: ready tasks in the order the scheduler considers
866
1062
  // them, manual starts first, so a waiting task can say how many are ahead.
867
1063
  const queued: StoredObject[] = [];
@@ -871,7 +1067,7 @@ async function scheduleRepository(
871
1067
  for (const planObject of keptSlotNext() ? oldestPlanOrder() : turnOrder()) {
872
1068
  const plan = planData(planObject.data);
873
1069
  if (plan.status !== "confirmed") continue;
874
- for (const object of [...planTasks(current, bareId(planObject.id))].sort(byId)) {
1070
+ for (const object of [...planTasks(current, idOfKey(planObject.id))].sort(byId)) {
875
1071
  const task = taskData(object.data);
876
1072
  if (task.phase !== "ready" || started.has(object.id)) continue;
877
1073
  if (queuedIds.has(object.id) || !inScope(task, plan)) continue;
@@ -895,24 +1091,27 @@ async function scheduleRepository(
895
1091
 
896
1092
  // Say why a ready task whose dependencies are met is not starting: its area
897
1093
  // is held. The record is cleared once the area is free or the task started.
898
- for (const object of current) {
1094
+ for (const object of latest) {
899
1095
  const task = taskData(object.data);
900
1096
  if (task.phase !== "ready" || started.has(object.id)) continue;
901
1097
  const holder =
902
1098
  task.area !== undefined && dependencyState(task, tasksById).ready
903
1099
  ? areaActive.get(task.area)
904
1100
  : undefined;
905
- await setAreaHold(ctx.store, object.id, holder, aheadOf(object));
1101
+ dirty =
1102
+ (await setAreaHold(ctx.store, object.id, holder, aheadOf(object), task)) || dirty;
906
1103
  const dependencies = dependencyState(task, tasksById);
907
- await setDependencyHold(
908
- ctx.store,
909
- object.id,
910
- !dependencies.ready && dependencies.cancelled === undefined,
911
- dependencies.waitingFor,
912
- );
1104
+ dirty =
1105
+ (await setDependencyHold(
1106
+ ctx.store,
1107
+ object.id,
1108
+ !dependencies.ready && dependencies.cancelled === undefined,
1109
+ dependencies.waitingFor,
1110
+ task,
1111
+ )) || dirty;
913
1112
  }
914
1113
 
915
- const plansById = new Map(plans.map((object) => [bareId(object.id), planData(object.data)]));
1114
+ const plansById = new Map(plans.map((object) => [idOfKey(object.id), planData(object.data)]));
916
1115
 
917
1116
  // Say why a ready task that could otherwise start does not: the plan's or
918
1117
  // the repository's slots are full, or a plugin dev needs is not loaded.
@@ -921,15 +1120,15 @@ async function scheduleRepository(
921
1120
  return more.length === 0 ? first : `${first} and ${more.length} more`;
922
1121
  };
923
1122
  const activeIds = (inPlan: string | undefined): readonly string[] =>
924
- current
1123
+ latest
925
1124
  .filter((object) => {
926
1125
  const task = taskData(object.data);
927
1126
  return (isActive(task) || started.has(object.id)) && (inPlan === undefined || task.plan === inPlan);
928
1127
  })
929
- .map((object) => bareId(object.id))
1128
+ .map((object) => idOfKey(object.id))
930
1129
  .sort();
931
1130
  const missing = missingPlugins(ctx.loaded).map((plugin) => plugin.name);
932
- for (const object of current) {
1131
+ for (const object of latest) {
933
1132
  const task = taskData(object.data);
934
1133
  if (task.phase !== "ready" || started.has(object.id)) continue;
935
1134
  let note: string | undefined;
@@ -947,12 +1146,12 @@ async function scheduleRepository(
947
1146
  note = `waiting for the plan's slot (${heldBy(holders)})`;
948
1147
  } else {
949
1148
  const pool = poolOf(task);
950
- const inPool = current
1149
+ const inPool = latest
951
1150
  .filter((other) => {
952
1151
  const otherTask = taskData(other.data);
953
1152
  return (isActive(otherTask) || started.has(other.id)) && poolOf(otherTask) === pool;
954
1153
  })
955
- .map((other) => bareId(other.id))
1154
+ .map((other) => idOfKey(other.id))
956
1155
  .sort();
957
1156
  if (
958
1157
  Object.keys(settings.workers.pools).length > 1 &&
@@ -965,31 +1164,60 @@ async function scheduleRepository(
965
1164
  }
966
1165
  }
967
1166
  }
968
- await setSlotHold(ctx.store, object.id, note);
1167
+ dirty = (await setSlotHold(ctx.store, object.id, note, task)) || dirty;
969
1168
  }
970
1169
 
971
1170
  // Name each open task's flow when the repository defines more than one, and
972
1171
  // say why a ready task whose flow is not defined does not start.
973
- for (const object of await listAll(ctx.store, "task")) {
1172
+ for (const object of latest) {
974
1173
  const task = taskData(object.data);
975
- if (task.repository !== repository.name) continue;
976
1174
  const requested = task.flow ?? plansById.get(task.plan)?.flow ?? "default";
977
1175
  const missing =
978
1176
  (task.phase === "ready" ||
979
1177
  (task.phase === "waiting" && task.run === null)) &&
980
1178
  task.flowName === undefined &&
981
1179
  flowFor(flows, requested) === undefined;
982
- await setFlowNote(ctx.store, object.id, {
983
- shown: flows.named.size > 1 ? requested : undefined,
984
- held: missing
985
- ? (flows.refused.get(requested) ?? `flow ${requested} is not defined in .operad/dev.json`)
986
- : undefined,
987
- });
1180
+ dirty =
1181
+ (await setFlowNote(
1182
+ ctx.store,
1183
+ object.id,
1184
+ {
1185
+ shown: flows.named.size > 1 ? requested : undefined,
1186
+ held: missing
1187
+ ? (flows.refused.get(requested) ?? `flow ${requested} is not defined in .operad/dev.json`)
1188
+ : undefined,
1189
+ },
1190
+ task,
1191
+ )) || dirty;
1192
+ }
1193
+
1194
+ if (dirty) {
1195
+ await refreshRepositoryTasks(snapshot, repository.name);
1196
+ dirty = false;
1197
+ }
1198
+ const final = tasksOf(snapshot.tasks, repository.name);
1199
+ const tasksByPlan = new Map<string, StoredObject[]>();
1200
+ for (const object of final) {
1201
+ const plan = taskData(object.data).plan;
1202
+ const mine = tasksByPlan.get(plan);
1203
+ if (mine === undefined) tasksByPlan.set(plan, [object]);
1204
+ else mine.push(object);
1205
+ }
1206
+ let signatures = planTaskSignatures.get(ctx.store);
1207
+ if (signatures === undefined) {
1208
+ signatures = new Map();
1209
+ planTaskSignatures.set(ctx.store, signatures);
988
1210
  }
989
1211
 
990
1212
  // Keep each plan's cached counts, and with them its row's mark, current.
991
1213
  for (const planObject of plans) {
992
- await refreshPlanCounts(ctx.store, await getPlan(ctx.store, planObject.id));
1214
+ const id = idOfKey(planObject.id);
1215
+ const mine = tasksByPlan.get(id) ?? [];
1216
+ const signature = taskSignature(mine);
1217
+ const changed = signatures.get(planObject.id) !== signature;
1218
+ if (planData(planObject.data).finishedReported === true && !changed) continue;
1219
+ await refreshPlanCounts(ctx.store, await getPlan(ctx.store, planObject.id), mine);
1220
+ signatures.set(planObject.id, signature);
993
1221
  }
994
1222
  }
995
1223
 
@@ -1039,13 +1267,16 @@ export function runScheduler(ctx: TickContext): Promise<void> {
1039
1267
  async function runPass(ctx: TickContext): Promise<void> {
1040
1268
  const repositories = await listRepositories(ctx.store);
1041
1269
  if (repositories.length === 0) return;
1042
- const tasks = await listAll(ctx.store, "task");
1043
- const plans = await listAll(ctx.store, "plan");
1270
+ const snapshot: PassSnapshot = {
1271
+ store: ctx.store,
1272
+ tasks: await listAll(ctx.store, "task"),
1273
+ plans: await listAll(ctx.store, "plan"),
1274
+ };
1044
1275
  for (const repository of repositories) {
1045
1276
  try {
1046
- await scheduleRepository(ctx, repository, tasks, plans);
1277
+ await scheduleRepository(ctx, repository, snapshot);
1047
1278
  } catch (error) {
1048
- const message = error instanceof Error ? error.message : String(error);
1279
+ const message = messageOf(error);
1049
1280
  console.error(`dev: repository "${repository.name}": ${message}`);
1050
1281
  }
1051
1282
  }