taxa-server 0.1.0

axum web server for taxa: reproduces the HTTP contract + serves the embedded D3 frontend.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
//! HTTP contract tests: slash-containing entity ids match, and invalid params
//! are rejected (400) rather than silently coerced. Driven via tower oneshot.

use std::sync::Arc;

use axum::body::Body;
use axum::http::{Request, StatusCode};
use polars::prelude::*;
use serde_json::json;
use taxa_core::{Backend, FrameBackend, FrameDataset, FrameSource};
use taxa_server::{build_router, build_router_ext};
use tower::ServiceExt;

fn app() -> axum::Router {
    let df = df![
        "fullname" => ["microsoft/vscode", "google/go"], // slash-containing id
        "owner" => ["microsoft", "google"],
        "dt" => Series::new("dt".into(), [20454i32, 20454]).cast(&DataType::Date).unwrap(),
        "stars" => [163000i64, 123000],
    ]
    .unwrap();
    let ds: FrameDataset = serde_json::from_value(json!({
        "source": "r", "id_column": "fullname", "label_column": "fullname",
        "timestamp_column": "dt",
        "axes": [{"id": "by_owner", "levels": ["owner", "fullname"]}],
        "metrics": [
            {"id": "stars", "agg": "sum", "column": "stars", "unit": "count"},
            {"id": "n", "agg": "count", "unit": "count"}
        ],
        "filters": [{"id": "owner", "column": "owner", "type": "categorical"}],
        "default_axis": "by_owner", "default_size_by": "stars"
    }))
    .unwrap();
    let backend: Arc<dyn Backend> = Arc::new(FrameBackend::new(Arc::new(FrameSource::new(df))));
    build_router(ds, backend, None)
}

async fn status(req: Request<Body>) -> StatusCode {
    app().oneshot(req).await.unwrap().status()
}

fn post(path: &str, body: serde_json::Value) -> Request<Body> {
    Request::builder()
        .method("POST")
        .uri(path)
        .header("content-type", "application/json")
        .body(Body::from(body.to_string()))
        .unwrap()
}

