@milabench/bujang 0.1.12 → 0.1.13

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.
@@ -16,183 +16,36 @@ import {
16
16
  VStack,
17
17
  Wrap,
18
18
  } from '@chakra-ui/react';
19
- import { useQuery } from '@tanstack/react-query';
20
- import { LuCopy, LuRefreshCw } from 'react-icons/lu';
21
- import { getJobData, getJobDataRows, jobDataRowsUrl } from '../api';
22
- import type { ApiError, JobData, JobDataField } from '../types';
19
+ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
20
+ import { LuCopy, LuPlus, LuRefreshCw } from 'react-icons/lu';
21
+ import {
22
+ getJobData,
23
+ getJobDataRows,
24
+ getJobOverviewLayout,
25
+ jobDataRowsUrl,
26
+ saveOverviewLayout,
27
+ updateSettings,
28
+ } from '../api';
29
+ import type { ApiError, JobData, JobDataField, JobOverviewLayout, OverviewLayout, OverviewPanel } from '../types';
23
30
  import { MonacoEditor } from '../components/MonacoEditor';
24
- import { useColorMode } from '../hooks/useColorMode';
25
31
  import { toaster } from '../toast';
26
-
27
- /** Rows fetched for a chart (the server caps at 500k) */
28
- const ROW_LIMIT = 50_000;
29
- /** Fields every row has: the file it comes from */
30
- const FILE_FIELDS: JobDataField[] = [
31
- { name: '_name', type: 'string', count: 0 },
32
- { name: '_file', type: 'string', count: 0 },
33
- ];
34
- const MARKS = ['point', 'line', 'bar', 'tick', 'boxplot', 'area', 'rect'] as const;
35
- const AGGREGATES = ['', 'mean', 'median', 'sum', 'min', 'max', 'count'] as const;
36
- /** The envelope events that are not data (the command, its output lines) */
37
- const NOISE_EVENTS = new Set(['line', 'config', 'meta', 'start', 'end', 'stop', 'error']);
38
-
39
- interface Builder {
40
- mark: (typeof MARKS)[number];
41
- x: string;
42
- y: string;
43
- yAggregate: (typeof AGGREGATES)[number];
44
- color: string;
45
- column: string;
46
- row: string;
47
- logX: boolean;
48
- logY: boolean;
49
- /** the number scales start at 0 (always for bar / area, whose length means something) */
50
- zero: boolean;
51
- }
52
-
53
- const EMPTY_BUILDER: Builder = {
54
- mark: 'point', x: '', y: '', yAggregate: '', color: '', column: '', row: '', logX: false, logY: false, zero: false,
55
- };
56
-
57
- const vlType = (field?: JobDataField) => (field?.type === 'number' ? 'quantitative' : 'nominal');
58
-
59
- /** A number field holding unix seconds (time, timestamp): shown as dates */
60
- const isUnixSeconds = (field?: JobDataField) =>
61
- !!field && field.type === 'number' && /time|stamp|date/i.test(field.name) &&
62
- (field.min ?? 0) > 1e9 && (field.max ?? 0) < 1e11;
63
-
64
- /** datum["a"]["b"] of a dotted field, for a Vega expression */
65
- const datumOf = (name: string) => `datum${name.split('.').map((p) => `[${JSON.stringify(p)}]`).join('')}`;
66
-
67
- /** Vega-Lite spec of the builder; the rows are the named dataset "rows" */
68
- const buildSpec = (b: Builder, fields: Map<string, JobDataField>): Record<string, unknown> => {
69
- const encoding: Record<string, unknown> = {};
70
- const transform: Record<string, unknown>[] = [];
71
- const keepsZero = b.zero || b.mark === 'bar' || b.mark === 'area';
72
- const channel = (name: string, extra: Record<string, unknown> = {}) => {
73
- const field = fields.get(name);
74
- if (isUnixSeconds(field)) {
75
- // seconds -> a date (Vega times are milliseconds)
76
- const as = `${name.replace(/\./g, '_')}_date`;
77
- if (!transform.some((t) => t.as === as)) transform.push({ calculate: `${datumOf(name)} * 1000`, as });
78
- return { field: as, type: 'temporal', title: name, ...extra };
79
- }
80
- const type = vlType(field);
81
- const scale = { ...(type === 'quantitative' && !keepsZero ? { zero: false } : {}), ...((extra.scale as object) || {}) };
82
- return { field: name, type, ...extra, ...(Object.keys(scale).length ? { scale } : {}) };
83
- };
84
- if (b.x) encoding.x = channel(b.x, b.logX ? { scale: { type: 'log' } } : {});
85
- if (b.y || b.yAggregate === 'count') {
86
- encoding.y = b.yAggregate === 'count'
87
- ? { aggregate: 'count', type: 'quantitative' }
88
- : channel(b.y, {
89
- ...(b.yAggregate ? { aggregate: b.yAggregate } : {}),
90
- ...(b.logY ? { scale: { type: 'log' } } : {}),
91
- });
92
- }
93
- if (b.color) encoding.color = channel(b.color, { legend: { labelLimit: 400 } });
94
- if (b.column) encoding.column = channel(b.column);
95
- if (b.row) encoding.row = channel(b.row);
96
- encoding.tooltip = [b.x, b.y, b.color, b.column, b.row, '_name']
97
- .filter((f, i, all) => f && all.indexOf(f) === i)
98
- .map((f) => ({ field: f, type: vlType(fields.get(f)) }));
99
- return {
100
- $schema: 'https://vega.github.io/schema/vega-lite/v5.json',
101
- data: { name: 'rows' },
102
- ...(transform.length ? { transform } : {}),
103
- // a composite mark (boxplot) takes no `tooltip` (Altair validates the spec)
104
- mark: { type: b.mark, ...(b.mark === 'boxplot' ? {} : { tooltip: true }), ...(b.mark === 'line' ? { point: true } : {}) },
105
- encoding,
106
- width: b.column ? 260 : 'container',
107
- height: 320,
108
- // the legend and the axes inside the container width, not past it
109
- ...(b.column ? {} : { autosize: { type: 'fit-x', contains: 'padding' } }),
110
- };
111
- };
112
-
113
- /** Defaults for a set of fields: a category on x, a rate-like number on y, the file as color */
114
- const guessBuilder = (fields: JobDataField[], multipleFiles: boolean): Builder => {
115
- const numbers = fields.filter((f) => f.type === 'number' && f.name !== 'time');
116
- // the categories with the most values first (test names before task: detail / train)
117
- const categories = fields
118
- .filter((f) => f.type === 'string' && f.name !== 'event' && f.values && f.values.length > 1 && f.values.length <= 40)
119
- .sort((a, b) => (b.values?.length || 0) - (a.values?.length || 0));
120
- const y = numbers.find((f) => /rate|throughput|loss|value/i.test(f.name)) || numbers[0];
121
- const x = categories[0] || fields.find((f) => f.name === 'time') || numbers.find((f) => f !== y);
122
- return {
123
- ...EMPTY_BUILDER,
124
- mark: x?.type === 'string' ? 'boxplot' : 'point',
125
- x: x?.name || '',
126
- y: y?.name || '',
127
- color: multipleFiles ? '_name' : categories[1]?.name || '',
128
- };
129
- };
130
-
131
- /** The fields a spec reads (to fetch only those): every `field` of it */
132
- const specFields = (spec: unknown, out = new Set<string>()): Set<string> => {
133
- if (Array.isArray(spec)) spec.forEach((item) => specFields(item, out));
134
- else if (spec && typeof spec === 'object') {
135
- for (const [key, value] of Object.entries(spec)) {
136
- if (key === 'field' && typeof value === 'string') out.add(value);
137
- else specFields(value, out);
138
- }
139
- }
140
- return out;
141
- };
142
-
143
- const isDarkPage = () =>
144
- typeof document !== 'undefined' &&
145
- (document.documentElement.classList.contains('dark') || document.documentElement.dataset.theme === 'dark');
146
-
147
- /** A Vega-Lite spec rendered with vega-embed (loaded on first use), `rows` as the dataset "rows" */
148
- const VegaChart: React.FC<{ spec: Record<string, unknown>; rows: Record<string, unknown>[] }> = ({ spec, rows }) => {
149
- const ref = useRef<HTMLDivElement>(null);
150
- const [error, setError] = useState<string | null>(null);
151
- const { colorMode } = useColorMode();
152
-
153
- useEffect(() => {
154
- let cancelled = false;
155
- let finalize: (() => void) | undefined;
156
- setError(null);
157
- import('vega-embed')
158
- .then(async ({ default: embed }) => {
159
- if (cancelled || !ref.current) return;
160
- const full = {
161
- ...spec,
162
- datasets: { ...((spec.datasets as object) || {}), rows },
163
- background: 'transparent',
164
- };
165
- const result = await embed(ref.current, full as never, {
166
- actions: { export: true, source: false, compiled: false, editor: false },
167
- theme: colorMode === 'dark' || isDarkPage() ? 'dark' : undefined,
168
- // canvas: the CSS reset of the page (font: inherit) would restyle the SVG texts Vega measured
169
- renderer: 'canvas',
170
- });
171
- if (cancelled) result.finalize();
172
- else finalize = result.finalize;
173
- })
174
- .catch((err: unknown) => !cancelled && setError(err instanceof Error ? err.message : String(err)));
175
- return () => {
176
- cancelled = true;
177
- finalize?.();
178
- };
179
- }, [spec, rows, colorMode]);
180
-
181
- return (
182
- <Box w="100%" minH="340px">
183
- {error && (
184
- <Alert.Root status="error" mb={2}>
185
- <Alert.Indicator />
186
- <Alert.Content>
187
- <Alert.Title>Chart error</Alert.Title>
188
- <Alert.Description fontFamily="mono" fontSize="xs">{error}</Alert.Description>
189
- </Alert.Content>
190
- </Alert.Root>
191
- )}
192
- <Box ref={ref} w="100%" />
193
- </Box>
194
- );
195
- };
32
+ import {
33
+ AGGREGATES,
34
+ type Builder,
35
+ EMPTY_BUILDER,
36
+ FILE_FIELDS,
37
+ MARKS,
38
+ ROLE_ORDER,
39
+ ROW_LIMIT,
40
+ VegaChart,
41
+ buildSpec,
42
+ filesWithEvent,
43
+ guessBuilder,
44
+ mergeFields,
45
+ panelOfBuilder,
46
+ specFields,
47
+ } from './dataCharts';
48
+ import { LayoutBar, LayoutPanels } from './OverviewPanels';
196
49
 
