hammerkit 2.0.0-next.13 → 2.0.0-next.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -24,6 +24,7 @@ const cache_sync_1 = require("./cache/cache-sync");
24
24
  const cache_inventory_1 = require("./cache/cache-inventory");
25
25
  const prefetch_secrets_1 = require("./secrets/prefetch-secrets");
26
26
  const work_network_1 = require("./planner/work-network");
27
+ const task_priority_1 = require("./executer/task-priority");
27
28
  const isCliTask = (val) => val.type === 'task';
28
29
  exports.isCliTask = isCliTask;
29
30
  const isCliService = (val) => val.type === 'service';
@@ -65,7 +66,9 @@ class Cli {
65
66
  if (capacity && type !== 'down' && (options?.resourceCheck ?? true)) {
66
67
  rejectOversizedWork(workTree, capacity, type === 'up');
67
68
  }
68
- const processManager = new process_manager_1.ProcessManager(options?.workers ?? 0, capacity ? new resource_budget_1.ResourceBudget(capacity, workTree.environment) : null);
69
+ // a server knows what tasks took from its runs, a run there keeps nothing of its own
70
+ const durations = options?.durations ?? (this.environment.hosted ? {} : await (0, task_priority_1.readTaskDurations)(workTree, this.environment));
71
+ const processManager = new process_manager_1.ProcessManager(options?.workers ?? 0, capacity ? new resource_budget_1.ResourceBudget(capacity, workTree.environment) : null, (0, task_priority_1.getTaskPriority)(workTree, durations));
69
72
  if (!(0, plan_work_tasks_1.hasError)(workTree)) {
70
73
  await (0, update_service_status_1.updateServiceStatus)(workTree);
71
74
  await (0, execute_work_tree_1.executeWorkTree)(workTree, this.environment, {
@@ -13,6 +13,7 @@ const explain_1 = require("../cache/explain");
13
13
  const archive_task_entry_1 = require("./archive-task-entry");
14
14
  const units_1 = require("../utils/units");
15
15
  const deferred_restore_1 = require("./deferred-restore");
16
+ const task_priority_1 = require("./task-priority");
16
17
  async function pushToBackend(work, environment, cacheState, options) {
17
18
  const { resolved, stateKey, provable } = cacheState;
18
19
  // an aggregate has nothing to store, see checkCacheState
@@ -97,6 +98,8 @@ dependents = null) {
97
98
  }
98
99
  await (0, await_completed_dependencies_1.awaitRunningNeeds)(work, work.needs.map((n) => n.service), abort);
99
100
  await options.processManager.task(work, async () => {
101
+ // from here it runs; `started` also counts its wait for dependencies and a place
102
+ const ranFrom = new Date();
100
103
  work.state.set({
101
104
  type: 'running',
102
105
  stateKey: cacheState.stateKey,
@@ -114,6 +117,7 @@ dependents = null) {
114
117
  daemon: options.daemon,
115
118
  publishPorts: false,
116
119
  waitForReady: true,
120
+ onQuotaRefused: (refused) => options.processManager.quotaRefused(work, refused),
117
121
  });
118
122
  }
119
123
  finally {
@@ -137,13 +141,19 @@ dependents = null) {
137
141
  work.status.write('debug', 'completed for state key ' + cacheState.stateKey);
138
142
  await pushToBackend(work, environment, cacheState, options);
139
143
  const cached = onlyGroupsCacheHits(work);
144
+ const duration = (0, states_1.getDuration)(started);
140
145
  work.state.set({
141
146
  stateKey: cacheState.stateKey,
142
147
  type: 'completed',
143
148
  cached,
144
- duration: (0, states_1.getDuration)(started),
149
+ duration,
145
150
  missCauses: cached ? undefined : missCauses,
146
151
  });
152
+ // what it took orders the next runs, see getTaskPriority
153
+ // on a server the runs are the record, see RunRegistry
154
+ if (!(0, work_task_1.isAggregateTask)(work.data) && !environment.hosted) {
155
+ await (0, task_priority_1.recordTaskDuration)(environment, work, (0, states_1.getDuration)(ranFrom));
156
+ }
147
157
  }
148
158
  else {
149
159
  if (!options.watch) {
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.executeWorkTree = void 0;
4
+ const work_tree_1 = require("../planner/work-tree");
4
5
  const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
5
6
  const execute_work_service_1 = require("./execute-work-service");
6
7
  const execute_work_task_1 = require("./execute-work-task");
@@ -18,7 +19,7 @@ async function executeWorkTree(work, environment, options) {
18
19
  if (initOf) {
19
20
  const service = work.services[initOf.serviceName] ?? null;
20
21
  // asked for alone (by name), it runs against a service already running too
21
- const requested = work.requested?.length === 1 && work.requested[0] === task.name;
22
+ const requested = (0, work_tree_1.isAskedByName)(work, task.name);
22
23
  itemPromises.push((0, execute_init_task_1.executeInitTask)(task, initOf.init, service, requested, environment, options));
23
24
  continue;
24
25
  }
@@ -7,14 +7,27 @@ class ProcessManager {
7
7
  // runs already; one starts regardless when nothing else runs, so a run
8
8
  // whose services alone fill the budget, or a task bigger than it, still
9
9
  // makes progress.
10
- constructor(workerLimit, budget = null) {
10
+ // With a priority, the waiting task that is most urgent takes a free place,
11
+ // else the one that waits longest. Places are then given out a moment after a
12
+ // task arrives or one ends, so the tasks that the same event made ready (the
13
+ // dependents of a task that completed) compete for them together.
14
+ constructor(workerLimit, budget = null, priority = null) {
11
15
  this.workerLimit = workerLimit;
12
16
  this.budget = budget;
17
+ this.priority = priority;
13
18
  this.processes = [];
14
19
  this.pendingProcesses = [];
20
+ this.pickScheduled = false;
21
+ // the running tasks whose pod the quota of the namespace refuses now
22
+ this.refused = new Set();
15
23
  }
16
24
  task(item, factory) {
17
25
  return new Promise((resolve, reject) => {
26
+ if (this.priority) {
27
+ this.pendingProcesses.push({ item, factory, resolve, reject });
28
+ this.schedulePick();
29
+ return;
30
+ }
18
31
  if (this.budget) {
19
32
  this.pendingProcesses.push({ item, factory, resolve, reject });
20
33
  this.startFitting();
@@ -43,11 +56,76 @@ class ProcessManager {
43
56
  if (!released) {
44
57
  released = true;
45
58
  budget.release(requests);
46
- this.startFitting();
59
+ if (this.priority) {
60
+ this.schedulePick();
61
+ }
62
+ else {
63
+ this.startFitting();
64
+ }
47
65
  }
48
66
  };
49
67
  }
68
+ // A running task tells whether the quota refuses its pod now. While it is refused, the
69
+ // tasks less urgent than it wait, so the room that frees goes to it and not to a pod of
70
+ // theirs; without a priority nothing changes.
71
+ quotaRefused(item, refused) {
72
+ if (refused) {
73
+ this.refused.add(item);
74
+ }
75
+ else if (this.refused.delete(item) && this.priority) {
76
+ this.schedulePick();
77
+ }
78
+ }
79
+ schedulePick() {
80
+ if (this.pickScheduled) {
81
+ return;
82
+ }
83
+ this.pickScheduled = true;
84
+ setImmediate(() => {
85
+ this.pickScheduled = false;
86
+ if (this.budget) {
87
+ this.startFitting();
88
+ }
89
+ else {
90
+ this.startByPriority();
91
+ }
92
+ });
93
+ }
94
+ // The waiting tasks that may start now, most urgent first; of equal ones, the one
95
+ // waiting longest. While the quota refuses a running task's pod, only those more urgent
96
+ // than it.
97
+ startable() {
98
+ const priority = this.priority;
99
+ if (!priority) {
100
+ return [...this.pendingProcesses];
101
+ }
102
+ const memo = new Map();
103
+ const floor = this.refused.size > 0 ? Math.max(...[...this.refused].map((item) => priority(item, memo))) : null;
104
+ // A task that needs a service is never held back: its service is up already and holds
105
+ // its room until the task ran, so holding the task back would keep that room taken.
106
+ return this.pendingProcesses
107
+ .map((pending, index) => ({ pending, index, rank: priority(pending.item, memo) }))
108
+ .filter(({ pending, rank }) => floor === null || rank > floor || pending.item.needs.length > 0)
109
+ .sort((a, b) => b.rank - a.rank || a.index - b.index)
110
+ .map(({ pending }) => pending);
111
+ }
112
+ startByPriority() {
113
+ for (const pending of this.startable()) {
114
+ if (this.workerLimit !== 0 && this.processes.length >= this.workerLimit) {
115
+ return;
116
+ }
117
+ if (this.processes.some((p) => p.id === pending.item.name)) {
118
+ continue;
119
+ }
120
+ this.pendingProcesses.splice(this.pendingProcesses.indexOf(pending), 1);
121
+ this.startProcess(pending);
122
+ }
123
+ }
50
124
  enqueuePendingProcesses() {
125
+ if (this.priority) {
126
+ this.schedulePick();
127
+ return;
128
+ }
51
129
  if (this.budget) {
52
130
  this.startFitting();
53
131
  return;
@@ -64,10 +142,10 @@ class ProcessManager {
64
142
  this.startProcess(pendingProcess);
65
143
  }
66
144
  }
67
- // In order, every pending task that fits; a later, smaller one may start
68
- // while an earlier one waits for room.
145
+ // In order (by priority when there is one), every pending task that fits; a
146
+ // later, smaller one may start while an earlier one waits for room.
69
147
  startFitting() {
70
- for (const pending of [...this.pendingProcesses]) {
148
+ for (const pending of this.startable()) {
71
149
  if (this.workerLimit !== 0 && this.processes.length >= this.workerLimit) {
72
150
  return;
73
151
  }
@@ -98,6 +176,7 @@ class ProcessManager {
98
176
  pendingProcess.reject(err);
99
177
  })
100
178
  .finally(() => {
179
+ this.refused.delete(pendingProcess.item);
101
180
  const index = this.processes.indexOf(item);
102
181
  this.processes.splice(index, 1);
103
182
  if (requests) {
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.recordTaskDuration = exports.readTaskDurations = exports.getDurationFile = exports.getTaskPriority = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const path_1 = require("path");
6
+ const work_item_1 = require("../planner/work-item");
7
+ const work_task_1 = require("../planner/work-task");
8
+ const plan_work_tasks_1 = require("../planner/utils/plan-work-tasks");
9
+ const get_cache_directory_1 = require("../optimizer/get-cache-directory");
10
+ const log_1 = require("../log");
11
+ // how many of its last durations a task keeps on this machine, the median of which it is
12
+ // expected to take
13
+ const KEPT_DURATIONS = 5;
14
+ /**
15
+ * The priority of a task waiting for a place to run: the time from its start until the end
16
+ * of the longest chain of what waits for it, its own expected duration and that of each
17
+ * task after it. A task on the longest chain of the run starts first, so a long chain does
18
+ * not wait behind short ones that could just as well run later.
19
+ *
20
+ * Expected durations come from past runs. A task without any counts as the median of the
21
+ * others; when none has one, every task counts 1 and the chain is counted in tasks. A task
22
+ * that runs nothing (it only groups others), and one that completed already (it was taken
23
+ * from the cache), count 0. A service counts 0 itself and carries on the chains of the
24
+ * tasks that need it.
25
+ */
26
+ function getTaskPriority(workTree, durations) {
27
+ const items = [...(0, plan_work_tasks_1.iterateWorkTasks)(workTree), ...(0, plan_work_tasks_1.iterateWorkServices)(workTree)];
28
+ const dependents = new Map();
29
+ const add = (on, dependent) => {
30
+ const list = dependents.get(on) ?? [];
31
+ if (!list.includes(dependent)) {
32
+ list.push(dependent);
33
+ }
34
+ dependents.set(on, list);
35
+ };
36
+ for (const item of items) {
37
+ for (const dep of item.deps) {
38
+ add(dep, item);
39
+ }
40
+ for (const need of item.needs) {
41
+ add(need.service, item);
42
+ }
43
+ }
44
+ const known = items
45
+ .filter((item) => (0, work_item_1.isWorkTaskItem)(item) && durations[item.name] !== undefined)
46
+ .map((item) => durations[item.name])
47
+ .sort((a, b) => a - b);
48
+ const fallback = known.length > 0 ? known[Math.floor((known.length - 1) / 2)] : 1;
49
+ const cost = (item) => {
50
+ if (!(0, work_item_1.isWorkTaskItem)(item)) {
51
+ return 0;
52
+ }
53
+ const state = item.state?.current;
54
+ if (state?.type === 'completed' || (0, work_task_1.isAggregateTask)(item.data)) {
55
+ return 0;
56
+ }
57
+ return durations[item.name] ?? fallback;
58
+ };
59
+ // a memo holds for one pick: what completed since the last one counts 0 now
60
+ return (item, memo = new Map()) => {
61
+ const chain = (current, path) => {
62
+ const cached = memo.get(current);
63
+ if (cached !== undefined) {
64
+ return cached;
65
+ }
66
+ // a loop is refused before a run starts, this only keeps the walk finite
67
+ if (path.has(current)) {
68
+ return 0;
69
+ }
70
+ path.add(current);
71
+ let longest = 0;
72
+ for (const dependent of dependents.get(current) ?? []) {
73
+ longest = Math.max(longest, chain(dependent, path));
74
+ }
75
+ path.delete(current);
76
+ const value = cost(current) + longest;
77
+ memo.set(current, value);
78
+ return value;
79
+ };
80
+ return chain(item, new Set());
81
+ };
82
+ }
83
+ exports.getTaskPriority = getTaskPriority;
84
+ // Where a task keeps its last durations on this machine: below hammerkit's directory, by
85
+ // the directory of its build file and its name.
86
+ function getDurationFile(task) {
87
+ const key = (0, crypto_1.createHash)('sha1').update(`${task.data.cwd}\0${task.name}`).digest('hex');
88
+ return (0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'durations', `${key}.json`);
89
+ }
90
+ exports.getDurationFile = getDurationFile;
91
+ async function readKept(environment, task) {
92
+ const file = getDurationFile(task);
93
+ try {
94
+ if (!(await environment.file.exists(file))) {
95
+ return [];
96
+ }
97
+ const parsed = JSON.parse(await environment.file.read(file));
98
+ return Array.isArray(parsed?.durations)
99
+ ? parsed.durations.filter((value) => typeof value === 'number' && value >= 0)
100
+ : [];
101
+ }
102
+ catch {
103
+ return [];
104
+ }
105
+ }
106
+ // What the tasks of a run took the last times they ran on this machine.
107
+ async function readTaskDurations(workTree, environment) {
108
+ const durations = {};
109
+ await Promise.all([...(0, plan_work_tasks_1.iterateWorkTasks)(workTree)].map(async (task) => {
110
+ const kept = await readKept(environment, task);
111
+ if (kept.length > 0) {
112
+ const sorted = [...kept].sort((a, b) => a - b);
113
+ durations[task.name] = sorted[Math.floor((sorted.length - 1) / 2)];
114
+ }
115
+ }));
116
+ return durations;
117
+ }
118
+ exports.readTaskDurations = readTaskDurations;
119
+ // Keep what a task took, once it ran to its end. Best effort: a run never fails over it.
120
+ async function recordTaskDuration(environment, task, duration) {
121
+ try {
122
+ const kept = [...(await readKept(environment, task)), Math.max(0, Math.round(duration))].slice(-KEPT_DURATIONS);
123
+ await environment.file.createDirectory((0, path_1.join)((0, get_cache_directory_1.getHammerkitDirectory)(), 'durations'));
124
+ await environment.file.writeFile(getDurationFile(task), JSON.stringify({ durations: kept }));
125
+ }
126
+ catch (e) {
127
+ task.status.write('debug', `${task.name} could not keep how long it took: ${(0, log_1.getErrorMessage)(e)}`);
128
+ }
129
+ }
130
+ exports.recordTaskDuration = recordTaskDuration;
131
+ //# sourceMappingURL=task-priority.js.map
@@ -33,38 +33,54 @@ async function awaitJobCompletion(instance, env, name, abort, pollInterval = 100
33
33
  : null;
34
34
  // when the job last had a pod: a refusal before it is not one of the pod it waits for now
35
35
  let hadPod = 0;
36
- for (;;) {
37
- if (abort.aborted) {
38
- await deleteJob(instance, env, name);
39
- throw new abort_1.AbortError();
40
- }
41
- const job = await instance.batchApi.readNamespacedJobStatus({ name, namespace: env.namespace });
42
- const status = job.status;
43
- if (status?.succeeded) {
44
- return;
36
+ let refused = false;
37
+ const tell = (now) => {
38
+ if (now !== refused) {
39
+ refused = now;
40
+ quota?.onRefused?.(now);
45
41
  }
46
- const failed = status?.conditions?.find((c) => c.type === 'Failed' && c.status === 'True');
47
- if (failed) {
48
- throw new Error(`job ${name} failed: ${failed.message ?? failed.reason ?? 'unknown reason'}`);
49
- }
50
- if (wait) {
51
- let refusal = null;
52
- if (status?.active || status?.ready) {
53
- hadPod = Date.now();
42
+ };
43
+ try {
44
+ return await pollJob();
45
+ }
46
+ finally {
47
+ tell(false);
48
+ }
49
+ async function pollJob() {
50
+ for (;;) {
51
+ if (abort.aborted) {
52
+ await deleteJob(instance, env, name);
53
+ throw new abort_1.AbortError();
54
54
  }
55
- else {
56
- // the job controller can't make the pod: no pod to wait on, only its events say why
57
- refusal = await readJobRefusal(instance, env, name, job, hadPod);
55
+ const job = await instance.batchApi.readNamespacedJobStatus({ name, namespace: env.namespace });
56
+ const status = job.status;
57
+ if (status?.succeeded) {
58
+ return;
58
59
  }
59
- try {
60
- await wait.check(refusal);
60
+ const failed = status?.conditions?.find((c) => c.type === 'Failed' && c.status === 'True');
61
+ if (failed) {
62
+ throw new Error(`job ${name} failed: ${failed.message ?? failed.reason ?? 'unknown reason'}`);
61
63
  }
62
- catch (e) {
63
- await deleteJob(instance, env, name);
64
- throw e;
64
+ if (wait) {
65
+ let refusal = null;
66
+ if (status?.active || status?.ready) {
67
+ hadPod = Date.now();
68
+ }
69
+ else {
70
+ // the job controller can't make the pod: no pod to wait on, only its events say why
71
+ refusal = await readJobRefusal(instance, env, name, job, hadPod);
72
+ }
73
+ tell(refusal !== null);
74
+ try {
75
+ await wait.check(refusal);
76
+ }
77
+ catch (e) {
78
+ await deleteJob(instance, env, name);
79
+ throw e;
80
+ }
65
81
  }
82
+ await sleep(pollInterval, abort);
66
83
  }
67
- await sleep(pollInterval, abort);
68
84
  }
69
85
  }
70
86
  exports.awaitJobCompletion = awaitJobCompletion;
@@ -388,6 +388,7 @@ function kubernetesTaskRuntime(task, kubernetes) {
388
388
  await (0, await_running_state_1.awaitJobCompletion)(instance, kubernetes, spec.metadata.name, options.abort, 1000, {
389
389
  onWaiting: (text) => task.status.write('warn', `${task.name} ${text}`),
390
390
  timeout: ensure_persistent_data_1.QUOTA_TIMEOUT,
391
+ onRefused: options.onQuotaRefused,
391
392
  });
392
393
  }
393
394
  catch (e) {
@@ -1,3 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isAskedByName = void 0;
4
+ // Whether a task was asked for by name: one of the tasks named, or the one task the run
5
+ // was asked for. An init task asked for by name starts its service and runs.
6
+ function isAskedByName(workTree, name) {
7
+ if (workTree.named) {
8
+ return workTree.named.includes(name);
9
+ }
10
+ return workTree.requested?.length === 1 && workTree.requested[0] === name;
11
+ }
12
+ exports.isAskedByName = isAskedByName;
3
13
  //# sourceMappingURL=work-tree.js.map
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getWorkContext = exports.defaultEnvironment = void 0;
4
4
  const work_scope_1 = require("../executer/work-scope");
5
+ const work_tree_1 = require("../planner/work-tree");
5
6
  const label_values_1 = require("../executer/label-values");
6
7
  const append_work_service_1 = require("../planner/utils/append-work-service");
7
8
  const append_work_task_1 = require("../planner/utils/append-work-task");
@@ -70,6 +71,14 @@ function getWorkContext(context, scope, environment) {
70
71
  throw new Error(`no task or service named ${unknown.join(', ')}, see hammerkit ls`);
71
72
  }
72
73
  }
74
+ if (!(0, work_scope_1.isContextTaskFilter)(scope) && scope.taskNames) {
75
+ filteredWorkTree.named = scope.taskNames;
76
+ const known = new Set(tasks.map((task) => task.name));
77
+ const unknown = scope.taskNames.filter((name) => !known.has(name));
78
+ if (unknown.length > 0) {
79
+ throw new Error(`no task named ${unknown.join(', ')}, see hammerkit ls`);
80
+ }
81
+ }
73
82
  if (scope.args) {
74
83
  (0, task_arguments_1.applyArguments)({ tasks: selectedTasks, services: scope.args.services ? selectedServices : [] }, scope.args.values, scope.args.cache);
75
84
  }
@@ -89,7 +98,7 @@ function keepRequirersInScope(workTree) {
89
98
  service.requiredBy = service.requiredBy.filter((required) => inScope.has(required));
90
99
  // an init task asked for alone is what its service starts for
91
100
  const init = service.data.type === 'container-service' ? service.data.init : null;
92
- if (init && workTree.requested?.length === 1 && workTree.requested[0] === init.task.name) {
101
+ if (init && (0, work_tree_1.isAskedByName)(workTree, init.task.name)) {
93
102
  service.requiredBy.push(init.task);
94
103
  }
95
104
  }
@@ -131,6 +140,9 @@ function matchesTaskWorkScope(task, scope) {
131
140
  if (scope.serviceNames) {
132
141
  return false;
133
142
  }
143
+ if (scope.taskNames) {
144
+ return scope.taskNames.includes(task.name);
145
+ }
134
146
  if (scope.names) {
135
147
  return scope.names.includes(task.name);
136
148
  }
@@ -143,6 +155,9 @@ function matchesServiceWorkScope(service, scope) {
143
155
  if (scope.serviceNames) {
144
156
  return scope.serviceNames.includes(service.name);
145
157
  }
158
+ if (scope.taskNames) {
159
+ return false;
160
+ }
146
161
  if (scope.names) {
147
162
  return scope.names.includes(service.name);
148
163
  }
@@ -345,6 +345,7 @@ class HostExecutor {
345
345
  accounts: run.accounts,
346
346
  volumeScope: volumeScope(run, this.options.directory),
347
347
  ...((0, checks_1.isCheckRun)(run) ? { check: true } : {}),
348
+ ...(context.durations ? { durations: context.durations } : {}),
348
349
  catalog: planning.environment.hosted?.catalog,
349
350
  ...(run.up
350
351
  ? {
@@ -723,10 +723,13 @@ exports.getPrivilegedNamespaceProblem = getPrivilegedNamespaceProblem;
723
723
  // What may mount a claim a run kept: the runs of the same branch or tag of a repository,
724
724
  // which share its cache, so that the runs of two branches go side by side and the runs of one find what
725
725
  // the last one left; on a sandbox the runs of that sandbox only, whose claim is on the same
726
- // node or zone as the kept ones. The owner is the namespace's.
726
+ // node or zone as the kept ones. An approved run on a sandbox keeps nothing with those runs,
727
+ // whose outputs nobody approved, as its cache is apart from theirs: it has a scope of its own,
728
+ // per sandbox, so that approved runs on two sandboxes go side by side. The owner is the namespace's.
727
729
  function getVolumeScope(run) {
728
730
  if (run.source.type === 'sandbox' && !run.source.check) {
729
- return `sandbox-${(0, crypto_1.createHash)('sha256').update(run.source.id).digest('hex').slice(0, 24)}`;
731
+ const id = (0, crypto_1.createHash)('sha256').update(run.source.id).digest('hex').slice(0, 24);
732
+ return (run.approvals?.length ?? 0) > 0 ? `approved-${id}` : `sandbox-${id}`;
730
733
  }
731
734
  // a ref given as a commit hash names no branch: its runs keep the repository's claims
732
735
  if (run.source.type === 'ref' && !/^[0-9a-f]{40}([0-9a-f]{24})?$/i.test(run.source.ref)) {
@@ -6,7 +6,8 @@ const plan_1 = require("./plan");
6
6
  function labels(values) {
7
7
  return values && values.length > 0 ? (0, parse_label_arguments_1.parseLabelArguments)(values) : undefined;
8
8
  }
9
- // The tasks in the order they were named, one scope each; by labels when none is. A
9
+ // The tasks named, as one scope: they are planned together and run side by side as far
10
+ // as their dependencies allow, in no particular order; by labels when none is named. A
10
11
  // service run is one scope of its services.
11
12
  // The arguments, if any, go to the one task named (the request allows no more). That
12
13
  // task runs uncached unless the request names a `cache` method, as `run --cache` does.
@@ -17,11 +18,22 @@ function getRunScopes(tasks, options, services = []) {
17
18
  const args = options.args && options.args.length > 0
18
19
  ? { values: options.args, services: false, cache: options.cache !== undefined }
19
20
  : undefined;
20
- return tasks.length > 0
21
- ? tasks.map((task) => ({
22
- name: task,
23
- scope: { taskName: task, environmentName: options.env ?? null, ...(args ? { args } : {}) },
24
- }))
21
+ const named = [...new Set(tasks)];
22
+ if (named.length === 1) {
23
+ return [
24
+ {
25
+ name: named[0],
26
+ scope: { taskName: named[0], environmentName: options.env ?? null, ...(args ? { args } : {}) },
27
+ },
28
+ ];
29
+ }
30
+ return named.length > 0
31
+ ? [
32
+ {
33
+ name: named.join(', '),
34
+ scope: { taskNames: named, environmentName: options.env ?? null, ...(args ? { args } : {}) },
35
+ },
36
+ ]
25
37
  : [
26
38
  {
27
39
  name: 'labels',
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.workerMain = exports.readInput = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.runTasks = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
3
+ exports.workerMain = exports.readInput = exports.taskCommands = exports.taskCauses = exports.describeFailures = exports.failedTasks = exports.runTasks = exports.getEndpointTargets = exports.publishEndpoints = exports.getRunNetwork = exports.workerInputSchema = void 0;
4
4
  const readline_1 = require("readline");
5
5
  const zod_1 = require("zod");
6
6
  const cli_1 = require("../cli");
@@ -80,6 +80,8 @@ exports.workerInputSchema = zod_1.z
80
80
  .optional(),
81
81
  // the run's results count as checks: report each task's check key before it runs
82
82
  check: zod_1.z.boolean().optional(),
83
+ // what its tasks took in past runs, in ms by name, so the longest chain starts first
84
+ durations: zod_1.z.record(zod_1.z.number().nonnegative()).optional(),
83
85
  })
84
86
  .strict();
85
87
  // The ceiling of the run, combined here and not in the server: the lower of two allow lists
@@ -206,6 +208,7 @@ up) {
206
208
  maxTimeout: options.maxTimeout ? (0, units_1.parseDuration)(options.maxTimeout) : null,
207
209
  skipDeps: options.skipDeps !== false,
208
210
  network: getRunNetwork(input),
211
+ ...(input.durations ? { durations: input.durations } : {}),
209
212
  // why a task was not taken from the cache goes into its result
210
213
  explain: true,
211
214
  };
@@ -307,7 +310,7 @@ up) {
307
310
  }
308
311
  // a service run names what failed and why: its services have no results of their own
309
312
  const failures = input.up ? describeFailures(execution.state.current, (text) => secrets.redact(text)) : [];
310
- throw new Error(failures.length > 0 ? failures.join('; ').slice(0, runs_1.MAX_TASK_ERROR) : `${name} failed`);
313
+ throw new Error(failures.length > 0 ? failures.join('; ').slice(0, runs_1.MAX_TASK_ERROR) : `${failedTasks(workTree, name)} failed`);
311
314
  }
312
315
  }
313
316
  finally {
@@ -371,6 +374,19 @@ function lastError(item) {
371
374
  }
372
375
  return last;
373
376
  }
377
+ // Of several tasks named, the ones that failed: those named first, else the dependencies
378
+ // that failed under them. One task named is the run's name, as before.
379
+ function failedTasks(workTree, name) {
380
+ const requested = workTree.requested ?? [];
381
+ if (requested.length < 2) {
382
+ return name;
383
+ }
384
+ const failed = [...(0, plan_work_tasks_1.iterateWorkTasks)(workTree)].filter((task) => task.state.current.type === 'error' || task.state.current.type === 'crash');
385
+ const named = failed.filter((task) => requested.includes(task.name));
386
+ const names = (named.length > 0 ? named : failed).map((task) => task.name);
387
+ return names.length > 0 ? names.join(', ') : name;
388
+ }
389
+ exports.failedTasks = failedTasks;
374
390
  /**
375
391
  * What failed in a run, one line each, for its error: the services and tasks that failed,
376
392
  * with their reason. Those that only stopped because another failed are left out.
@@ -15,6 +15,21 @@ exports.isFinal = isFinal;
15
15
  // those of the sandbox), `namespace` prepares its place on the cluster, `plan` starts the
16
16
  // process of the run and reads its build files.
17
17
  exports.RUN_PHASES = ['source', 'namespace', 'plan'];
18
+ // how many past runs of a task its expected duration is the median of
19
+ const DURATION_SAMPLES = 9;
20
+ // How long a task that succeeded ran: from its first command to the end of its last when
21
+ // they are known, as its duration also counts its wait for its dependencies and a place.
22
+ function ranFor(result) {
23
+ const commands = result.commands ?? [];
24
+ if (commands.length > 0) {
25
+ const from = Date.parse(commands[0].startedAt);
26
+ const to = Date.parse(commands[commands.length - 1].finishedAt);
27
+ if (Number.isFinite(from) && Number.isFinite(to) && to >= from) {
28
+ return to - from;
29
+ }
30
+ }
31
+ return result.durationMs;
32
+ }
18
33
  // The server can not take the run now; `status` is what the caller is told
19
34
  class RunError extends Error {
20
35
  constructor() {
@@ -278,6 +293,44 @@ class RunRegistry {
278
293
  const entry = this.entries.get(id);
279
294
  return entry ? this.copy(entry.run) : undefined;
280
295
  }
296
+ // What the tasks of a run took when they last ran in its repository, in ms by task name:
297
+ // the median of their last DURATION_SAMPLES runs that succeeded. Only times, of runs of any
298
+ // caller, and only for the scheduling of this run.
299
+ durationsOf(run) {
300
+ const repo = run.source.type === 'upload' ? undefined : run.source.repo;
301
+ if (!repo) {
302
+ return {};
303
+ }
304
+ const samples = new Map();
305
+ for (const entry of [...this.entries.values()].reverse()) {
306
+ const other = entry.run;
307
+ if (other.id === run.id || other.source.type === 'upload' || other.source.repo !== repo) {
308
+ continue;
309
+ }
310
+ for (const [task, result] of Object.entries(other.results ?? {})) {
311
+ const took = result.status === 'succeeded' ? ranFor(result) : undefined;
312
+ if (took === undefined) {
313
+ continue;
314
+ }
315
+ const times = samples.get(task) ?? [];
316
+ if (times.length < DURATION_SAMPLES) {
317
+ times.push(took);
318
+ samples.set(task, times);
319
+ }
320
+ }
321
+ }
322
+ const durations = {};
323
+ // only the tasks of this run, when its plan says which
324
+ const planned = run.plan ? new Set(Object.keys(run.plan)) : null;
325
+ for (const [task, times] of samples) {
326
+ if (planned && !planned.has(task)) {
327
+ continue;
328
+ }
329
+ times.sort((a, b) => a - b);
330
+ durations[task] = times[Math.floor((times.length - 1) / 2)];
331
+ }
332
+ return durations;
333
+ }
281
334
  // every run it keeps, of every caller, newest first: who may see which is for the caller
282
335
  all() {
283
336
  return [...this.entries.values()].map((entry) => this.copy(entry.run)).reverse();
@@ -842,9 +895,11 @@ class RunRegistry {
842
895
  ? { ...this.copy(entry.run), source: { ...landing.source }, ...(landing.plan ? { plan: landing.plan } : {}) }
843
896
  : this.copy(entry.run);
844
897
  try {
898
+ const durations = this.durationsOf(run);
845
899
  await this.options.executor.execute(run, {
846
900
  emit: (event) => this.record(entry, event),
847
901
  signal: entry.abort.signal,
902
+ ...(Object.keys(durations).length > 0 ? { durations } : {}),
848
903
  ...(entry.run.up
849
904
  ? {
850
905
  up: (targets) => this.markUp(entry, targets),
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hammerkit",
3
3
  "description": "Containerized build tool with incremental caching that runs the same build file locally, in Docker and on Kubernetes.",
4
- "version": "2.0.0-next.13",
4
+ "version": "2.0.0-next.15",
5
5
  "keywords": [
6
6
  "build",
7
7
  "build-tool",