#[tokio::test]
async fn slash_entity_id_matches() {
    // `/api/entity/owner/repo` must hit the entity route (not the SPA fallback).
    let resp = app()
        .oneshot(
            Request::builder()
                .uri("/api/entity/microsoft/vscode")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(v["label"], json!("microsoft/vscode"));
}

#[tokio::test]
async fn unknown_entity_is_404() {
    assert_eq!(
        status(
            Request::builder()
                .uri("/api/entity/nope/nope")
                .body(Body::empty())
                .unwrap()
        )
        .await,
        StatusCode::NOT_FOUND
    );
}

#[tokio::test]
async fn invalid_params_are_400() {
    assert_eq!(
        status(post(
            "/api/series",
            json!({"axis": "by_owner", "metric": "stars", "agg": "bogus"})
        ))
        .await,
        StatusCode::BAD_REQUEST
    );
    assert_eq!(
        status(post(
            "/api/series",
            json!({"axis": "by_owner", "metric": "stars", "resolution": "zzz"})
        ))
        .await,
        StatusCode::BAD_REQUEST
    );
    assert_eq!(
        status(post(
            "/api/series",
            json!({"axis": "by_owner", "metric": "stars", "window": "nope"})
        ))
        .await,
        StatusCode::BAD_REQUEST
    );
    assert_eq!(
        status(post(
            "/api/series",
            json!({"axis": "nope", "metric": "stars"})
        ))
        .await,
        StatusCode::BAD_REQUEST
    );
    assert_eq!(
        status(post(
            "/api/treemap",
            json!({"axis": "by_owner", "filters": {"nope": "x"}})
        ))
        .await,
        StatusCode::BAD_REQUEST
    );
    assert_eq!(
        status(post(
            "/api/treemap",
            json!({"axis": "by_owner", "size_by": "bogus"})
        ))
        .await,
        StatusCode::BAD_REQUEST
    );
}

#[tokio::test]
async fn treemap_is_focus_bounded() {
    // Focus into "microsoft", depth 1 → the response is that subtree only
    // (its repos), NOT the whole owner tree.
    let resp = app()
        .oneshot(post(
            "/api/treemap",
            json!({"axis": "by_owner", "focus": ["root", "microsoft"], "depth": 1}),
        ))
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let t: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    let names: Vec<&str> = t["children"]
        .as_array()
        .unwrap()
        .iter()
        .map(|c| c["name"].as_str().unwrap())
        .collect();
    assert_eq!(names, ["microsoft/vscode"]); // microsoft's repo, not ["microsoft","google"]
    assert_eq!(t["stars"], json!(163000)); // root measure = microsoft's total
}

#[tokio::test]
async fn valid_requests_are_200() {
    assert_eq!(
        status(post(
            "/api/treemap",
            json!({"axis": "by_owner", "filters": {}})
        ))
        .await,
        StatusCode::OK
    );
    assert_eq!(
        status(post(
            "/api/treemap",
            json!({"axis": "by_owner", "filters": {"owner": ["microsoft"]}})
        ))
        .await,
        StatusCode::OK
    );
    assert_eq!(
        status(post(
            "/api/treemap",
            json!({"axis": "by_owner", "size_by": "n"})
        ))
        .await,
        StatusCode::OK
    );
    assert_eq!(
        status(post(
            "/api/series",
            json!({"axis": "by_owner", "metric": "stars", "agg": "median", "resolution": "w"})
        ))
        .await,
        StatusCode::OK
    );
    // size_by + top_k are parsed (treemap-aligned branch selection).
    assert_eq!(
        status(post(
            "/api/series",
            json!({"axis": "by_owner", "metric": "stars", "size_by": "stars", "top_k": 3})
        ))
        .await,
        StatusCode::OK
    );
    // Fix 1: a `size_by` that ISN'T a series metric (the Line tab always forwards
    // the current treemap size metric, which may be outside the reduced series
    // set) must NOT 400 — it falls back to ranking by the plotted metric.
    assert_eq!(
        status(post(
            "/api/series",
            json!({"axis": "by_owner", "metric": "stars", "size_by": "bogus"})
        ))
        .await,
        StatusCode::OK
    );
    // An over-cap top_k is clamped (not rejected).
    assert_eq!(
        status(post(
            "/api/series",
            json!({"axis": "by_owner", "metric": "stars", "top_k": 100000})
        ))
        .await,
        StatusCode::OK
    );
}

// An app with a SEPARATE series source/dataset routes /api/series to it. The
// series dataset carries a different timestamp column ("snap") and a metric the
// MAIN dataset lacks ("price") — a 200 proves the request bound against the
// series ds/backend, not the main one.
fn series_app() -> axum::Router {
    let main_df = df![
        "fullname" => ["microsoft/vscode", "google/go"],
        "owner" => ["microsoft", "google"],
        "stars" => [163000i64, 123000],
    ]
    .unwrap();
    let main_ds: FrameDataset = serde_json::from_value(json!({
        "source": "r", "id_column": "fullname", "label_column": "fullname",
        "axes": [{"id": "by_owner", "levels": ["owner", "fullname"]}],
        "metrics": [{"id": "stars", "agg": "sum", "column": "stars", "unit": "count"}],
        "filters": [{"id": "owner", "column": "owner", "type": "categorical"}],
        "default_axis": "by_owner", "default_size_by": "stars"
    }))
    .unwrap();
    let main_backend: Arc<dyn Backend> =
        Arc::new(FrameBackend::new(Arc::new(FrameSource::new(main_df))));

    // Dense timestamped series table with its OWN timestamp column + metric.
    let series_df = df![
        "fullname" => ["microsoft/vscode", "microsoft/vscode", "google/go"],
        "owner" => ["microsoft", "microsoft", "google"],
        "snap" => Series::new("snap".into(), [20454i32, 20461, 20454]).cast(&DataType::Date).unwrap(),
        "price" => [10.0f64, 12.0, 8.0],
    ]
    .unwrap();
    let series_ds: FrameDataset = serde_json::from_value(json!({
        "source": "s", "id_column": "fullname", "label_column": "fullname",
        "timestamp_column": "snap",
        "axes": [{"id": "by_owner", "levels": ["owner", "fullname"]}],
        "metrics": [{"id": "price", "agg": "sum", "column": "price", "unit": "money"}],
        "default_axis": "by_owner", "default_size_by": "price"
    }))
    .unwrap();
    let series_backend: Arc<dyn Backend> =
        Arc::new(FrameBackend::new(Arc::new(FrameSource::new(series_df))));

    build_router(main_ds, main_backend, Some((series_ds, series_backend)))
}

#[tokio::test]
async fn series_routes_to_series_backend() {
    // "price" exists ONLY in the series dataset; a 200 proves routing.
    let resp = series_app()
        .oneshot(post("/api/series", json!({
            "axis": "by_owner", "metric": "price", "size_by": "price", "top_k": 5, "window": "1y"
        })))
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(v["meta"]["metric_id"], json!("price"));
    assert!(!v["series"].as_array().unwrap().is_empty());

    // The MAIN-only metric "stars" is NOT in the series ds → rejected.
    assert_eq!(
        series_app()
            .oneshot(post(
                "/api/series",
                json!({"axis": "by_owner", "metric": "stars"})
            ))
            .await
            .unwrap()
            .status(),
        StatusCode::BAD_REQUEST
    );
}

#[tokio::test]
async fn entity_series_returns_one_line() {
    // `/api/entity/<id>/series` reads the series ds ("price" exists only there)
    // and returns the flat {dates,values,unit,label} the detail page consumes,
    // filtered to that one entity. The id ("microsoft/vscode") contains a slash.
    let resp = series_app()
        .oneshot(
            Request::builder()
                .uri("/api/entity/microsoft/vscode/series?metric=price&window=1y&resolution=w")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    // Only vscode's two price points (10, 12) — NOT google/go's 8.
    let vals: Vec<f64> = v["values"]
        .as_array()
        .unwrap()
        .iter()
        .map(|x| x.as_f64().unwrap())
        .collect();
    assert_eq!(vals, vec![10.0, 12.0]);
    assert_eq!(v["dates"].as_array().unwrap().len(), 2);
    assert_eq!(v["unit"], json!("money"));
    assert_eq!(v["metric_id"], json!("price"));
}

#[tokio::test]
async fn entity_ohlc_is_404() {
    // No price/OHLC source → 404 so entity.js falls back to the metric line.
    let resp = series_app()
        .oneshot(
            Request::builder()
                .uri("/api/entity/microsoft/vscode/ohlc?window=1y&resolution=w")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn series_non_series_size_by_falls_back_not_400() {
    // Fix 1: "stars" is a real metric but exists ONLY in the main ds, not the
    // reduced series ds. The Line tab forwards it as `size_by`; the engine must
    // fall back to ranking by the plotted (series) metric instead of 400-ing.
    let resp = series_app()
        .oneshot(post(
            "/api/series",
            json!({
                "axis": "by_owner", "metric": "price", "size_by": "stars"
            }),
        ))
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::OK,
        "non-series size_by must fall back, not 400"
    );
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(v["meta"]["metric_id"], json!("price"));
}

#[tokio::test]
async fn entity_id_ending_in_subroute_word_is_reachable() {
    // Fix 7: a bare "/api/entity/series" (id == "series", empty before the
    // suffix) must NOT be treated as the series subroute — it falls through to
    // the plain detail lookup (404 here since no such entity), NOT a "no metric"
    // 400 from the series branch.
    let resp = app()
        .oneshot(
            Request::builder()
                .uri("/api/entity/series")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::NOT_FOUND,
        "bare /series id is a detail lookup, not a subroute"
    );
    // Likewise a bare "/ohlc" id is a detail lookup (404), not the ohlc 404 branch
    // — both are 404 here, but the path matters: it must reach `detail`.
    let resp = app()
        .oneshot(
            Request::builder()
                .uri("/api/entity/ohlc")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

// A frames/views-style app: the MAIN (snapshot) ds ranks sectors by `mcap`; the
// SERIES ds plots `flow` and FOLLOWS THE TREEMAP for its branch set. The series
// frame lacks `mcap` entirely — proving the branch set is resolved on the
// snapshot, then applied to the series frame.
fn frames_views_app() -> axum::Router {
    // Snapshot: tech=1000, fin=500, energy=100 by mcap.
    let snap_df = df![
        "symbol" => ["A", "B", "C"],
        "sector" => ["tech", "fin", "energy"],
        "mcap" => [1000.0f64, 500.0, 100.0],
    ]
    .unwrap();
    let snap_ds: FrameDataset = serde_json::from_value(json!({
        "source": "snap", "id_column": "symbol", "label_column": "symbol",
        "axes": [{"id": "sector", "levels": ["sector", "symbol"]}],
        "metrics": [{"id": "mcap", "agg": "sum", "column": "mcap", "unit": "money"}],
        "default_axis": "sector", "default_size_by": "mcap"
    }))
    .unwrap();
    let snap_backend: Arc<dyn Backend> =
        Arc::new(FrameBackend::new(Arc::new(FrameSource::new(snap_df))));

    // Series: plots `flow`. energy has the biggest flow but is NOT a treemap top-2.
    let series_df = df![
        "symbol" => ["A", "B", "C"],
        "sector" => ["tech", "fin", "energy"],
        "date" => Series::new("date".into(), [20454i32, 20454, 20454]).cast(&DataType::Date).unwrap(),
        "flow" => [1.0f64, 2.0, 999.0],
    ]
    .unwrap();
    let series_ds: FrameDataset = serde_json::from_value(json!({
        "source": "facts", "id_column": "symbol", "label_column": "symbol", "timestamp_column": "date",
        "axes": [{"id": "sector", "levels": ["sector", "symbol"]}],
        "metrics": [{"id": "flow", "agg": "sum", "column": "flow", "unit": "number"}],
        "default_axis": "sector", "default_size_by": "flow"
    }))
    .unwrap();
    let series_backend: Arc<dyn Backend> =
        Arc::new(FrameBackend::new(Arc::new(FrameSource::new(series_df))));

    // series_follows_treemap = true → /api/series resolves the branch set from the
    // snapshot treemap.
    build_router_ext(
        snap_ds,
        snap_backend,
        Some((series_ds, series_backend)),
        true,
    )
}

#[tokio::test]
async fn frames_views_series_follows_treemap_branch_set() {
    // top_k=2 over the snapshot (mcap) → keep {tech, fin}, fold energy → Other.
    // The series plots `flow`; despite energy having the biggest flow, it must NOT
    // be a kept branch (it isn't in the treemap top-2). size_by=mcap is a metric
    // the SERIES frame lacks — proving the ranking ran on the snapshot.
    let resp = frames_views_app()
        .oneshot(post(
            "/api/series",
            json!({"axis": "sector", "metric": "flow", "size_by": "mcap", "top_k": 2}),
        ))
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    let keys: Vec<&str> = v["meta"]["branch_keys"]
        .as_array()
        .unwrap()
        .iter()
        .map(|x| x.as_str().unwrap())
        .collect();
    // EXACTLY the treemap's top-2 by mcap, plus the folded Other — NOT a flow rank.
    assert_eq!(keys, ["tech", "fin", "__other__"]);
    assert_eq!(v["meta"]["metric_id"], json!("flow"));
}

// A series ds that RESTRICTS resolutions to `["w"]` (a weekly-pre-bucketed
// producer). /api/series must validate the requested resolution against the
// FRAME's declared set, not the global ["d","w","m","q","y"] allowlist.
fn weekly_only_series_app() -> axum::Router {
    let main_df = df![
        "fullname" => ["microsoft/vscode", "google/go"],
        "owner" => ["microsoft", "google"],
        "stars" => [163000i64, 123000],
    ]
    .unwrap();
    let main_ds: FrameDataset = serde_json::from_value(json!({
        "source": "r", "id_column": "fullname", "label_column": "fullname",
        "axes": [{"id": "by_owner", "levels": ["owner", "fullname"]}],
        "metrics": [{"id": "stars", "agg": "sum", "column": "stars", "unit": "count"}],
        "default_axis": "by_owner", "default_size_by": "stars"
    }))
    .unwrap();
    let main_backend: Arc<dyn Backend> =
        Arc::new(FrameBackend::new(Arc::new(FrameSource::new(main_df))));

    let series_df = df![
        "fullname" => ["microsoft/vscode", "google/go"],
        "owner" => ["microsoft", "google"],
        "snap" => Series::new("snap".into(), [20454i32, 20454]).cast(&DataType::Date).unwrap(),
        "price" => [10.0f64, 8.0],
    ]
    .unwrap();
    let series_ds: FrameDataset = serde_json::from_value(json!({
        "source": "s", "id_column": "fullname", "label_column": "fullname",
        "timestamp_column": "snap",
        "axes": [{"id": "by_owner", "levels": ["owner", "fullname"]}],
        "metrics": [{"id": "price", "agg": "sum", "column": "price", "unit": "money"}],
        "series_resolutions": ["w"],
        "default_axis": "by_owner", "default_size_by": "price"
    }))
    .unwrap();
    let series_backend: Arc<dyn Backend> =
        Arc::new(FrameBackend::new(Arc::new(FrameSource::new(series_df))));

    build_router(main_ds, main_backend, Some((series_ds, series_backend)))
}

#[tokio::test]
async fn series_resolution_validates_against_frame_not_global() {
    // Fix 2: a `d` resolution is in the GLOBAL allowlist but NOT in this frame's
    // declared `["w"]` — /api/series must 400 (previously it accepted any global
    // resolution, re-bucketing a weekly-pre-bucketed metric to daily).
    assert_eq!(
        weekly_only_series_app()
            .oneshot(post(
                "/api/series",
                json!({"axis": "by_owner", "metric": "price", "resolution": "d"})
            ))
            .await
            .unwrap()
            .status(),
        StatusCode::BAD_REQUEST,
        "a frame-disallowed resolution must 400"
    );
    // The frame's declared resolution is accepted.
    assert_eq!(
        weekly_only_series_app()
            .oneshot(post(
                "/api/series",
                json!({"axis": "by_owner", "metric": "price", "resolution": "w"})
            ))
            .await
            .unwrap()
            .status(),
        StatusCode::OK
    );
    // Fix 3: with NO resolution, the request defaults to the frame's FIRST allowed
    // resolution ("w") — not the global "d" — so it succeeds and reports weekly.
    let resp = weekly_only_series_app()
        .oneshot(post(
            "/api/series",
            json!({"axis": "by_owner", "metric": "price"}),
        ))
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
    assert_eq!(
        v["meta"]["cadence"],
        json!("weekly"),
        "absent resolution must default to the frame's first allowed ('w')"
    );
}

#[tokio::test]
async fn embedded_assets_etag_revalidation() {
    // Every embedded asset (index.html included) carries a strong ETag and
    // `no-cache` — the browser revalidates each load, so a regenerated vendor
    // file (e.g. the geo registry) is picked up on the next refresh instead of
    // after a fixed max-age.
    let resp = app()
        .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(
        resp.headers().get("cache-control").unwrap(),
        "no-cache",
        "embedded assets must revalidate, never cache blindly"
    );
    let etag = resp.headers().get("etag").expect("ETag present").clone();
    let etag = etag.to_str().unwrap();
    assert!(
        etag.starts_with('"') && etag.ends_with('"'),
        "strong quoted ETag: {etag}"
    );

    // A matching If-None-Match gets a body-less 304 (the cheap path for the
    // multi-MB vendor TopoJSONs).
    let resp = app()
        .oneshot(
            Request::builder()
                .uri("/")
                .header("if-none-match", etag)
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_MODIFIED);
    assert!(
        resp.headers().get("etag").is_some(),
        "304 re-states the ETag"
    );
    let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
        .await
        .unwrap();
    assert!(bytes.is_empty(), "304 must not carry a body");

    // A stale ETag (regenerated file) gets the full 200 again.
    let resp = app()
        .oneshot(
            Request::builder()
                .uri("/")
                .header("if-none-match", "\"deadbeef\"")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    // Same contract on the /static/ asset route — a generic atlas that taxa
    // legitimately ships embedded (the sub-county census DATA was evicted to
    // consumers' --geo-dir; only the us/world atlases powering built-in maps
    // remain in the bundle).
    let resp = app()
        .oneshot(
            Request::builder()
                .uri("/static/vendor/world-countries-med.json")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    assert_eq!(resp.headers().get("cache-control").unwrap(), "no-cache");
    let etag = resp
        .headers()
        .get("etag")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();
    let resp = app()
        .oneshot(
            Request::builder()
                .uri("/static/vendor/world-countries-med.json")
                .header("if-none-match", format!("W/{etag}")) // weak compare ok for 304
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_MODIFIED);
}

#[tokio::test]
async fn entity_series_unknown_metric_is_400() {
    let resp = series_app()
        .oneshot(
            Request::builder()
                .uri("/api/entity/microsoft/vscode/series?metric=bogus&window=1y")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}