197
50
  const FieldSelect: React.FC<{
198
51
  label: string;
@@ -226,9 +79,10 @@ const formatRange = (f: JobDataField) => {
226
79
  };
227
80
 
228
81
  /**
229
- * The Overview tab of a job: the JSONL files of its artifact folders (output/, runs/, results/)
230
- * plotted with Vega-Lite. A builder writes the spec; the spec can be edited by hand, and is shown
231
- * with the rows URL as an Altair snippet.
82
+ * The Overview tab of a job: the panels of its layout (the log view, charts: GET
83
+ * /jobs/<jr>/overview/layout), then an explorer of the JSONL files of its artifact folders (output/,
84
+ * runs/, results/) plotted with Vega-Lite. Its builder writes the spec; the spec can be edited by hand,
85
+ * is shown with the rows URL as an Altair snippet, and can be added to the layout.
232
86
  */
233
87
  export const JobDataOverview: React.FC<{ jrJobId: string }> = ({ jrJobId }) => {
234
88
  const { data, isLoading, error, refetch, isFetching } = useQuery<JobData, ApiError>({
@@ -245,39 +99,23 @@ export const JobDataOverview: React.FC<{ jrJobId: string }> = ({ jrJobId }) => {
245
99
  [files, selectedFiles],
246
100
  );
247
101
 
248
- // events of the selected files, data events first
102
+ // events of the selected files, the plotted ones (role metric) first
249
103
  const events = useMemo(() => {
250
104
  const counts = new Map<string, number>();
251
- activeFiles.forEach((f) => f.events?.forEach((e) => counts.set(e.event, (counts.get(e.event) || 0) + e.count)));
105
+ const order = new Map<string, number>();
106
+ activeFiles.forEach((f) => f.events?.forEach((e) => {
107
+ counts.set(e.event, (counts.get(e.event) || 0) + e.count);
108
+ order.set(e.event, Math.min(order.get(e.event) ?? 9, ROLE_ORDER[e.role] ?? 0));
109
+ }));
252
110
  return [...counts.entries()].sort(
253
- (a, b) => Number(NOISE_EVENTS.has(a[0])) - Number(NOISE_EVENTS.has(b[0])) || b[1] - a[1],
111
+ (a, b) => (order.get(a[0]) ?? 0) - (order.get(b[0]) ?? 0) || b[1] - a[1],
254
112
  );
255
113
  }, [activeFiles]);
256
114
  const [event, setEvent] = useState<string | null>(null);
257
115
  const activeEvent = event !== null && events.some(([e]) => e === event) ? event : events[0]?.[0] ?? '';
258
116
 
259
117
  // fields of the event, merged over the selected files
260
- const fields = useMemo(() => {
261
- const merged = new Map<string, JobDataField>();
262
- activeFiles.forEach((f) =>
263
- f.events?.filter((e) => e.event === activeEvent).forEach((e) =>
264
- e.fields.forEach((field) => {
265
- const prev = merged.get(field.name);
266
- if (!prev) {
267
- merged.set(field.name, { ...field, values: field.values ? [...field.values] : field.values });
268
- return;
269
- }
270
- prev.count += field.count;
271
- if (prev.type !== field.type) prev.type = 'mixed';
272
- if (field.min !== undefined) prev.min = Math.min(prev.min ?? field.min, field.min);
273
- if (field.max !== undefined) prev.max = Math.max(prev.max ?? field.max, field.max);
274
- if (prev.values && field.values) prev.values = [...new Set([...prev.values, ...field.values])].sort();
275
- else if (field.values === null) prev.values = null;
276
- }),
277
- ),
278
- );
279
- return [...merged.values()];
280
- }, [activeFiles, activeEvent]);
118
+ const fields = useMemo(() => mergeFields(activeFiles, activeEvent), [activeFiles, activeEvent]);
281
119
  const fieldMap = useMemo(() => new Map([...fields, ...FILE_FIELDS].map((f) => [f.name, f])), [fields]);
282
120
  const fieldOptions = useMemo(() => [...fields, ...FILE_FIELDS], [fields]);
283
121
 
@@ -288,9 +126,9 @@ export const JobDataOverview: React.FC<{ jrJobId: string }> = ({ jrJobId }) => {
288
126
  useEffect(() => {
289
127
  if (fields.length && lastGuess.current !== guessKey) {
290
128
  lastGuess.current = guessKey;
291
- setBuilder(guessBuilder(fields, activeFiles.length > 1));
129
+ setBuilder(guessBuilder(fields, filesWithEvent(activeFiles, activeEvent).length > 1));
292
130
  }
293
- }, [guessKey, fields, activeFiles.length]);
131
+ }, [guessKey, fields, activeFiles, activeEvent]);
294
132
 
295
133
  // the spec: from the builder, or edited by hand
296
134
  const builtSpec = useMemo(() => buildSpec(builder, fieldMap), [builder, fieldMap]);
@@ -356,6 +194,48 @@ export const JobDataOverview: React.FC<{ jrJobId: string }> = ({ jrJobId }) => {
356
194
  setBuilder((b) => ({ ...b, ...patch }));
357
195
  };
358
196
 
197
+ // the layout: the server's, or the one being edited (`draft`, until saved or discarded)
198
+ const queryClient = useQueryClient();
199
+ const layoutKey = ['bujang-overview-layout', jrJobId];
200
+ const { data: found, error: layoutError } = useQuery<JobOverviewLayout, ApiError>({
201
+ queryKey: layoutKey,
202
+ queryFn: () => getJobOverviewLayout(jrJobId),
203
+ enabled: !!data,
204
+ staleTime: 30_000,
205
+ retry: false,
206
+ });
207
+ const [draft, setDraft] = useState<OverviewLayout | null>(null);
208
+ const [editing, setEditing] = useState(false);
209
+ const layout = draft ?? found?.layout ?? null;
210
+ const changeLayout = (next: OverviewLayout) => {
211
+ setDraft(next);
212
+ setEditing(true);
213
+ };
214
+ const saveLayout = useMutation<unknown, ApiError, { target: 'experiment' | 'script' | 'default'; layout: OverviewLayout | null }>({
215
+ mutationFn: ({ target, layout: value }) => {
216
+ if (target === 'default') return updateSettings({ overview_layout: value });
217
+ const key = target === 'experiment' ? found?.keys.experiment : found?.keys.script;
218
+ return saveOverviewLayout(target, key || '', value);
219
+ },
220
+ onSuccess: (_, { target, layout: value }) => {
221
+ setDraft(null);
222
+ setEditing(false);
223
+ queryClient.invalidateQueries({ queryKey: ['bujang-overview-layout'] });
224
+ const what = target === 'default' ? 'the default layout' : `the ${target} ${target === 'experiment' ? found?.keys.experiment : found?.keys.script}`;
225
+ toaster.create({ title: value ? `Layout saved for ${what}` : `Layout of ${what} removed`, type: 'success', duration: 3000 });
226
+ },
227
+ onError: (err) => toaster.create({ title: 'Could not save the layout', description: err.message, type: 'error' }),
228
+ });
229
+ const addToLayout = () => {
230
+ const base = layout ?? { panels: [] };
231
+ const chosen = selectedFiles === null ? {} : { files: activeFiles.map((f) => f.path).join(',') };
232
+ const panel: OverviewPanel = specText !== null && lastSpec
233
+ ? { kind: 'chart', title: activeEvent || 'records', event: activeEvent, spec: lastSpec, ...chosen }
234
+ : { ...panelOfBuilder(builder, activeEvent), ...chosen };
235
+ changeLayout({ panels: [...base.panels, panel] });
236
+ toaster.create({ title: 'Chart added to the layout', description: 'Save the layout to keep it.', type: 'info', duration: 3000 });
237
+ };
238
+
359
239
  if (isLoading) {
360
240
  return (
361
241
  <VStack py={10}><Spinner size="lg" /><Text>Reading the data files…</Text></VStack>
@@ -392,6 +272,35 @@ export const JobDataOverview: React.FC<{ jrJobId: string }> = ({ jrJobId }) => {
392
272
 
393
273
  return (
394
274
  <VStack align="stretch" gap={4} pb={6}>
275
+ {/* The layout and its panels */}
276
+ {layoutError && (
277
+ <Alert.Root status="error">
278
+ <Alert.Indicator />
279
+ <Alert.Description>Could not read the layout: {layoutError.message}</Alert.Description>
280
+ </Alert.Root>
281
+ )}
282
+ {found && layout && (
283
+ <>
284
+ <LayoutBar
285
+ found={found}
286
+ dirty={draft !== null}
287
+ editing={editing}
288
+ saving={saveLayout.isPending}
289
+ onEdit={setEditing}
290
+ onSave={(target) => saveLayout.mutate({ target, layout })}
291
+ onDiscard={() => { setDraft(null); setEditing(false); }}
292
+ onReset={() => {
293
+ const { kind, name } = found.source;
294
+ if ((kind === 'experiment' || kind === 'script') && window.confirm(`Remove the layout saved for the ${kind} ${name}?`)) {
295
+ saveLayout.mutate({ target: kind, layout: null });
296
+ }
297
+ }}
298
+ />
299
+ <LayoutPanels jrJobId={jrJobId} files={files} layout={layout} editing={editing} onChange={changeLayout} />
300
+ </>
301
+ )}
302
+
303
+ <Text fontSize="sm" fontWeight="semibold" pt={2}>Explore the data</Text>
395
304
  {/* Files and event */}
396
305
  <Card.Root {...cardProps}>
397
306
  <Card.Body py={3}>
@@ -496,6 +405,10 @@ export const JobDataOverview: React.FC<{ jrJobId: string }> = ({ jrJobId }) => {
496
405
  {rowsLoading && <Spinner size="xs" />}
497
406
  {rows && <Text>{rows.length}{rows.length >= ROW_LIMIT ? '+ (first rows only)' : ''} rows</Text>}
498
407
  {specText !== null && <Badge size="xs" colorPalette="orange">spec edited by hand</Badge>}
408
+ <Button size="2xs" variant="outline" ml="auto" onClick={addToLayout} disabled={!lastSpec}
409
+ title="Add this chart to the layout above (then save the layout)">
410
+ <LuPlus /> Add to layout
411
+ </Button>
499
412
  </HStack>
500
413
  {rowsError && (
501
414
  <Alert.Root status="error" mb={2}>