@milabench/bujang 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,693 @@
1
+ import React, { useEffect, useMemo, useState } from 'react';
2
+ import { Link } from 'react-router-dom';
3
+ import {
4
+ Badge,
5
+ Box,
6
+ Button,
7
+ Code,
8
+ Heading,
9
+ HStack,
10
+ Input,
11
+ NativeSelect,
12
+ Spinner,
13
+ Table,
14
+ Text,
15
+ VStack,
16
+ } from '@chakra-ui/react';
17
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
18
+ import {
19
+ LuActivity,
20
+ LuArchive,
21
+ LuArrowDown,
22
+ LuArrowUp,
23
+ LuBrush,
24
+ LuCalendarClock,
25
+ LuGauge,
26
+ LuHistory,
27
+ LuRefreshCw,
28
+ LuServer,
29
+ LuTrash2,
30
+ } from 'react-icons/lu';
31
+ import {
32
+ getJanitor,
33
+ getJanitorCleanup,
34
+ getJanitorHistory,
35
+ janitorArchive,
36
+ janitorPrune,
37
+ janitorRemoveStale,
38
+ } from '../api';
39
+ import type {
40
+ ApiError,
41
+ JanitorArchiveResult,
42
+ JanitorOverview,
43
+ JanitorRun,
44
+ JanitorSkipped,
45
+ JanitorStaleResult,
46
+ JanitorStat,
47
+ JanitorStatus,
48
+ } from '../types';
49
+ import { LinkableCard, useHashScroll } from '../components/LinkableCard';
50
+ import { Tooltip } from '../components/tooltip';
51
+ import { toaster } from '../toast';
52
+ import { useBujangPaths } from '../context';
53
+ import { usePageTitle } from '../hooks/usePageTitle';
54
+ import { NO_JOB_ID } from '../constants';
55
+
56
+ const POLL_MS = 5_000;
57
+ const OVERVIEW_KEY = ['bujang-janitor'];
58
+
59
+ const SECTIONS: { id: string; label: string }[] = [
60
+ { id: 'running', label: 'Running now' },
61
+ { id: 'periodic', label: 'Periodic jobs' },
62
+ { id: 'clusters', label: 'Cluster load' },
63
+ { id: 'tasks', label: 'Tasks' },
64
+ { id: 'runs', label: 'Runs' },
65
+ { id: 'cleanup', label: 'Cleanup' },
66
+ ];
67
+
68
+ const inputStyle = {
69
+ bg: 'var(--color-input-bg)',
70
+ borderColor: 'var(--color-input-border)',
71
+ color: 'var(--color-text)',
72
+ } as const;
73
+
74
+ const errorMessage = (error: unknown) => (error as ApiError)?.message || String(error);
75
+ const fail = (title: string) => (error: unknown) =>
76
+ toaster.create({ title, description: errorMessage(error), type: 'error', closable: true });
77
+
78
+ // ─── Formatting ─────────────────────────────────────────────────────
79
+
80
+ export function formatDuration(s: number | null | undefined): string {
81
+ if (s == null) return '—';
82
+ if (s < 1) return `${Math.round(s * 1000)} ms`;
83
+ if (s < 60) return `${s.toFixed(s < 10 ? 2 : 1)} s`;
84
+ if (s < 3600) return `${Math.floor(s / 60)} m ${Math.round(s % 60)} s`;
85
+ return `${Math.floor(s / 3600)} h ${Math.round((s % 3600) / 60)} m`;
86
+ }
87
+
88
+ function ago(ts: number | null | undefined, now: number = Date.now() / 1000): string {
89
+ if (!ts) return '—';
90
+ const s = now - ts;
91
+ if (s < 0) return `in ${formatDuration(-s)}`;
92
+ if (s < 60) return `${Math.round(s)} s ago`;
93
+ if (s < 3600) return `${Math.round(s / 60)} min ago`;
94
+ if (s < 86400) return `${Math.round(s / 3600)} h ago`;
95
+ return `${Math.round(s / 86400)} d ago`;
96
+ }
97
+
98
+ const when = (ts: number | null | undefined) => (ts ? new Date(ts * 1000).toLocaleString() : '—');
99
+
100
+ const STATUS_COLORS: Record<JanitorStatus, string> = { ok: 'green', failed: 'red', timeout: 'orange', skipped: 'gray' };
101
+
102
+ const StatusBadge: React.FC<{ status: JanitorStatus | null | undefined; error?: string | null }> = ({ status, error }) => {
103
+ if (!status) return <Text color="var(--color-text-muted)">—</Text>;
104
+ const badge = <Badge size="sm" colorPalette={STATUS_COLORS[status] || 'gray'}>{status}</Badge>;
105
+ return error ? <Tooltip content={error} showArrow>{badge}</Tooltip> : badge;
106
+ };
107
+
108
+ const Direction: React.FC<{ direction: string | null; node?: unknown }> = ({ direction, node }) => {
109
+ if (direction === 'pull' && node) {
110
+ // early sync: straight from the compute node the job runs on
111
+ return (
112
+ <Tooltip content={`early sync: compute node ${String(node)} → this machine`} showArrow>
113
+ <Badge size="sm" variant="subtle" colorPalette="teal"><LuArrowDown /> pull ← {String(node).split('.')[0]}</Badge>
114
+ </Tooltip>
115
+ );
116
+ }
117
+ if (direction === 'pull') return <Tooltip content="pull: cluster → this machine" showArrow><Badge size="sm" variant="subtle"><LuArrowDown /> pull</Badge></Tooltip>;
118
+ if (direction === 'push') return <Tooltip content="push: this machine → cluster" showArrow><Badge size="sm" variant="subtle" colorPalette="purple"><LuArrowUp /> push</Badge></Tooltip>;
119
+ return <Text color="var(--color-text-muted)">—</Text>;
120
+ };
121
+
122
+ const Muted: React.FC<{ children: React.ReactNode }> = ({ children }) => (
123
+ <Text fontSize="sm" color="var(--color-text-muted)" fontStyle="italic">{children}</Text>
124
+ );
125
+
126
+ const SubHeading: React.FC<{ children: React.ReactNode }> = ({ children }) => (
127
+ <Text fontSize="sm" fontWeight="semibold" color="var(--color-text)">{children}</Text>
128
+ );
129
+
130
+ /** Re-render every second (elapsed times of the running tasks) */
131
+ function useNow(): number {
132
+ const [now, setNow] = useState(Date.now() / 1000);
133
+ useEffect(() => {
134
+ const timer = window.setInterval(() => setNow(Date.now() / 1000), 1000);
135
+ return () => window.clearInterval(timer);
136
+ }, []);
137
+ return now;
138
+ }
139
+
140
+ // ─── Running now + sync queue ───────────────────────────────────────
141
+
142
+ const RunningCard: React.FC<{ data: JanitorOverview }> = ({ data }) => {
143
+ const now = useNow();
144
+ return (
145
+ <LinkableCard
146
+ id="running"
147
+ icon={<LuActivity />}
148
+ title="Running now"
149
+ subtitle="The background tasks in progress (rsync, ssh, book keeping, ...) and the rsyncs waiting for their cluster."
150
+ >
151
+ {data.active.length === 0 ? <Muted>Nothing running.</Muted> : (
152
+ <Table.Root size="sm" variant="outline">
153
+ <Table.Header>
154
+ <Table.Row>
155
+ {['Task', 'Kind', 'Cluster', 'Started', 'Running for', 'pid'].map(h => <Table.ColumnHeader key={h}>{h}</Table.ColumnHeader>)}
156
+ </Table.Row>
157
+ </Table.Header>
158
+ <Table.Body>
159
+ {data.active.map(t => (
160
+ <Table.Row key={t.id}>
161
+ <Table.Cell fontFamily="mono" fontSize="xs">
162
+ <Tooltip content={String(t.detail?.command ?? '') || t.name} showArrow><span>{t.name}</span></Tooltip>
163
+ </Table.Cell>
164
+ <Table.Cell><Badge size="sm" variant="subtle">{t.kind}</Badge></Table.Cell>
165
+ <Table.Cell>{t.cluster || '—'}</Table.Cell>
166
+ <Table.Cell fontSize="xs">{when(t.started)}</Table.Cell>
167
+ <Table.Cell>{formatDuration(now - t.started)}</Table.Cell>
168
+ <Table.Cell fontSize="xs" color="var(--color-text-muted)">{t.pid ?? '—'}</Table.Cell>
169
+ </Table.Row>
170
+ ))}
171
+ </Table.Body>
172
+ </Table.Root>
173
+ )}
174
+ <Box>
175
+ <SubHeading>Sync queue</SubHeading>
176
+ <Text fontSize="sm" color="var(--color-text-muted)" mb={2}>
177
+ One rsync per cluster at a time, first come first served, shared by the server and the CLI commands.
178
+ </Text>
179
+ {data.queue.length === 0 ? <Muted>Empty.</Muted> : (
180
+ <Table.Root size="sm" variant="outline">
181
+ <Table.Header>
182
+ <Table.Row>
183
+ {['Cluster', 'For', 'State', 'Queued'].map(h => <Table.ColumnHeader key={h}>{h}</Table.ColumnHeader>)}
184
+ </Table.Row>
185
+ </Table.Header>
186
+ <Table.Body>
187
+ {data.queue.map(q => (
188
+ <Table.Row key={q.id}>
189
+ <Table.Cell>{q.cluster}</Table.Cell>
190
+ <Table.Cell fontFamily="mono" fontSize="xs">{q.what || '—'}</Table.Cell>
191
+ <Table.Cell>
192
+ {q.started
193
+ ? <Badge size="sm" colorPalette="blue">running {formatDuration(now - q.started)}</Badge>
194
+ : <Badge size="sm" colorPalette="yellow">waiting</Badge>}
195
+ </Table.Cell>
196
+ <Table.Cell fontSize="xs">{ago(q.queued, now)}</Table.Cell>
197
+ </Table.Row>
198
+ ))}
199
+ </Table.Body>
200
+ </Table.Root>
201
+ )}
202
+ </Box>
203
+ </LinkableCard>
204
+ );
205
+ };
206
+
207
+ // ─── Periodic jobs ──────────────────────────────────────────────────
208
+
209
+ const PERIODIC_HELP: Record<string, string> = {
210
+ 'job sync': 'pulls the job folders of the clusters that have unfinished jobs (rsync), then updates the index of the jobs page for what changed. Not a database sync.',
211
+ book_keeping: 'hourly: full rsync of each cluster, accounting of the finished jobs, then removal of their folders on the cluster',
212
+ scheduled_check: 'submits the scheduled jobs that are due',
213
+ janitor_prune: 'removes the history older than the retention',
214
+ index: 'every job folder against the index (after the book keeping)',
215
+ organize: 'the organizer folders (clusters/, experiments/, groups/)',
216
+ };
217
+
218
+ const PeriodicCard: React.FC<{ data: JanitorOverview }> = ({ data }) => (
219
+ <LinkableCard id="periodic" icon={<LuCalendarClock />} title="Periodic jobs" subtitle="What runs on its own, when it runs next and how its last run went.">
220
+ {data.periodic.length === 0 ? <Muted>No periodic job (the server was started without its scheduler).</Muted> : (
221
+ <Table.Root size="sm" variant="outline">
222
+ <Table.Header>
223
+ <Table.Row>
224
+ {['Job', 'What it does', 'Every', 'Next run', 'Last run', 'Took', 'Data', 'Status'].map(h => <Table.ColumnHeader key={h}>{h}</Table.ColumnHeader>)}
225
+ </Table.Row>
226
+ </Table.Header>
227
+ <Table.Body>
228
+ {data.periodic.map(p => (
229
+ <Table.Row key={p.name}>
230
+ <Table.Cell>
231
+ <Tooltip content={PERIODIC_HELP[p.name] || p.name} showArrow>
232
+ <Text fontFamily="mono" fontSize="xs">{p.name}</Text>
233
+ </Tooltip>
234
+ </Table.Cell>
235
+ <Table.Cell fontSize="xs" color="var(--color-text-muted)" maxW="380px">{PERIODIC_HELP[p.name] || '—'}</Table.Cell>
236
+ <Table.Cell>{p.interval ? formatDuration(p.interval) : p.id ? 'when due' : '—'}</Table.Cell>
237
+ <Table.Cell fontSize="xs">{p.next_run ? <Tooltip content={when(p.next_run)} showArrow><span>{ago(p.next_run)}</span></Tooltip> : '—'}</Table.Cell>
238
+ <Table.Cell fontSize="xs">{p.last ? <Tooltip content={when(p.last.ended)} showArrow><span>{ago(p.last.ended)}</span></Tooltip> : 'never'}</Table.Cell>
239
+ <Table.Cell>{formatDuration(p.last?.duration)}</Table.Cell>
240
+ <Table.Cell fontSize="xs"><Bytes bytesIn={p.last?.bytes_in} bytesOut={p.last?.bytes_out} /></Table.Cell>
241
+ <Table.Cell><StatusBadge status={p.last?.status} error={p.last?.error} /></Table.Cell>
242
+ </Table.Row>
243
+ ))}
244
+ </Table.Body>
245
+ </Table.Root>
246
+ )}
247
+ </LinkableCard>
248
+ );
249
+
250
+ // ─── Runs ───────────────────────────────────────────────────────────
251
+
252
+ export function formatBytes(n: number | null | undefined): string {
253
+ if (n == null) return '—';
254
+ if (n < 1024) return `${n} B`;
255
+ const units = ['KB', 'MB', 'GB', 'TB'];
256
+ let v = n / 1024;
257
+ let i = 0;
258
+ while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
259
+ return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;
260
+ }
261
+
262
+ /** in ↓ / out ↑, the side that moved data */
263
+ const Bytes: React.FC<{ bytesIn: number | null | undefined; bytesOut: number | null | undefined }> = ({ bytesIn, bytesOut }) => {
264
+ if (bytesIn == null && bytesOut == null) return <Text color="var(--color-text-muted)">—</Text>;
265
+ return (
266
+ <Tooltip content={`received ${formatBytes(bytesIn ?? 0)}, sent ${formatBytes(bytesOut ?? 0)}`} showArrow>
267
+ <Text as="span" whiteSpace="nowrap">
268
+ {bytesIn ? <>↓ {formatBytes(bytesIn)}</> : null}
269
+ {bytesIn && bytesOut ? ' ' : null}
270
+ {bytesOut ? <>↑ {formatBytes(bytesOut)}</> : null}
271
+ {!bytesIn && !bytesOut ? '0 B' : null}
272
+ </Text>
273
+ </Tooltip>
274
+ );
275
+ };
276
+
277
+ const RunsTable: React.FC<{ runs: JanitorRun[] }> = ({ runs }) => (
278
+ <Box overflowX="auto" maxH="480px" overflowY="auto">
279
+ <Table.Root size="sm" variant="outline" stickyHeader>
280
+ {/* the frozen header carries its own background, above the rows scrolling under it */}
281
+ <Table.Header bg="bg.muted" zIndex={1}>
282
+ <Table.Row>
283
+ {['When', 'Task', 'Cluster', 'Way', 'Took', 'Waited', 'Data', 'Status', 'Detail'].map(h => (
284
+ <Table.ColumnHeader key={h} bg="bg.muted">{h}</Table.ColumnHeader>
285
+ ))}
286
+ </Table.Row>
287
+ </Table.Header>
288
+ <Table.Body>
289
+ {runs.map(r => {
290
+ const d = r.detail || {};
291
+ const detail = [
292
+ d.jr_job_id ? `job ${d.jr_job_id}` : '',
293
+ d.files != null ? `${d.files} files transferred` : '',
294
+ d.http_status ? `HTTP ${d.http_status}` : '',
295
+ d.changed != null ? `${d.changed} jobs changed` : '',
296
+ d.moved != null ? `${d.moved} moved` : '',
297
+ d.removed != null ? `${d.removed} removed` : '',
298
+ d.remaining != null ? `${d.remaining} left on the cluster` : '',
299
+ ].filter(Boolean).join(', ');
300
+ return (
301
+ <Table.Row key={r.id}>
302
+ <Table.Cell fontSize="xs" whiteSpace="nowrap"><Tooltip content={when(r.started)} showArrow><span>{ago(r.started)}</span></Tooltip></Table.Cell>
303
+ <Table.Cell fontFamily="mono" fontSize="xs">
304
+ <Tooltip content={String(d.command ?? '') || r.name} showArrow><span>{r.name}</span></Tooltip>
305
+ </Table.Cell>
306
+ <Table.Cell>{r.cluster || '—'}</Table.Cell>
307
+ <Table.Cell><Direction direction={r.direction} node={d.node} /></Table.Cell>
308
+ <Table.Cell whiteSpace="nowrap">{formatDuration(r.duration)}</Table.Cell>
309
+ <Table.Cell whiteSpace="nowrap" color="var(--color-text-muted)">{r.waited ? formatDuration(r.waited) : '—'}</Table.Cell>
310
+ <Table.Cell fontSize="xs"><Bytes bytesIn={r.bytes_in} bytesOut={r.bytes_out} /></Table.Cell>
311
+ <Table.Cell><StatusBadge status={r.status} error={r.error} /></Table.Cell>
312
+ <Table.Cell fontSize="xs" color="var(--color-text-muted)">{detail || '—'}</Table.Cell>
313
+ </Table.Row>
314
+ );
315
+ })}
316
+ </Table.Body>
317
+ </Table.Root>
318
+ </Box>
319
+ );
320
+
321
+ const Select: React.FC<{ value: string; onChange: (v: string) => void; options: [string, string][]; w?: string }> = ({ value, onChange, options, w = '160px' }) => (
322
+ <NativeSelect.Root size="sm" w={w}>
323
+ <NativeSelect.Field {...inputStyle} value={value} onChange={(e) => onChange(e.target.value)}>
324
+ {options.map(([v, label]) => <option key={v} value={v}>{label}</option>)}
325
+ </NativeSelect.Field>
326
+ <NativeSelect.Indicator />
327
+ </NativeSelect.Root>
328
+ );
329
+
330
+ // ─── Clusters ───────────────────────────────────────────────────────
331
+
332
+ const ClustersCard: React.FC<{ data: JanitorOverview }> = ({ data }) => {
333
+ const clusters = Object.entries(data.clusters).sort(([a], [b]) => a.localeCompare(b));
334
+ return (
335
+ <LinkableCard
336
+ id="clusters"
337
+ icon={<LuServer />}
338
+ title="Cluster load"
339
+ subtitle="What bujang asked of each cluster over the last 24 hours: every ssh, rsync and scp, the time they took and the data they moved (↓ to this machine, ↑ to the cluster)."
340
+ >
341
+ {clusters.length === 0 ? <Muted>No call to a cluster in the last 24 hours.</Muted> : (
342
+ <Table.Root size="sm" variant="outline">
343
+ <Table.Header>
344
+ <Table.Row>
345
+ {['Cluster', 'Calls', 'of which rsync', 'Time spent', 'Waited in the queue', 'Data', 'Failures'].map(h => <Table.ColumnHeader key={h}>{h}</Table.ColumnHeader>)}
346
+ </Table.Row>
347
+ </Table.Header>
348
+ <Table.Body>
349
+ {clusters.map(([name, c]) => (
350
+ <Table.Row key={name}>
351
+ <Table.Cell fontWeight="semibold">{name}</Table.Cell>
352
+ <Table.Cell>{c.calls}</Table.Cell>
353
+ <Table.Cell>{c.rsyncs}</Table.Cell>
354
+ <Table.Cell>{formatDuration(c.seconds)}</Table.Cell>
355
+ <Table.Cell>{formatDuration(c.waited)}</Table.Cell>
356
+ <Table.Cell><Bytes bytesIn={c.bytes_in} bytesOut={c.bytes_out} /></Table.Cell>
357
+ <Table.Cell>{c.failures ? <Badge size="sm" colorPalette="red">{c.failures}</Badge> : 0}</Table.Cell>
358
+ </Table.Row>
359
+ ))}
360
+ </Table.Body>
361
+ </Table.Root>
362
+ )}
363
+ </LinkableCard>
364
+ );
365
+ };
366
+
367
+ // ─── Tasks: totals, then the runs ───────────────────────────────────
368
+
369
+ const KINDS: [string, string][] = [
370
+ ['', 'All kinds'], ['periodic', 'periodic'], ['submit', 'submissions'], ['rsync', 'rsync'], ['scp', 'scp'], ['ssh', 'ssh'],
371
+ ['request', 'slow requests (> 1 s)'], ['cleanup', 'cleanups'],
372
+ ];
373
+
374
+ const TasksCard: React.FC<{ data: JanitorOverview }> = ({ data }) => {
375
+ const queryClient = useQueryClient();
376
+ const [period, setPeriod] = useState<'day' | 'week'>('day');
377
+ const [kind, setKind] = useState('');
378
+ const [cluster, setCluster] = useState('');
379
+ const [status, setStatus] = useState('');
380
+ const [selected, setSelected] = useState<JanitorStat | null>(null);
381
+ const clusters = useMemo(() => Object.keys(data.clusters).sort(), [data.clusters]);
382
+ // slow requests (the pages, not the background) only when asked for
383
+ const shownKind = (k: string) => (kind ? k === kind : k !== 'request');
384
+ const stats = data.stats[period].filter(s => shownKind(s.kind) && (!cluster || s.cluster === cluster));
385
+
386
+ const { data: history, isLoading } = useQuery({
387
+ queryKey: ['bujang-janitor-history', kind, cluster, status, selected?.name, selected?.cluster],
388
+ queryFn: () => getJanitorHistory({
389
+ kind: (selected?.kind ?? kind) || undefined,
390
+ name: selected?.name,
391
+ cluster: (selected ? selected.cluster : cluster) || undefined,
392
+ status: status || undefined,
393
+ limit: 300,
394
+ }),
395
+ refetchInterval: POLL_MS,
396
+ });
397
+ const prune = useMutation({
398
+ mutationFn: janitorPrune,
399
+ onSuccess: (out) => {
400
+ toaster.create({ title: `Removed ${out.removed} old runs`, type: 'success' });
401
+ queryClient.invalidateQueries({ queryKey: ['bujang-janitor-history'] });
402
+ },
403
+ onError: fail('Could not prune the history'),
404
+ });
405
+ const key = (s: JanitorStat) => `${s.name}|${s.kind}|${s.cluster}`;
406
+
407
+ // two cards sharing their filters: the totals (Tasks), and the runs behind them (Runs)
408
+ return (
409
+ <>
410
+ <LinkableCard
411
+ id="tasks"
412
+ icon={<LuGauge />}
413
+ title="Tasks"
414
+ subtitle={<>
415
+ The totals per background task, slowest in total first. Requests slower than a second are here too.
416
+ Click a row to see its runs below.
417
+ </>}
418
+ >
419
+ <HStack gap={2} wrap="wrap">
420
+ <Select value={period} onChange={(v) => setPeriod(v as 'day' | 'week')} options={[['day', 'Last 24 hours'], ['week', 'Last 7 days']]} w="150px" />
421
+ <Select value={kind} onChange={(v) => { setKind(v); setSelected(null); }} options={KINDS} />
422
+ <Select value={cluster} onChange={(v) => { setCluster(v); setSelected(null); }} options={[['', 'All clusters'], ...clusters.map(c => [c, c] as [string, string])]} />
423
+ </HStack>
424
+ {stats.length === 0 ? <Muted>Nothing recorded yet.</Muted> : (
425
+ <Box overflowX="auto">
426
+ <Table.Root size="sm" variant="outline" interactive>
427
+ <Table.Header>
428
+ <Table.Row>
429
+ {['Task', 'Kind', 'Cluster', 'Runs', 'Failed', 'Mean', 'p95', 'Max', 'Total', 'Data', 'Last'].map(h => (
430
+ <Table.ColumnHeader key={h} textAlign={['Task', 'Kind', 'Cluster', 'Data', 'Last'].includes(h) ? 'start' : 'end'}>{h}</Table.ColumnHeader>
431
+ ))}
432
+ </Table.Row>
433
+ </Table.Header>
434
+ <Table.Body>
435
+ {stats.map(s => {
436
+ const active = selected && key(selected) === key(s);
437
+ return (
438
+ <Table.Row key={key(s)} cursor="pointer" bg={active ? 'var(--color-bg-stripe)' : undefined}
439
+ onClick={() => setSelected(active ? null : s)}>
440
+ <Table.Cell fontFamily="mono" fontSize="xs">
441
+ <Tooltip content={PERIODIC_HELP[s.name] || s.name} showArrow><span>{s.name}</span></Tooltip>
442
+ </Table.Cell>
443
+ <Table.Cell><Badge size="sm" variant="subtle">{s.kind}</Badge></Table.Cell>
444
+ <Table.Cell>{s.cluster || '—'}</Table.Cell>
445
+ <Table.Cell textAlign="end">{s.runs}</Table.Cell>
446
+ <Table.Cell textAlign="end">{s.failures ? <Badge size="sm" colorPalette="red">{s.failures}</Badge> : 0}</Table.Cell>
447
+ <Table.Cell textAlign="end">{formatDuration(s.mean)}</Table.Cell>
448
+ <Table.Cell textAlign="end">{formatDuration(s.p95)}</Table.Cell>
449
+ <Table.Cell textAlign="end">{formatDuration(s.max)}</Table.Cell>
450
+ <Table.Cell textAlign="end" fontWeight="semibold">{formatDuration(s.total)}</Table.Cell>
451
+ <Table.Cell fontSize="xs"><Bytes bytesIn={s.bytes_in} bytesOut={s.bytes_out} /></Table.Cell>
452
+ <Table.Cell><StatusBadge status={s.last_status} /></Table.Cell>
453
+ </Table.Row>
454
+ );
455
+ })}
456
+ </Table.Body>
457
+ </Table.Root>
458
+ </Box>
459
+ )}
460
+ </LinkableCard>
461
+ <LinkableCard
462
+ id="runs"
463
+ icon={<LuHistory />}
464
+ title={selected ? `Runs of ${selected.name}${selected.cluster ? ` on ${selected.cluster}` : ''}` : 'Runs'}
465
+ subtitle={<>
466
+ Every run, most recent first{selected ? '' : ', with the kind and cluster chosen in Tasks'}. Kept{' '}
467
+ {data.history_days} days (<Code fontSize="xs">task_history_days</Code>), pruned once a day.
468
+ </>}
469
+ actions={<Button size="xs" variant="outline" loading={prune.isPending} onClick={() => prune.mutate()}>Prune now</Button>}
470
+ >
471
+ <HStack gap={2} wrap="wrap">
472
+ <Select value={status} onChange={setStatus} options={[['', 'Any status'], ['ok', 'ok'], ['failed', 'failed'], ['timeout', 'timeout'], ['skipped', 'skipped']]} w="140px" />
473
+ {selected && <Button size="xs" variant="ghost" onClick={() => setSelected(null)}>Show every task</Button>}
474
+ </HStack>
475
+ {isLoading ? <Spinner /> : history && history.runs.length > 0
476
+ ? <RunsTable runs={selected ? history.runs : history.runs.filter(r => shownKind(r.kind))} />
477
+ : <Muted>None recorded.</Muted>}
478
+ </LinkableCard>
479
+ </>
480
+ );
481
+ };
482
+
483
+ // ─── Cleanup ────────────────────────────────────────────────────────
484
+
485
+ const SkippedList: React.FC<{ skipped: JanitorSkipped[] }> = ({ skipped }) => {
486
+ if (!skipped.length) return null;
487
+ const byReason: Record<string, string[]> = {};
488
+ for (const s of skipped) (byReason[s.reason] ||= []).push(s.jr_job_id);
489
+ return (
490
+ <VStack align="stretch" gap={1}>
491
+ {Object.entries(byReason).map(([reason, ids]) => (
492
+ <Text key={reason} fontSize="xs" color="var(--color-text-muted)">
493
+ left alone, {reason} ({ids.length}): {ids.slice(0, 12).join(', ')}{ids.length > 12 ? ', …' : ''}
494
+ </Text>
495
+ ))}
496
+ </VStack>
497
+ );
498
+ };
499
+
500
+ const ArchiveTool: React.FC = () => {
501
+ const queryClient = useQueryClient();
502
+ const paths = useBujangPaths();
503
+ const { data: info } = useQuery({ queryKey: ['bujang-janitor-cleanup'], queryFn: getJanitorCleanup });
504
+ const [organizer, setOrganizer] = useState('experiments');
505
+ const [value, setValue] = useState('');
506
+ const [plan, setPlan] = useState<JanitorArchiveResult | null>(null);
507
+ const organizers = info?.organizers ?? [];
508
+ const values = organizers.find(o => o.name === organizer)?.values ?? [];
509
+ useEffect(() => { if (organizers.length && !organizers.some(o => o.name === organizer)) setOrganizer(organizers[0].name); }, [organizers, organizer]);
510
+
511
+ const preview = useMutation({
512
+ mutationFn: () => janitorArchive({ organizer, value: value || null, dry_run: true }),
513
+ onSuccess: setPlan,
514
+ onError: fail('Preview failed'),
515
+ });
516
+ const apply = useMutation({
517
+ mutationFn: () => janitorArchive({ organizer, value: value || null, dry_run: false }),
518
+ onSuccess: (out) => {
519
+ setPlan(null);
520
+ toaster.create({ title: `Archived ${out.moved?.length ?? 0} job folders`, type: 'success' });
521
+ queryClient.invalidateQueries({ queryKey: ['bujang-janitor-cleanup'] });
522
+ queryClient.invalidateQueries({ queryKey: OVERVIEW_KEY });
523
+ },
524
+ onError: fail('Archive failed'),
525
+ });
526
+
527
+ return (
528
+ <Box>
529
+ <HStack gap={2} mb={1}><LuArchive /><SubHeading>Archive an experiment or a group</SubHeading></HStack>
530
+ <Text fontSize="sm" color="var(--color-text-muted)" mb={3}>
531
+ Moves the job folders out of <Code fontSize="xs">jobs/</Code> into <Code fontSize="xs">&lt;organizer&gt;/&lt;value&gt;/</Code>:
532
+ the link there becomes the folder itself, so <Code fontSize="xs">jobs/</Code> keeps only what is still moving.
533
+ The jobs stay on every page. A pipeline run moves with its steps: the run folder, its steps inside it.
534
+ Jobs not over or still on their cluster are left where they are (a run with such a step too).
535
+ </Text>
536
+ <HStack gap={2} wrap="wrap">
537
+ <Select value={organizer} onChange={(v) => { setOrganizer(v); setValue(''); setPlan(null); }}
538
+ options={organizers.map(o => [o.name, o.name] as [string, string])} />
539
+ <Select value={value} onChange={(v) => { setValue(v); setPlan(null); }} w="240px"
540
+ options={[['', `every ${organizer} folder`], ...values.map(v => [v.value, `${v.value} (${v.jobs})`] as [string, string])]} />
541
+ <Button size="sm" variant="outline" colorPalette="blue" loading={preview.isPending} onClick={() => preview.mutate()}>Preview</Button>
542
+ </HStack>
543
+ {plan && (
544
+ <VStack align="stretch" gap={2} mt={3}>
545
+ {(plan.would_move ?? []).length === 0
546
+ ? <Muted>Nothing to move.</Muted>
547
+ : (
548
+ <>
549
+ <Text fontSize="sm" color="var(--color-text)">{plan.would_move!.length} job folders move:</Text>
550
+ <Box maxH="200px" overflowY="auto" fontFamily="mono" fontSize="xs" color="var(--color-text-muted)">
551
+ {plan.would_move!.map(m => (
552
+ <Box key={m.jr_job_id}>
553
+ <Link to={paths.jobLogs(NO_JOB_ID, m.jr_job_id)}>{m.jr_job_id}</Link>: {m.from} → {m.to}
554
+ </Box>
555
+ ))}
556
+ </Box>
557
+ </>
558
+ )}
559
+ <SkippedList skipped={plan.skipped} />
560
+ <HStack gap={2}>
561
+ {(plan.would_move ?? []).length > 0 && (
562
+ <Button size="sm" colorPalette="blue" loading={apply.isPending} onClick={() => apply.mutate()}>
563
+ Move {plan.would_move!.length} folders
564
+ </Button>
565
+ )}
566
+ <Button size="sm" variant="ghost" onClick={() => setPlan(null)}>Cancel</Button>
567
+ </HStack>
568
+ </VStack>
569
+ )}
570
+ </Box>
571
+ );
572
+ };
573
+
574
+ const StaleTool: React.FC = () => {
575
+ const queryClient = useQueryClient();
576
+ const [days, setDays] = useState(7);
577
+ const [plan, setPlan] = useState<JanitorStaleResult | null>(null);
578
+ const preview = useMutation({
579
+ mutationFn: () => janitorRemoveStale({ older_than_days: days, dry_run: true }),
580
+ onSuccess: setPlan,
581
+ onError: fail('Preview failed'),
582
+ });
583
+ const apply = useMutation({
584
+ mutationFn: () => janitorRemoveStale({ older_than_days: days, dry_run: false }),
585
+ onSuccess: (out) => {
586
+ setPlan(null);
587
+ toaster.create({ title: `Removed ${out.removed?.length ?? 0} job folders`, type: 'success' });
588
+ queryClient.invalidateQueries({ queryKey: OVERVIEW_KEY });
589
+ },
590
+ onError: fail('Removal failed'),
591
+ });
592
+ return (
593
+ <Box borderTopWidth="1px" borderColor="var(--color-border)" pt={4}>
594
+ <HStack gap={2} mb={1}><LuTrash2 /><SubHeading>Remove the jobs that never ran</SubHeading></HStack>
595
+ <Text fontSize="sm" color="var(--color-text-muted)" mb={3}>
596
+ Job folders older than the limit with no log (<Code fontSize="xs">log.stdout</Code> / <Code fontSize="xs">log.stderr</Code> missing
597
+ or empty) and no result (nothing in <Code fontSize="xs">output/</Code>): a submission that failed, a job cancelled while pending.
598
+ Important jobs, jobs in a group, jobs not over and jobs still on their cluster stay.
599
+ </Text>
600
+ <HStack gap={2} wrap="wrap">
601
+ <Text fontSize="sm" color="var(--color-text-muted)">older than</Text>
602
+ <Input {...inputStyle} size="sm" type="number" w="80px" min={1} value={days}
603
+ onChange={(e) => { setDays(Math.max(1, Number(e.target.value) || 7)); setPlan(null); }} />
604
+ <Text fontSize="sm" color="var(--color-text-muted)">days</Text>
605
+ <Button size="sm" variant="outline" colorPalette="blue" loading={preview.isPending} onClick={() => preview.mutate()}>Preview</Button>
606
+ </HStack>
607
+ {plan && (
608
+ <VStack align="stretch" gap={2} mt={3}>
609
+ {(plan.would_remove ?? []).length === 0 ? <Muted>Nothing to remove.</Muted> : (
610
+ <>
611
+ <Text fontSize="sm" color="var(--color-text)">{plan.would_remove!.length} job folders go:</Text>
612
+ <Box maxH="200px" overflowY="auto" fontFamily="mono" fontSize="xs" color="var(--color-text-muted)">
613
+ {plan.would_remove!.map(r => (
614
+ <Box key={r.jr_job_id}>{r.folder} · {r.cluster || '—'} · {ago(r.modified)}</Box>
615
+ ))}
616
+ </Box>
617
+ </>
618
+ )}
619
+ <SkippedList skipped={plan.skipped} />
620
+ <HStack gap={2}>
621
+ {(plan.would_remove ?? []).length > 0 && (
622
+ <Button size="sm" colorPalette="red" loading={apply.isPending} onClick={() => apply.mutate()}>
623
+ Remove {plan.would_remove!.length} folders
624
+ </Button>
625
+ )}
626
+ <Button size="sm" variant="ghost" onClick={() => setPlan(null)}>Cancel</Button>
627
+ </HStack>
628
+ </VStack>
629
+ )}
630
+ </Box>
631
+ );
632
+ };
633
+
634
+ const CleanupCard: React.FC = () => (
635
+ <LinkableCard
636
+ id="cleanup"
637
+ icon={<LuBrush />}
638
+ title="Cleanup"
639
+ subtitle="Keep the job folder small: the pages and the background sync go faster. Both actions preview first; asking the clusters what they still hold takes a few seconds."
640
+ >
641
+ <ArchiveTool />
642
+ <StaleTool />
643
+ </LinkableCard>
644
+ );
645
+
646
+ // ─── Page ───────────────────────────────────────────────────────────
647
+
648
+ export const JanitorView: React.FC = () => {
649
+ usePageTitle('Janitor');
650
+ const paths = useBujangPaths();
651
+ const { data, isLoading, error, refetch, isFetching } = useQuery<JanitorOverview>({
652
+ queryKey: OVERVIEW_KEY,
653
+ queryFn: getJanitor,
654
+ refetchInterval: POLL_MS,
655
+ });
656
+ useHashScroll(!!data);
657
+
658
+ return (
659
+ <Box p={6} maxW="1200px">
660
+ <HStack mb={2} gap={3} color="var(--color-text)" justify="space-between">
661
+ <HStack gap={3}>
662
+ <LuBrush size={24} />
663
+ <Heading size="lg">Janitor</Heading>
664
+ </HStack>
665
+ <Button size="sm" variant="ghost" loading={isFetching} onClick={() => refetch()}><LuRefreshCw /> Refresh</Button>
666
+ </HStack>
667
+ <Text mb={3} color="var(--color-text-muted)">
668
+ What bujang does in the background, how long it takes and how hard it uses the clusters, and the cleanups
669
+ that keep it fast.
670
+ </Text>
671
+ <HStack mb={6} gap={2} wrap="wrap">
672
+ {SECTIONS.map(s => (
673
+ <Link key={s.id} to={paths.janitor(s.id)}>
674
+ <Badge variant="outline" cursor="pointer">{s.label}</Badge>
675
+ </Link>
676
+ ))}
677
+ </HStack>
678
+ {isLoading && <Spinner />}
679
+ {error && <Text color="var(--color-status-failed)">{errorMessage(error)}</Text>}
680
+ {data && (
681
+ <VStack align="stretch" gap={6}>
682
+ <RunningCard data={data} />
683
+ <PeriodicCard data={data} />
684
+ <ClustersCard data={data} />
685
+ <TasksCard data={data} />
686
+ <CleanupCard />
687
+ </VStack>
688
+ )}
689
+ </Box>
690
+ );
691
+ };
692
+
693
+ export default JanitorView;