-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_server.py
More file actions
4372 lines (3845 loc) · 155 KB
/
Copy pathtest_server.py
File metadata and controls
4372 lines (3845 loc) · 155 KB
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import base64
import io
import json
import math
import re
import socket
import struct
import time
import wave
from datetime import datetime, timedelta, timezone
from pathlib import Path
from threading import Event
import pytest
from fastapi.testclient import TestClient
from server.audio_io import write_sine_wav
from server.cosmoaudition import (
CosmoauditionBridge,
CosmoauditionBridgeError,
_decode_json_object,
validate_loopback_base_url,
)
from server.job_runner import JobQueueFullError
from server.main import app
from server.providers.stability_api_provider import StabilityAPIProvider
from server.providers.stable_audio_mlx_provider import StableAudioMLXProvider
from server.providers.stable_audio_python_provider import StableAudioPythonProvider
from server.registry import (
control_registry,
job_runner,
registry,
settings,
storage,
strain_registry,
)
from server.routes import audio_tools
from server.routes import cosmoaudition as cosmoaudition_routes
from server.routes import image_to_audio as image_routes
from server.routes import micro as micro_routes
from server.routes import wavetables as wavetable_routes
from server.routes.time_render import time_clock_summary
from server.schemas import GenerationResult, GenerateRequest, InpaintRequest, TimeClock, TimeRenderRequest
from server.storage import (
JOB_EVICTION_GRACE_SECONDS,
MAX_LINEAGE_CHILD_LOCKS,
MAX_TRACKED_JOBS,
MAX_TRACKED_JOBS_HARD,
)
from server.wavetable import note_to_frequency
client = TestClient(app)
@pytest.fixture(autouse=True)
def restore_control_state_for_control_tests(request: pytest.FixtureRequest):
if not request.node.name.startswith("test_control_"):
yield
return
control_dir = settings.output_root / "control"
control_dir.mkdir(parents=True, exist_ok=True)
state_paths = [
control_registry.events_path,
control_registry.routes_path,
control_registry.cv_profiles_path,
]
original_state = {
path: path.read_text(encoding="utf-8") if path.exists() else None
for path in state_paths
}
original_events = control_registry.events()
existing_files = set(control_dir.iterdir())
yield
for path in control_dir.iterdir():
if path in existing_files or not path.name.startswith("pytest_"):
continue
path.unlink()
for path, content in original_state.items():
if content is None:
if path.exists():
path.unlink()
else:
path.write_text(content, encoding="utf-8")
with control_registry._lock:
control_registry._events.clear()
control_registry._events.extend(original_events)
@pytest.fixture(autouse=True)
def restore_strain_and_micro_state(request: pytest.FixtureRequest):
if not (
request.node.name.startswith("test_strain_")
or request.node.name.startswith("test_micro_")
or request.node.name.startswith("test_matter_")
):
yield
return
strain_registry.strain_dir.mkdir(parents=True, exist_ok=True)
micro_dir = settings.output_root / "micro"
micro_dir.mkdir(parents=True, exist_ok=True)
masa_dir = settings.masa_dir
masa_dir.mkdir(parents=True, exist_ok=True)
audio_dir = settings.audio_dir
audio_dir.mkdir(parents=True, exist_ok=True)
strain_content = (
strain_registry.registry_path.read_text(encoding="utf-8")
if strain_registry.registry_path.exists()
else None
)
existing_micro_files = set(micro_dir.iterdir())
existing_masa_files = set(masa_dir.iterdir())
existing_audio_files = set(audio_dir.iterdir())
yield
for path in micro_dir.iterdir():
if path in existing_micro_files or not path.name.startswith("pytest_"):
continue
path.unlink()
for directory, existing_files in (
(masa_dir, existing_masa_files),
(audio_dir, existing_audio_files),
):
for path in directory.iterdir():
if path in existing_files or not path.name.startswith("pytest_"):
continue
path.unlink()
if strain_content is None:
if strain_registry.registry_path.exists():
strain_registry.registry_path.unlink()
else:
strain_registry.registry_path.write_text(strain_content, encoding="utf-8")
def poll_job(status_url: str, timeout: float = 5.0) -> dict:
deadline = time.monotonic() + timeout
last: dict = {}
while time.monotonic() < deadline:
response = client.get(status_url)
assert response.status_code == 200
last = response.json()
if last["status"] in {"done", "error", "cancelled"}:
return last
time.sleep(0.02)
raise AssertionError(f"job did not finish before timeout: {last}")
def write_wavetable_stack(path: Path, *, frame_size: int = 512, frame_count: int = 4) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with wave.open(str(path), "wb") as wav:
wav.setnchannels(1)
wav.setsampwidth(2)
wav.setframerate(44100)
frames = bytearray()
for frame_index in range(frame_count):
harmonic = frame_index + 1
for sample_index in range(frame_size):
phase = (sample_index / frame_size) * harmonic * 2.0 * math.pi
frames.extend(struct.pack("<h", int(18000 * math.sin(phase))))
wav.writeframes(bytes(frames))
def test_health_returns_ok() -> None:
response = client.get("/health")
assert response.status_code == 200
assert "x-process-time-ms" in response.headers
body = response.json()
assert body["status"] == "ok"
assert body["server"] == "germ"
def test_models_returns_providers() -> None:
response = client.get("/models")
assert response.status_code == 200
providers = {item["id"]: item for item in response.json()["providers"]}
assert "mock" in providers
assert "stable_audio_python" in providers
assert "stable_audio_mlx" in providers
assert "stability_api" in providers
assert providers["mock"]["available"] is True
def test_failed_provider_load_does_not_change_active_provider(
monkeypatch: pytest.MonkeyPatch,
) -> None:
previous = registry.active_provider_id
registry.set_active("mock")
monkeypatch.setattr(settings, "stability_api_key", "")
try:
response = client.post(
"/models/load",
json={
"provider": "stability_api",
"model": "stable-audio-3",
"device": "api",
},
)
assert response.status_code == 200
assert response.json()["status"] == "error"
assert registry.active_provider_id == "mock"
finally:
registry.set_active(previous)
def test_diagnostics_reports_local_readiness() -> None:
response = client.get("/diagnostics")
assert response.status_code == 200
body = response.json()
assert "dependencies" in body
assert "audio_processing" in body
assert "providers" in body
assert "install_commands" in body
assert "rubberband_available" in body["audio_processing"]
assert body["recommended_local_provider"] in {"stable_audio_mlx", "stable_audio_python"}
def test_performance_endpoint_reports_recent_requests() -> None:
client.get("/health")
response = client.get("/performance")
assert response.status_code == 200
body = response.json()
assert body["count"] >= 1
assert "summary" in body
def test_control_ports_and_routes_round_trip() -> None:
ports_response = client.get("/control/ports")
assert ports_response.status_code == 200
ports = {item["id"]: item for item in ports_response.json()["ports"]}
assert ports["mod:audio_to_control"]["kind"] == "control"
assert ports["generation:seed_drift"]["direction"] == "input"
assert ports["cv:export"]["metadata"]["hardware_output"] is False
route_response = client.post(
"/control/routes",
json={
"source_port_id": "mod:audio_to_control",
"target_port_id": "generation:seed_drift",
"source_kind": "control",
"target_kind": "control",
"label": "pytest audio control to seed drift",
"transform": {"amount": 0.5, "smoothing_ms": 20},
},
)
assert route_response.status_code == 200
route = route_response.json()
assert route["id"].startswith("route_")
assert route["enabled"] is True
assert route["lineage_role"] == "control-parent"
disable_response = client.post(f"/control/routes/{route['id']}/enable", json={"enabled": False})
assert disable_response.status_code == 200
assert disable_response.json()["enabled"] is False
delete_response = client.delete(f"/control/routes/{route['id']}")
assert delete_response.status_code == 200
rejected_response = client.post(
"/control/routes",
json={
"source_port_id": "midi:input",
"target_port_id": "app:arbitrary",
"source_kind": "midi",
"target_kind": "control",
},
)
assert rejected_response.status_code == 422
def test_control_events_reject_nonfinite_values_before_persistence() -> None:
original_count = len(control_registry.events())
response = client.post(
"/control/events",
content='{"kind":"event","source":"pytest","value":NaN}',
headers={"content-type": "application/json"},
)
assert response.status_code == 422
assert len(control_registry.events()) == original_count
def test_control_graph_does_not_follow_metadata_symlinks(tmp_path: Path) -> None:
external = tmp_path / "external-control-metadata.json"
external.write_text(
json.dumps({"sound_id": "pytest_external_symlink_sound", "prompt": "must stay private"}),
encoding="utf-8",
)
link = settings.metadata_dir / "pytest_external_control_symlink.json"
link.symlink_to(external)
try:
response = client.get("/control/genetic/control-graph?limit=1000")
finally:
link.unlink(missing_ok=True)
assert response.status_code == 200
assert all(
node["id"] != "pytest_external_symlink_sound"
for node in response.json()["nodes"]
)
def test_control_audio_analysis_and_cv_safe_render() -> None:
audio_path = settings.audio_dir / "pytest_control_source.wav"
write_sine_wav(audio_path, duration=0.2, amplitude=0.2)
analysis_response = client.post(
"/control/analyze-audio",
json={
"input_audio_path": storage.relative_path(audio_path),
"features": [
"envelope",
"rms",
"transient",
"spectral_centroid",
"pitch",
"chroma",
"onset_density",
"tempo",
"timbre",
],
"window_ms": 20,
"hop_ms": 10,
"output_name": "pytest_control_analysis",
},
)
assert analysis_response.status_code == 200
analysis = analysis_response.json()
assert analysis["status"] == "done"
assert len(analysis["control_files"]) == 1
control_path = Path(analysis["control_files"][0])
assert control_path.exists()
control_data = json.loads(control_path.read_text(encoding="utf-8"))
assert control_data["type"] == "control_analysis"
assert "envelope" in control_data["features"]
assert "pitch" in control_data["features"]
assert "timbre" in control_data["features"]
assert control_data["lineage"]["operation"] == "control_analysis"
cv_response = client.post(
"/control/render-cv",
json={
"input_control_path": analysis["control_files"][0],
"feature": "envelope",
"duration": 0.2,
"output_name": "pytest_cv_export",
"mode": "cv",
"range": "unipolar",
"scale": 0.5,
"slew_ms": 1,
},
)
assert cv_response.status_code == 200
cv = cv_response.json()
assert cv["status"] == "done"
assert cv["cv_safe"] is True
assert cv["hardware_output"] is False
assert Path(cv["audio_file"]).exists()
assert Path(cv["metadata_file"]).exists()
def test_control_bridges_profiles_events_and_graph() -> None:
event_response = client.post(
"/control/events",
json={"kind": "metadata", "source": "pytest", "value": {"action": "persist"}},
)
assert event_response.status_code == 200
assert (settings.output_root / "control" / "events.json").exists()
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp:
udp.bind(("127.0.0.1", 0))
udp.settimeout(1.0)
port = udp.getsockname()[1]
osc_response = client.post(
"/control/osc/send",
json={
"host": "127.0.0.1",
"port": port,
"address": "/germinator/pytest",
"values": [0.75],
},
)
assert osc_response.status_code == 200
assert osc_response.json()["sent"] is True
packet, _ = udp.recvfrom(1024)
assert b"/germinator/pytest" in packet
norns_profile = client.get("/control/osc/norns/profile")
assert norns_profile.status_code == 200
mappings = norns_profile.json()["mappings"]
assert any(mapping["target"] == "dish.gravity" for mapping in mappings)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp:
udp.bind(("127.0.0.1", 0))
udp.settimeout(1.0)
port = udp.getsockname()[1]
norns_response = client.post(
"/control/osc/norns/send",
json={"host": "127.0.0.1", "port": port, "gravity": 0.25, "energy": 0.8, "spawn": True},
)
assert norns_response.status_code == 200
norns = norns_response.json()
assert norns["status"] == "sent"
assert norns["sent"] is True
packets = [udp.recvfrom(1024)[0] for _ in range(3)]
assert any(b"/germ/dish/gravity" in packet for packet in packets)
assert any(b"/germ/dish/energy" in packet for packet in packets)
assert any(b"/germ/dish/spawn" in packet for packet in packets)
osc_receive = client.post(
"/control/osc/receive",
json={"address": "/germinator/in", "values": [1]},
)
assert osc_receive.status_code == 200
assert osc_receive.json()["status"] == "recorded"
midi_response = client.post(
"/control/midi/send",
json={"backend": "event", "type": "cc", "channel": 1, "cc": 11, "value": 64},
)
assert midi_response.status_code == 200
assert midi_response.json()["status"] == "recorded"
profile_response = client.post(
"/control/cv/profiles",
json={
"name": "pytest cv output",
"output_channel": 1,
"calibrated": False,
"speaker_protection": True,
},
)
assert profile_response.status_code == 200
profile_id = profile_response.json()["id"]
arm_rejected = client.post(
f"/control/cv/profiles/{profile_id}/arm",
json={"armed": True, "confirm": True},
)
assert arm_rejected.status_code == 422
calibrated_response = client.post(
"/control/cv/profiles",
json={
"name": "pytest calibrated cv output",
"output_channel": 2,
"calibrated": True,
"speaker_protection": True,
},
)
assert calibrated_response.status_code == 200
calibrated_id = calibrated_response.json()["id"]
arm_response = client.post(
f"/control/cv/profiles/{calibrated_id}/arm",
json={"armed": True, "confirm": True},
)
assert arm_response.status_code == 200
assert arm_response.json()["armed"] is True
panic_response = client.post("/control/panic")
assert panic_response.status_code == 200
profiles = client.get("/control/cv/profiles").json()["profiles"]
assert all(profile["armed"] is False for profile in profiles)
status_response = client.get("/control/bridge/status")
assert status_response.status_code == 200
assert status_response.json()["cv_hardware_output"] is False
graph_response = client.get("/control/genetic/control-graph")
assert graph_response.status_code == 200
assert "nodes" in graph_response.json()
assert "edges" in graph_response.json()
def test_control_osc_send_rejects_invalid_host() -> None:
response = client.post(
"/control/osc/send",
json={
"host": "256.256.256.256",
"port": 9000,
"address": "/germinator/pytest",
"values": [0.5],
},
)
assert response.status_code == 422
def test_strain_registry_roundtrip_and_generation_metadata() -> None:
save_response = client.post(
"/strains",
json={
"name": "pytest dust strain",
"path": "output/strains/pytest_dust.safetensors",
"description": "Small noisy granular identity for tests.",
"source_dataset": "pytest fixture",
"license": "internal-test",
"author": "pytest",
"prompt_vocabulary": ["dust", "grain", "cell"],
"recommended_modules": ["grain_culture", "microscope"],
"tags": ["pytest", "micro"],
"strength_min": 0.1,
"strength_max": 1.2,
"default_strength": 0.65,
"provenance_notes": "created by test metadata only",
},
)
assert save_response.status_code == 200
strain = save_response.json()
assert strain["id"].startswith("strain_")
list_response = client.get("/strains")
assert list_response.status_code == 200
assert any(item["id"] == strain["id"] for item in list_response.json()["strains"])
load_response = client.post(
"/strains/load",
json={"provider": "mock", "strain_ids": [strain["id"]]},
)
assert load_response.status_code == 200
assert load_response.json()["status"] == "loaded"
assert "output/strains/pytest_dust.safetensors" in load_response.json()["loaded_loras"]
generate_response = client.post(
"/generate",
json={
"provider": "mock",
"model": "mock-sine",
"prompt": "short dusty grain cell",
"duration": 0.25,
"output_name": "pytest_strain_generate",
"lora": [
{
"id": strain["id"],
"name": strain["name"],
"path": strain["path"],
"strength": strain["default_strength"],
"tags": strain["tags"],
"license": strain["license"],
"author": strain["author"],
"prompt_vocabulary": strain["prompt_vocabulary"],
"recommended_modules": strain["recommended_modules"],
"provenance_notes": strain["provenance_notes"],
}
],
},
)
assert generate_response.status_code == 200
metadata = json.loads(Path(generate_response.json()["metadata_files"][0]).read_text(encoding="utf-8"))
assert metadata["lora_strains"][0]["id"] == strain["id"]
assert metadata["lora_strains"][0]["name"] == "pytest dust strain"
assert metadata["lora_strains"][0]["prompt_vocabulary"] == ["dust", "grain", "cell"]
assert metadata["strain_stack"] == metadata["lora_strains"]
def test_strain_get_delete_and_direct_lora_routes() -> None:
save_response = client.post(
"/strains",
json={
"name": "pytest disposable strain",
"path": "output/strains/pytest_disposable.safetensors",
"tags": ["pytest"],
},
)
assert save_response.status_code == 200
strain = save_response.json()
get_response = client.get(f"/strains/{strain['id']}")
assert get_response.status_code == 200
assert get_response.json()["id"] == strain["id"]
lora_load = client.post(
"/lora/load",
json={"provider": "mock", "paths": ["output/strains/pytest_direct.safetensors"]},
)
assert lora_load.status_code == 200
assert lora_load.json()["status"] == "loaded"
assert "output/strains/pytest_direct.safetensors" in lora_load.json()["loaded_loras"]
lora_strength = client.post(
"/lora/strength",
json={"provider": "mock", "strength": 0.42, "lora_index": 0},
)
assert lora_strength.status_code == 200
assert lora_strength.json()["status"] == "set"
assert lora_strength.json()["strength"] == 0.42
delete_response = client.delete(f"/strains/{strain['id']}")
assert delete_response.status_code == 200
assert delete_response.json()["status"] == "deleted"
missing_response = client.get(f"/strains/{strain['id']}")
assert missing_response.status_code == 404
def test_micro_matter_profile_and_graph_links() -> None:
strain_response = client.post(
"/strains",
json={
"name": "pytest graph strain",
"path": "output/strains/pytest_graph.safetensors",
"recommended_modules": ["spectral_tissue"],
"default_strength": 0.7,
},
)
assert strain_response.status_code == 200
strain = strain_response.json()
semantic_effect = {
"id": "node_micro_pytest:semantic",
"module_id": "node_micro_pytest",
"fx_type": "grain_culture",
"amount": 0.8,
"prompt_layer": "granular cloud, dense cells",
}
generate_response = client.post(
"/generate",
json={
"provider": "mock",
"model": "mock-sine",
"prompt": "short graph granular test",
"duration": 0.25,
"output_name": "pytest_micro_graph",
"semantic_effects": [semantic_effect],
"lora": [
{
"id": strain["id"],
"name": strain["name"],
"path": strain["path"],
"strength": 0.7,
"recommended_modules": strain["recommended_modules"],
}
],
},
)
assert generate_response.status_code == 200
generated = generate_response.json()
metadata_path = Path(generated["metadata_files"][0])
metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
profile_response = client.post(
"/micro/matter-profile",
json={
"input_audio_path": generated["audio_files"][0],
"metadata_path": generated["metadata_files"][0],
"source_id": metadata["sound_id"],
"module": "microscope",
"window_ms": 20,
"hop_ms": 10,
"output_name": "pytest_micro_profile",
"lineage": {"parents": [metadata["sound_id"]]},
},
)
assert profile_response.status_code == 200
profile = profile_response.json()
assert profile["status"] == "done"
assert profile["descriptors"]["cell_count"] >= 1
profile_file = Path(profile["profile_file"])
assert profile_file.exists()
profile_data = json.loads(profile_file.read_text(encoding="utf-8"))
assert profile_data["type"] == "micro_matter_profile"
assert profile_data["lineage"]["operation"] == "micro_matter_profile"
graph_response = client.get("/control/genetic/control-graph?limit=50")
assert graph_response.status_code == 200
graph = graph_response.json()
node_types = {node["type"] for node in graph["nodes"]}
edge_types = {edge["type"] for edge in graph["edges"]}
assert "strain" in node_types
assert "micro_module" in node_types
assert "micro_profile" in node_types
assert "strain-applied" in edge_types
assert "micro-shape" in edge_types
assert "micro-profiled" in edge_types
def test_micro_matter_profile_reuses_cached_analysis(monkeypatch: pytest.MonkeyPatch) -> None:
source_path = settings.audio_dir / "pytest_micro_cache_source.wav"
write_sine_wav(source_path, duration=0.25)
with micro_routes._MATTER_PROFILE_ANALYSIS_CACHE_LOCK:
micro_routes._MATTER_PROFILE_ANALYSIS_CACHE.clear()
calls = 0
original_analyze = micro_routes._analyze_features
def counting_analyze(**kwargs):
nonlocal calls
calls += 1
return original_analyze(**kwargs)
monkeypatch.setattr(micro_routes, "_analyze_features", counting_analyze)
payload = {
"input_audio_path": storage.relative_path(source_path),
"module": "microscope",
"window_ms": 20,
"hop_ms": 10,
"output_name": "pytest_micro_cache_profile",
}
first = client.post("/micro/matter-profile", json=payload)
second = client.post("/micro/matter-profile", json=payload)
assert first.status_code == 200
assert second.status_code == 200
assert first.json()["descriptors"] == second.json()["descriptors"]
assert calls == 1
def test_micro_analysis_cache_evicts_single_oversized_entry_without_double_pop(
monkeypatch: pytest.MonkeyPatch,
) -> None:
source_path = settings.audio_dir / "pytest_micro_cache_pressure.wav"
write_sine_wav(source_path, duration=0.25)
with micro_routes._MATTER_PROFILE_ANALYSIS_CACHE_LOCK:
micro_routes._MATTER_PROFILE_ANALYSIS_CACHE.clear()
monkeypatch.setattr(micro_routes, "MATTER_PROFILE_CACHE_LIMIT", 1)
monkeypatch.setattr(micro_routes, "MATTER_PROFILE_CACHE_MAX_POINTS", 1)
response = client.post(
"/micro/matter-profile",
json={
"input_audio_path": storage.relative_path(source_path),
"module": "microscope",
"window_ms": 20,
"hop_ms": 10,
"output_name": "pytest_micro_cache_pressure_profile",
},
)
assert response.status_code == 200
with micro_routes._MATTER_PROFILE_ANALYSIS_CACHE_LOCK:
assert not micro_routes._MATTER_PROFILE_ANALYSIS_CACHE
def test_micro_biomes_save_list_load_delete() -> None:
payload = {
"name": "pytest mist biome",
"state": {
"version": 2,
"germs": [{"id": "germ_a", "assetId": "asset_a"}],
"modules": [{"id": "module_a", "type": "crystal"}],
},
}
saved = client.post("/micro/biomes", json=payload)
assert saved.status_code == 200
body = saved.json()
biome_id = body["biome"]["id"]
assert body["biome"]["germ_count"] == 1
assert body["biome"]["module_count"] == 1
listed = client.get("/micro/biomes")
assert listed.status_code == 200
assert any(item["id"] == biome_id for item in listed.json())
loaded = client.get(f"/micro/biomes/{biome_id}")
assert loaded.status_code == 200
assert loaded.json()["state"]["germs"][0]["id"] == "germ_a"
deleted = client.delete(f"/micro/biomes/{biome_id}")
assert deleted.status_code == 200
assert deleted.json()["status"] == "deleted"
def test_micro_biomes_do_not_follow_symlinks(tmp_path: Path) -> None:
external = tmp_path / "external-biome.json"
external.write_text(
json.dumps({"id": "pytest_external_biome", "name": "outside", "state": {}}),
encoding="utf-8",
)
link = settings.micro_biome_dir / "pytest_external_biome.json"
link.symlink_to(external)
try:
listed = client.get("/micro/biomes")
loaded = client.get("/micro/biomes/pytest_external_biome")
finally:
link.unlink(missing_ok=True)
assert listed.status_code == 200
assert all(item["id"] != "pytest_external_biome" for item in listed.json())
assert loaded.status_code == 404
def test_micro_biome_rejects_oversized_state(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(micro_routes, "MAX_BIOME_STATE_BYTES", 64)
response = client.post(
"/micro/biomes",
json={"name": "pytest huge biome", "state": {"payload": "x" * 128}},
)
assert response.status_code == 413
def test_cosmoaudition_bridge_mapping_and_archive(monkeypatch: pytest.MonkeyPatch) -> None:
class FakeBridge:
def status(self) -> dict:
return {
"available": True,
"contract": "cosmoaudition-germ/v0.1",
"remote": {"ok": True},
}
def get_json(self, path: str, *, params: dict | None = None) -> dict:
assert path == "/api/snapshot"
assert params == {"mode": "fixture"}
return {
"generatedAt": "2026-07-30T12:00:00Z",
"mode": "fixture",
"signals": [
{
"id": "solar_wind_speed",
"label": "Solar wind speed",
"layer": "earth",
"unit": "km/s",
"value": 450,
"normalized": 0.5,
"timestamp": "2026-07-30T12:00:00Z",
"sourceId": "swpc_solar_wind",
"sphere": "cosmos",
"epistemicStatus": "reported",
"temporalCharacter": "stream",
"signalKind": "observation",
"confidence": "high",
}
],
"sources": [],
"cache": [],
}
monkeypatch.setattr(cosmoaudition_routes, "_bridge", lambda: FakeBridge())
status = client.get("/cosmoaudition/status")
assert status.status_code == 200
assert status.json()["available"] is True
snapshot = client.get("/cosmoaudition/snapshot?mode=fixture")
assert snapshot.status_code == 200
assert snapshot.json()["payload"]["signals"][0]["sphere"] == "cosmos"
modules = client.get("/cosmoaudition/modules")
assert modules.status_code == 200
module_ids = {item["id"] for item in modules.json()["modules"]}
assert {"cosmo_observation", "cosmo_matter_modulator", "matter_analysis"} <= module_ids
mapping = {
"mapping": {
"id": "pytest_solar_to_density",
"signalId": "solar_wind_speed",
"layer": "earth",
"target": "generation:inpaint_density",
"scale": "linear",
"inputRange": [300, 600],
"outputRange": [0, 1],
"smoothingMs": 80,
"missingData": "hold-explicitly",
"epistemicNote": "Authored test relation; not a source identity claim.",
},
"signal": snapshot.json()["payload"]["signals"][0],
"amount": 1,
}
mapped = client.post("/cosmoaudition/map", json=mapping)
assert mapped.status_code == 200
assert mapped.json()["status"] == "applied"
assert mapped.json()["outputValue"] == pytest.approx(0.5)
assert mapped.json()["epistemicStatus"] == "reported"
assert mapped.json()["temporalCharacter"] == "stream"
log_mapping = {
**mapping,
"mapping": {
**mapping["mapping"],
"scale": "log",
"inputRange": [10, 100],
},
}
log_below = client.post(
"/cosmoaudition/map",
json={**log_mapping, "signal": {**mapping["signal"], "value": 1}},
)
log_above = client.post(
"/cosmoaudition/map",
json={**log_mapping, "signal": {**mapping["signal"], "value": 1_000}},
)
assert log_below.status_code == 200
assert log_below.json()["status"] == "applied"
assert log_below.json()["outputValue"] == 0
assert log_above.status_code == 200
assert log_above.json()["outputValue"] == 1
held = client.post(
"/cosmoaudition/map",
json={**mapping, "signal": None, "previousOutput": 0.37},
)
assert held.status_code == 200
assert held.json()["status"] == "held"
assert held.json()["outputValue"] == pytest.approx(0.37)
archived = client.post(
"/cosmoaudition/archives",
json={
"label": "pytest observatory fixture",
"module": "cosmo_cosmic_field",
"snapshot": snapshot.json()["payload"],
},
)
assert archived.status_code == 200
archive_id = archived.json()["id"]
loaded = client.get(f"/cosmoaudition/archives/{archive_id}")
assert loaded.status_code == 200
assert loaded.json()["snapshot"]["mode"] == "fixture"
deleted = client.delete(f"/cosmoaudition/archives/{archive_id}")
assert deleted.status_code == 200
def test_cosmoaudition_bridge_errors_do_not_expose_backend_details(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class FailingBridge:
def status(self) -> dict:
raise ValueError("private backend path: /Users/listener/secret")
monkeypatch.setattr(cosmoaudition_routes, "_bridge", lambda: FailingBridge())
response = client.get("/cosmoaudition/status")
assert response.status_code == 200
assert response.json()["error"] == "Cosmoaudition bridge unavailable"
assert "secret" not in response.text
@pytest.mark.parametrize(
("value", "expected"),
[
("http://127.0.0.1:8797", "http://127.0.0.1:8797"),
("http://localhost:8797/", "http://localhost:8797"),
("http://[::1]:8797", "http://[::1]:8797"),
],
)
def test_cosmoaudition_bridge_accepts_only_explicit_http_loopback(
value: str,
expected: str,
) -> None:
assert validate_loopback_base_url(value) == expected
@pytest.mark.parametrize(
"value",
[
"https://127.0.0.1:8797",
"http://example.com:8797",
"http://127.0.0.1:8797/api/snapshot",
"http://user:password@127.0.0.1:8797",
],
)
def test_cosmoaudition_bridge_rejects_non_loopback_or_ambiguous_urls(value: str) -> None:
with pytest.raises(ValueError):
validate_loopback_base_url(value)
@pytest.mark.parametrize(
"payload",
[
b'{"value": NaN}',
b'{"value": Infinity}',
b'{"value": -Infinity}',
b'["not", "an", "object"]',
],
)
def test_cosmoaudition_bridge_rejects_invalid_json_boundaries(payload: bytes) -> None:
with pytest.raises(CosmoauditionBridgeError):
_decode_json_object(payload)
def test_cosmoaudition_bridge_rejects_excessively_nested_json() -> None:
payload = (b'{"value":' * 40) + b"null" + (b"}" * 40)
with pytest.raises(CosmoauditionBridgeError, match="invalid JSON"):
_decode_json_object(payload)
def test_cosmoaudition_status_requires_boolean_remote_health(
monkeypatch: pytest.MonkeyPatch,
) -> None:
bridge = CosmoauditionBridge(
base_url="http://127.0.0.1:8797",
timeout_seconds=0.1,
max_response_bytes=1_024,
)
monkeypatch.setattr(bridge, "get_json", lambda path: {"ok": "false"})
assert bridge.status()["available"] is False
def test_cosmoaudition_status_logs_but_does_not_return_backend_details(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
bridge = CosmoauditionBridge(
base_url="http://127.0.0.1:8797",
timeout_seconds=0.1,
max_response_bytes=1_024,
)
def fail(_path: str) -> dict:
raise CosmoauditionBridgeError("private backend path: /Users/listener/secret")