-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
6943 lines (6205 loc) · 292 KB
/
Copy pathmain.py
File metadata and controls
6943 lines (6205 loc) · 292 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
"""MinimapPR application entrypoint."""
from __future__ import annotations
import asyncio
import contextvars
import contextlib
import json
import logging
import math
import os
import sys
import threading
import time
import uuid
from contextlib import asynccontextmanager
from dataclasses import fields as dataclass_fields, replace
from pathlib import Path
from typing import Any, Awaitable, Callable, Literal
import urllib.error
import urllib.parse
import urllib.request
import numpy as np
from fastapi import FastAPI, File, Form, HTTPException, Query, Request, Response, UploadFile, WebSocket, WebSocketDisconnect
from pydantic import BaseModel, model_validator
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.requests import ClientDisconnect
from minimappr.api.binary_ingest import parse_binary_ingest_payload
from minimappr.api.live import LiveEventHub
from minimappr.api.spool_consumer import IngestSpoolConsumer
from minimappr.api.stream_consumer import IngestStreamConsumer, StreamConsumerConfig
from minimappr.classifiers.availability import probe_backends
from minimappr.classifiers.factory import create_context_classifier
from minimappr.classifiers.routing import (
CONTEXT_LOCALIZED_RENDER,
load_routing,
load_routing_file,
parse_routing_document,
routing_to_dict,
)
from minimappr.core.config_groups import group_flat_config
from minimappr.core.pipeline_graph import build_pipeline_graph
from minimappr.config import (
FusionConfig,
IngestSidecarProcessConfig,
IngestSidecarStartupConfig,
LocalizationConfig,
Settings,
)
from minimappr.settings_store import CONFIG_PATCH_ALLOWLIST, load_overrides, save_overrides
from minimappr.ingest_sidecar_runtime import (
IngestSidecarRuntimeState as _RuntimeSidecarState,
build_ingest_stream_consumer as _runtime_build_ingest_stream_consumer,
build_ingest_sidecar_environment as _runtime_build_ingest_sidecar_environment,
ensure_ingest_stream_consumer_running as _runtime_ensure_ingest_stream_consumer_running,
fetch_ingest_sidecar_health as _runtime_fetch_ingest_sidecar_health,
ingest_stream_consumer_runtime as _runtime_ingest_stream_consumer_runtime,
ingest_sidecar_is_running as _runtime_ingest_sidecar_is_running,
ingest_sidecar_process_config as _runtime_ingest_sidecar_process_config,
ingest_sidecar_startup_config as _runtime_ingest_sidecar_startup_config,
launch_managed_ingest_sidecar as _runtime_launch_managed_ingest_sidecar,
probe_ingest_sidecar_ready as _runtime_probe_ingest_sidecar_ready,
shutdown_managed_ingest_sidecar as _runtime_shutdown_managed_ingest_sidecar,
should_autostart_ingest_sidecar as _runtime_should_autostart_ingest_sidecar,
sidecar_classification_window_seconds as _runtime_sidecar_classification_window_seconds,
sidecar_classifier_render_min_interval_seconds as _runtime_sidecar_classifier_render_min_interval_seconds,
start_ingest_sidecar as _runtime_start_ingest_sidecar,
supervise_ingest_sidecar as _runtime_supervise_ingest_sidecar,
wait_for_ingest_sidecar_ready as _runtime_wait_for_ingest_sidecar_ready,
)
from minimappr.runtime_bootstrap import (
_ApiOnlyRuntimeTaskHandles,
_CombinedRuntimeTaskHandles,
_apply_settings_site_origin_resolution,
_build_api_only_runtime_federation,
_build_capture_manager,
_build_combined_runtime_core_services,
_build_combined_runtime_federation,
_build_common_live_runtime_services,
_build_effector_manager,
_build_hass_bridge,
_initialize_storage_and_resolve_site_origin,
_start_api_only_runtime_services,
_stop_api_only_runtime_services,
_stop_combined_ingest_stream_consumer,
_shutdown_combined_runtime_services,
_start_combined_runtime_background_tasks,
_stop_combined_runtime_background_tasks,
_wire_effector_zone_interlocks,
_wire_effector_rules_handler,
_wire_hass_live_event_tee,
_wire_hass_rules_handler,
)
from minimappr.core.capture_session import (
CaptureSessionManager,
CaptureSessionRecord,
CaptureStartRequest,
CaptureState,
)
from minimappr.core.ambisonics import (
AmbisonicSpatialEncoder,
SoundscapeRenderer,
SpatialSourceFrame,
foa_to_5_1,
wav_multichannel_bytes,
)
from minimappr.core.audio_buffer import MultiSensorBuffer
from minimappr.audio_processing.levels import apply_level_profile
from minimappr.audio_processing.profiles import LISTENING_PROFILE_NAME, load_audio_processing_configuration
from minimappr.audio_processing.wav_serving import listening_wav_bytes, level_report_headers
from minimappr.core.auth import extract_federation_token
from minimappr.core.ble_multilateration import estimate_ble_device_position
from minimappr.core.ble_observations import BleObservationStore
from minimappr.core.ble_tracking import BleTracker
from minimappr.core.bit_report import BITReportEvaluator
from minimappr.core.cluster_registry import ClusterRegistry
from minimappr.core.effectors.registry import EffectorManager
from minimappr.core.node_registry import NodeRegistry
from minimappr.core.environment import LiveEnvironmentProvider
from minimappr.core.federation import ACTIVE_TRACK_STATUSES, FederationCoordinator
from minimappr.core.hass.state_mapper import (
HassStateSnapshot,
NodeStateInput,
SystemStateInput,
ZoneStateInput,
)
from minimappr.core.hass.topics import is_valid_topic_level
from minimappr.core.hass.track_slots import TrackSlotCandidate
from minimappr.core.fusion_node import FusionNode
from minimappr.core.geo_restriction import excludes_audio_ingest
from minimappr.core.geo import LocalCoordinateFrame
from minimappr.core.logging_ring import install_global as install_log_ring, process_start_ns
from minimappr.core.rules import ConfigRuleEngine, RuleDef, default_rules_as_dicts
from minimappr.core.site_origin import (
SOURCE_GPS_ANCHOR,
SOURCE_PERSISTED,
SiteOriginResolution,
origins_differ,
persist_site_origin,
)
from minimappr.core.zones import ZoneMatcher
from minimappr.core import system_info
from minimappr.calibration.bundle import build_ground_truth_payload, write_bundle_zip
from minimappr.calibration.embeddings import extract_embedding_npy
from minimappr.models import (
AlertStatus,
BITReport,
CalibrationGroundTruthEvent,
CalibrationGroundTruthIn,
CalibrationGroundTruthUpdate,
BITReportIn,
BITStatus,
BITTestResult,
BITType,
BleIngestRequest,
ClassifierRoutingConfigResponse,
ClassifierRoutingConfigUpdate,
ClusterSpec,
ContextSnapshot,
CopStatusResponse,
DetectionReviewState,
DetectionReviewUpdateRequest,
EnvironmentSampleIn,
FederationAck,
FederationHeartbeat,
FederationStatusResponse,
HassBridgeStatusResponse,
FederationTrackSnapshot,
FusionStatusResponse,
MapOverlayKind,
MapOverlaySpec,
MapOverlayUpdate,
GeoPoint,
IngestFrameRequest,
IngestFrameResponse,
MicView,
NodeCapability,
NodeHealthStatus,
NodeAudioOverride,
NodeOverrides,
NodePatchRequest,
NodeRegistrationRequest,
NodeSafetyConfig,
NodeSpec,
PipelineGraph,
PipelineNodeView,
PipelineNodesResponse,
PipelineStageView,
RulesConfigResponse,
RulesConfigUpdate,
ReviewedDetectionExportItem,
ReviewedDetectionExportPackage,
StoreForwardBufferedFrameResponse,
StoreForwardIngestRequest,
StoreForwardIngestResponse,
TrackState,
TrainingExampleKind,
Vec3,
ZoneOccupancyState,
ZoneSpec,
)
from minimappr.training_dataset import (
TrainingDatasetError,
delete_training_example_files,
materialize_training_example,
)
from minimappr.storage.db import Storage
from minimappr.utils.audio import mono_mix, read_wav_mono
logger = logging.getLogger(__name__)
frontend_dir = Path(__file__).parent / "frontend"
_INGEST_STREAM_CONSUMER_WATCHDOG_INTERVAL_SECONDS = 1.0
_INGEST_PATH_PREFIXES = (
"/api/v1/ingest",
"/api/v1/capture",
"/api/v1/recordings",
"/api/v1/fusion/status",
"/api/v1/system/diagnostics",
"/api/v1/system/logs",
# Diagnostics that need the DSP runtime live in the ingest process; the API
# process proxies them here (see diagnostics_summary / debug_* handlers).
# Omitting them made these endpoints 404 on ingest AND 503 on api — dead in
# both roles of a split deployment.
"/api/v1/diagnostics",
"/api/v1/debug",
)
# Default ingest concurrency ceiling. Mirrors the Rust sidecar's bounded MPSC
# strategy ([ingest_backend.rs] raw_manifest_channel_capacity = 2048) but
# scaled down because each Python ingest task does much heavier work (numpy
# merge + classifier wakeup) than a Rust ingest task (just queue + write).
# Tuned in conjunction with the to_thread merge in audio_buffer.py.
_DEFAULT_INGEST_MAX_CONCURRENT = 64
class _IngestConcurrencyLimit:
"""Bounded-concurrency gate on the FastAPI ingest endpoints.
Mirrors the Rust sidecar's HTTP-503-with-`Retry-After` shape at
[main.rs] so a burst of slow concurrent requests cannot saturate the
worker pool. We *shed* immediately on overload (no buffering) — the
firmware client retries on `Retry-After`, which is the same wait-and-
retry contract the sidecar already enforces, just on the Python lane.
Single-threaded asyncio makes the counter-check and increment safe
without a lock (no yield points between them).
"""
def __init__(self, max_concurrent: int, lease_timeout_seconds: float = 5.0) -> None:
self._max = max(1, int(max_concurrent))
self._lease_timeout_seconds = max(0.1, float(lease_timeout_seconds))
self._active_leases: dict[int, float] = {}
self._next_lease_id = 0
self._lease_context: contextvars.ContextVar[int | None] = contextvars.ContextVar(
"minimappr_ingest_lease_id",
default=None,
)
# Atomic-from-asyncio's perspective: count never escapes the event loop.
# `total_admissions` / `total_shed` are exposed via /api/v1/system/diagnostics
# so operators can confirm backpressure is firing under load.
self.total_admissions = 0
self.total_shed = 0
@property
def max_concurrent(self) -> int:
return self._max
@property
def active(self) -> int:
self._evict_expired_leases(time.monotonic())
return len(self._active_leases)
async def __aenter__(self) -> "_IngestConcurrencyLimit":
now = time.monotonic()
self._evict_expired_leases(now)
if len(self._active_leases) >= self._max:
self.total_shed += 1
raise HTTPException(
status_code=503,
detail=(
f"ingest backpressure: {len(self._active_leases)}/{self._max} slots in use"
),
headers={"Retry-After": "1"},
)
self._next_lease_id += 1
lease_id = self._next_lease_id
self._active_leases[lease_id] = now + self._lease_timeout_seconds
self._lease_context.set(lease_id)
self.total_admissions += 1
return self
async def __aexit__(self, *exc: object) -> None:
lease_id = self._lease_context.get()
if lease_id is not None:
self._active_leases.pop(lease_id, None)
self._lease_context.set(None)
def _evict_expired_leases(self, now: float) -> None:
expired = [
lease_id
for lease_id, deadline in self._active_leases.items()
if deadline <= now
]
for lease_id in expired:
self._active_leases.pop(lease_id, None)
def _require_ingest_concurrency(request: Request) -> _IngestConcurrencyLimit:
"""Fetch the per-app ingest concurrency limiter. Falls through to a fresh
unbounded limiter only in tests where lifespan setup is skipped — in
production, the lifespan binds the configured limit on app.state."""
limit = getattr(request.app.state, "ingest_concurrency", None)
if isinstance(limit, _IngestConcurrencyLimit):
return limit
# Defensive fallback for tests that bypass lifespan: a limiter with the
# default ceiling, attached to app.state so subsequent requests share it.
limit = _IngestConcurrencyLimit(_DEFAULT_INGEST_MAX_CONCURRENT)
request.app.state.ingest_concurrency = limit
return limit
def _ingest_request_timeout_seconds(request: Request) -> float:
settings: Settings | None = getattr(request.app.state, "settings", None)
if settings is None:
return 5.0
return settings.ingest_request_timeout_seconds
async def _run_ingest_with_timeout(request: Request, operation) -> Any:
return await asyncio.wait_for(
operation,
timeout=_ingest_request_timeout_seconds(request),
)
def _default_sidecar_classifier_command_json(settings: "Settings") -> str | None:
# Availability is evaluated inside the helper's deployment environment.
# The API process may intentionally have fewer model extras installed than
# the ingest/classifier process, so probing imports here creates false
# negatives and silently disables the configured classifier bridge.
del settings
return json.dumps([sys.executable, "-m", "minimappr.sidecar_classifier_helper"])
def _build_runtime_classifier(settings: Settings):
return create_context_classifier(settings, CONTEXT_LOCALIZED_RENDER)
def _parse_window_ns(window: str) -> int:
"""Parse a compact window string (e.g. '24h', '7d', '30m', '1y') into nanoseconds."""
if not window:
raise HTTPException(status_code=400, detail="Empty window")
unit = window[-1].lower()
if unit.isdigit():
# Bare seconds
try:
return int(window) * 1_000_000_000
except ValueError as exc:
raise HTTPException(status_code=400, detail=f"Invalid window '{window}'") from exc
try:
amount = int(window[:-1])
except (TypeError, ValueError) as exc:
raise HTTPException(status_code=400, detail=f"Invalid window '{window}'") from exc
multipliers = {
"s": 1_000_000_000,
"m": 60 * 1_000_000_000,
"h": 3600 * 1_000_000_000,
"d": 86400 * 1_000_000_000,
"w": 7 * 86400 * 1_000_000_000,
"y": 365 * 86400 * 1_000_000_000,
}
if unit not in multipliers:
raise HTTPException(status_code=400, detail=f"Unknown window unit '{unit}'")
return amount * multipliers[unit]
def _require_state(request: Request):
if not hasattr(request.app.state, "storage"):
raise RuntimeError("Storage is not initialized")
return request.app.state
def _require_ws_state(websocket: WebSocket):
if not hasattr(websocket.app.state, "storage"):
raise RuntimeError("Storage is not initialized")
return websocket.app.state
async def _cleanup_loop(app: FastAPI) -> None:
while True:
state = app.state
settings: Settings = state.settings
# Supervised: this loop is the only thing that persists track aging
# (housekeeping_tick → tracker.snapshot → upsert_track). One uncaught
# exception used to kill it silently for the life of the process, after
# which no track was ever aged into storage again.
try:
now_ns = time.time_ns()
cleanup_summary = await state.cleanup_service.run_housekeeping_cycle(now_ns=now_ns)
if any(cleanup_summary["partial_cleanup"].values()) or any(cleanup_summary["retention_cleanup"].values()):
logger.info("Cleanup cycle removed data: %s", cleanup_summary)
await state.fusion_node.housekeeping_tick(now_ns=now_ns)
except asyncio.CancelledError:
raise
except Exception:
logger.exception("Cleanup cycle failed; continuing")
await asyncio.sleep(settings.cleanup_interval_seconds)
async def _ble_tracking_loop(app: FastAPI) -> None:
"""Periodically trilaterate BLE observations into first-class tracks.
Runs in whichever process owns the BLE observation store + tracks storage
(both the combined runtime and the API-only role). Direct-broadcasts each
updated track so WS clients see BLE devices in all deployment modes.
"""
state = app.state
settings: Settings = state.settings
ble_tracker: BleTracker = state.ble_tracker
period_s = max(float(settings.ble_tracking_period_s), 0.1)
while True:
try:
now_ns = time.time_ns()
node_positions = await _ble_node_positions(state)
await ble_tracker.run_tick(
storage=state.storage,
observation_store=_ble_observation_store(state),
node_positions=node_positions,
now_ns=now_ns,
live_hub=state.live_hub,
coordinate_frame=getattr(state, "coordinate_frame", None),
)
except asyncio.CancelledError:
raise
except Exception: # noqa: BLE001
logger.exception("BLE tracking tick failed")
await asyncio.sleep(period_s)
def _apply_site_origin_resolution(state, resolved_site_origin) -> None:
settings: Settings = state.settings
_apply_settings_site_origin_resolution(settings, resolved_site_origin)
state.site_origin_resolution_source = resolved_site_origin.source
state.site_origin_contributing_node_ids = resolved_site_origin.contributing_node_ids
state.site_origin_anchored = resolved_site_origin.is_anchored
def _clear_transient_ingest_runtime_state(state) -> None:
_clear_state_attrs(
state,
"ingest_stream_consumer",
"ingest_stream_consumer_watchdog_task",
"ingest_spool_tasks",
)
def _clear_bound_runtime_state(state) -> None:
_clear_state_attrs(
state,
"settings",
"storage",
"registry",
"cluster_registry",
"ble_observation_store",
"ble_tracker",
"audio_buffer",
"localizer",
"classifier",
"tracker",
"live_hub",
"coordinate_frame",
"zone_matcher",
"environment_provider",
"fusion_node",
"ingest_transport",
"federation",
"bit_evaluator",
"diagnostics",
"cleanup_service",
"ingest_spool_consumer",
"sidecar_state",
"capture_manager",
"ingest_concurrency",
"ingest_stream_consumer_enabled",
"site_origin_resolution_source",
"site_origin_contributing_node_ids",
"effector_manager",
"hass_bridge",
)
def _ensure_lifespan_runtime_directories(settings: Settings) -> None:
settings.federation_peers_config_path.parent.mkdir(parents=True, exist_ok=True)
settings.snippet_dir.mkdir(parents=True, exist_ok=True)
settings.large_artifact_dir.mkdir(parents=True, exist_ok=True)
settings.map_overlay_dir.mkdir(parents=True, exist_ok=True)
settings.effector_snapshot_dir.mkdir(parents=True, exist_ok=True)
def _prepare_lifespan_runtime(state, settings: Settings) -> None:
install_log_ring()
_clear_bound_runtime_state(state)
_clear_transient_ingest_runtime_state(state)
_ensure_lifespan_runtime_directories(settings)
def _bind_runtime_state(state, *, resolved_site_origin=None, **state_fields) -> None:
for name, value in state_fields.items():
setattr(state, name, value)
if resolved_site_origin is not None:
_apply_site_origin_resolution(state, resolved_site_origin)
def _request_hass_reconcile(state) -> None:
"""Nudge the HA bridge after zone/node CRUD so entities appear/vanish now.
Synchronous by design: these are request handlers, and the bridge only sets a
flag its publisher picks up next cycle. The periodic reconcile is the safety
net if a call site is ever missed.
"""
bridge = getattr(state, "hass_bridge", None)
if bridge is not None:
bridge.request_reconcile()
def _warn_when_direct_ingest_falls_back(settings: Settings, sidecar_state: _SidecarState) -> None:
if settings.direct_ingest_enabled or sidecar_state.status == "running":
return
logger.warning(
"Direct ingest is disabled but sidecar is not running (status=%s). "
"Falling back to direct ingest to avoid node ingest outage.",
sidecar_state.status,
)
async def _rebind_site_origin(app: FastAPI, resolved_site_origin) -> None:
"""Swap the process onto a new site origin.
In-memory node position estimators hold ENU metres and are reprojected into
the new frame rather than reset, so a stationary node keeps however many
hours of GNSS averaging it has accumulated. Persisted checkpoints are stored
geodetically and need no migration at all.
"""
state = app.state
settings: Settings = state.settings
candidate_settings = replace(
settings,
site_origin_lat=resolved_site_origin.origin.lat,
site_origin_lon=resolved_site_origin.origin.lon,
site_origin_alt_m=resolved_site_origin.origin.alt_m,
)
new_classifier = _build_runtime_classifier(candidate_settings)
new_coordinate_frame = LocalCoordinateFrame(
origin=resolved_site_origin.origin,
mode=settings.coordinate_mode,
)
previous_coordinate_frame = state.coordinate_frame
previous_classifier = state.classifier
fusion_node = getattr(state, "fusion_node", None)
if fusion_node is not None:
fusion_node.rebind_runtime_dependencies(
classifier=new_classifier,
coordinate_frame=new_coordinate_frame,
)
fusion_node.reproject_position_estimators(previous_coordinate_frame)
state.classifier = new_classifier
state.coordinate_frame = new_coordinate_frame
state.diagnostics.replace_classifier(new_classifier)
_apply_site_origin_resolution(state, resolved_site_origin)
if previous_classifier is not None and previous_classifier is not new_classifier:
try:
previous_classifier.close()
except Exception as exc: # noqa: BLE001
logger.warning("Previous classifier close failed after site-origin change: %s", exc)
def _make_site_origin_anchor(app: FastAPI):
"""Build the ingest callback that anchors the site origin on a trusted GPS fix.
Anchoring is one-shot per site: the first node to report a real fix defines
the origin, it is persisted so every process and every restart agrees, and
the callback uninstalls itself. Sites with no GPS simply never anchor and
keep running on the configured fallback.
"""
lock = asyncio.Lock()
async def anchor(node_id: str, geo: GeoPoint) -> None:
state = app.state
async with lock:
if getattr(state, "site_origin_anchored", False):
return
resolution = SiteOriginResolution(
origin=geo,
source=SOURCE_GPS_ANCHOR,
contributing_node_ids=(node_id,),
)
# Persist before adopting. This runs on the ingest frame path, so a
# storage failure must neither reject the frame nor latch the anchor
# shut — leaving it armed lets the next frame retry.
try:
await persist_site_origin(state.storage, resolution)
except Exception as exc: # noqa: BLE001
logger.warning(
"Persisting GPS-anchored site origin from node %s failed; "
"will retry on the next frame: %s",
node_id,
exc,
)
return
state.site_origin_anchored = True
previous = GeoPoint(
lat=state.settings.site_origin_lat,
lon=state.settings.site_origin_lon,
alt_m=state.settings.site_origin_alt_m,
)
if origins_differ(previous, geo):
await _rebind_site_origin(app, resolution)
else:
_apply_site_origin_resolution(state, resolution)
_install_site_origin_anchor(app)
logger.info(
"Anchored site origin from node %s GPS fix: lat=%.6f lon=%.6f alt=%.2f "
"(was lat=%.6f lon=%.6f)",
node_id,
geo.lat,
geo.lon,
geo.alt_m,
previous.lat,
previous.lon,
)
return anchor
def _install_site_origin_anchor(app: FastAPI) -> None:
"""Arm or disarm GPS anchoring to match the current anchored state."""
state = app.state
fusion_node = getattr(state, "fusion_node", None)
if fusion_node is None:
return
if getattr(state, "site_origin_anchored", False):
fusion_node.set_site_origin_anchor(None)
return
fusion_node.set_site_origin_anchor(_make_site_origin_anchor(app))
logger.info(
"Site origin is un-anchored (source=%s); awaiting a trusted GPS fix from any node",
getattr(state, "site_origin_resolution_source", "unknown"),
)
async def _sync_site_origin_from_storage(app: FastAPI) -> None:
"""Adopt an origin anchored by the ingest process.
Only the ingest process sees frames, so it is the one that anchors. The api
process reads the persisted result and rebinds, which is what keeps the two
from drifting into disagreeing coordinate frames.
"""
state = app.state
settings: Settings = state.settings
if settings.site_origin_source == "manual":
return
persisted = await state.storage.get_site_origin()
if persisted is None:
return
origin = GeoPoint(
lat=float(persisted["lat"]),
lon=float(persisted["lon"]),
alt_m=float(persisted["alt_m"]),
)
current = GeoPoint(
lat=settings.site_origin_lat,
lon=settings.site_origin_lon,
alt_m=settings.site_origin_alt_m,
)
if not origins_differ(current, origin) and getattr(state, "site_origin_anchored", False):
return
await _rebind_site_origin(
app,
SiteOriginResolution(
origin=origin,
source=SOURCE_PERSISTED,
contributing_node_ids=tuple(persisted.get("contributing_node_ids") or ()),
),
)
logger.info(
"Adopted persisted site origin: lat=%.6f lon=%.6f alt=%.2f", origin.lat, origin.lon, origin.alt_m
)
async def _api_live_db_poll_loop(app: FastAPI) -> None:
"""Bridge ingest-process DB writes into API-process websocket updates."""
state = app.state
settings: Settings = state.settings
last_detection_ts = time.time_ns()
last_track_ts = last_detection_ts
last_environment_ts = 0
seen_detection_ids: set[str] = set()
seen_track_ids: set[str] = set()
while True:
try:
await _sync_site_origin_from_storage(app)
detections = await state.storage.list_detections(
limit=100,
since_ns=last_detection_ts,
min_label_confidence=settings.detection_min_confidence,
)
for detection in sorted(detections, key=lambda item: int(item.get("timestamp_ns") or 0)):
detection_id = str(detection.get("id") or detection.get("event_id") or "")
timestamp_ns = int(detection.get("timestamp_ns") or last_detection_ts)
if detection_id and detection_id not in seen_detection_ids:
await state.live_hub.broadcast(
{
"type": "detection",
"event_id": detection.get("event_id"),
"event_type": "detection",
"detection": detection,
"track": None,
"server_time_ns": time.time_ns(),
}
)
seen_detection_ids.add(detection_id)
if len(seen_detection_ids) > 512:
seen_detection_ids = set(list(seen_detection_ids)[-256:])
last_detection_ts = max(last_detection_ts, timestamp_ns)
tracks = await state.storage.list_tracks(limit=100, since_ns=last_track_ts)
for track in sorted(tracks, key=lambda item: int(item.get("last_seen_ns") or 0)):
track_id = str(track.get("id") or "")
last_seen_ns = int(track.get("last_seen_ns") or last_track_ts)
dedupe_key = f"{track_id}:{last_seen_ns}"
if track_id and dedupe_key not in seen_track_ids:
await state.live_hub.broadcast(
{
"type": "track_updated",
"track": track,
"server_time_ns": time.time_ns(),
}
)
seen_track_ids.add(dedupe_key)
if len(seen_track_ids) > 512:
seen_track_ids = set(list(seen_track_ids)[-256:])
last_track_ts = max(last_track_ts, last_seen_ns)
# Hydrate the API-process environment provider from storage. In the
# split api/ingest deployment, environment ingest is proxied to the
# ingest worker, so this process's provider would otherwise stay
# empty and /api/v1/environment/current would report static_fallback.
environment_provider = getattr(state, "environment_provider", None)
if environment_provider is not None and hasattr(
environment_provider, "ingest_sample"
):
latest_environment = await state.storage.list_latest_environment_per_node()
for reading in latest_environment:
timestamp_ns = int(reading.get("timestamp_ns") or 0)
if timestamp_ns <= last_environment_ts:
continue
position = reading.get("position_m")
location_m = (
tuple(float(value) for value in position)
if position is not None
else None
)
environment_provider.ingest_sample(
node_id=str(reading.get("node_id") or ""),
timestamp_ns=timestamp_ns,
temperature_c=reading.get("temperature_c"),
humidity_fraction=reading.get("humidity_fraction"),
pressure_pa=reading.get("pressure_pa"),
wind_speed_mps=reading.get("wind_speed_mps"),
wind_dir_deg=reading.get("wind_dir_deg"),
solar_lux=reading.get("solar_lux"),
location_m=location_m,
metadata=reading.get("metadata") or {},
)
last_environment_ts = max(last_environment_ts, timestamp_ns)
except asyncio.CancelledError:
raise
except Exception as exc: # noqa: BLE001
logger.warning("API live DB poll failed: %s", exc)
await asyncio.sleep(1.0)
# Keep the historical private name stable for local call sites and tests while
# delegating the implementation to the dedicated sidecar runtime module.
_SidecarState = _RuntimeSidecarState
class _EnvironmentIngestSample(BaseModel):
node_id: str
sample: EnvironmentSampleIn
class _EnvironmentIngestBody(BaseModel):
samples: list[_EnvironmentIngestSample]
def _ble_observation_store(state) -> BleObservationStore:
store = getattr(state, "ble_observation_store", None)
if store is None:
store = BleObservationStore()
setattr(state, "ble_observation_store", store)
return store
def _ingest_sidecar_is_running(state) -> bool:
return _runtime_ingest_sidecar_is_running(state)
def _should_block_direct_ingest(state) -> bool:
"""Return True when direct ingest must be rejected in favor of sidecar ingest.
Direct ingest should only be hard-blocked when operators disabled it and the
sidecar is confirmed running. If sidecar startup fails (missing binary,
crash, misconfiguration), we fail open to keep nodes reporting instead of
creating a complete ingest outage.
"""
if state.settings.direct_ingest_enabled:
return False
return _ingest_sidecar_is_running(state)
def _should_autostart_ingest_sidecar(settings: "Settings") -> bool:
return _runtime_should_autostart_ingest_sidecar(settings)
def _ingest_sidecar_startup_config(settings) -> IngestSidecarStartupConfig:
return _runtime_ingest_sidecar_startup_config(settings)
def _ingest_sidecar_process_config(settings) -> IngestSidecarProcessConfig:
return _runtime_ingest_sidecar_process_config(settings)
def _sidecar_classification_window_seconds(settings) -> float:
return _runtime_sidecar_classification_window_seconds(settings)
def _sidecar_classifier_render_min_interval_seconds(
settings,
*,
classification_window_seconds: float,
) -> float:
return _runtime_sidecar_classifier_render_min_interval_seconds(
settings,
classification_window_seconds=classification_window_seconds,
)
def _sidecar_classifier_command_json(settings) -> str | None:
classifier_command_json = os.environ.get("MINIMAPPR_SIDECAR_CLASSIFIER_COMMAND_JSON")
if classifier_command_json is not None:
return classifier_command_json
return _default_sidecar_classifier_command_json(settings)
def _build_ingest_sidecar_environment(settings) -> dict[str, str]:
return _runtime_build_ingest_sidecar_environment(
settings,
default_classifier_command_json_builder=_default_sidecar_classifier_command_json,
)
def _ingest_runtime_base_url(settings: "Settings") -> str:
return settings.ingest_base_url.rstrip("/")
def _should_proxy_ingest_to_python_worker(state) -> bool:
settings = state.settings
return (
getattr(settings, "process_role", "combined") == "api"
and getattr(settings, "ingest_backend", "python") == "python"
and settings.ingest_port != settings.port
and os.getenv("MINIMAPPR_INGEST_PORT") is not None
)
async def _proxy_json_to_python_worker(
state,
*,
method: str,
endpoint_path: str,
json_body: object | None = None,
) -> dict | list:
settings = state.settings
if settings.ingest_port == settings.port:
raise HTTPException(
status_code=503,
detail="Ingest proxy is misconfigured: ingest_port matches API port",
)
target_url = f"{_ingest_runtime_base_url(settings)}{endpoint_path}"
payload = None if json_body is None else json.dumps(json_body).encode("utf-8")
headers = {"Content-Type": "application/json"} if payload is not None else {}
def _request() -> tuple[int, bytes]:
request = urllib.request.Request(
target_url,
data=payload,
method=method,
headers=headers,
)
with urllib.request.urlopen(request, timeout=30.0) as response:
status = int(getattr(response, "status", 200))
return status, response.read()
try:
status, response_payload = await asyncio.to_thread(_request)
except urllib.error.HTTPError as exc:
detail = exc.reason or "Ingest worker error"
error_payload = exc.read()
try:
parsed = json.loads(error_payload)
if isinstance(parsed, dict) and parsed.get("detail"):
detail = str(parsed["detail"])
except Exception:
pass
raise HTTPException(status_code=exc.code, detail=detail) from exc
except urllib.error.URLError as exc:
raise HTTPException(status_code=503, detail=f"Ingest worker unreachable: {exc}") from exc
if not response_payload:
return {}
try:
decoded = json.loads(response_payload.decode("utf-8"))
except Exception as exc:
raise HTTPException(status_code=502, detail="Invalid JSON response from ingest worker") from exc
if not isinstance(decoded, (dict, list)):
raise HTTPException(status_code=502, detail="Unexpected response shape from ingest worker")
if status >= 400:
detail = decoded.get("detail") if isinstance(decoded, dict) else "Ingest worker error"
raise HTTPException(status_code=status, detail=str(detail or "Ingest worker error"))
return decoded
async def _proxy_ingest_post(
state,
*,
endpoint_path: str,
body: bytes,
content_type: str,
) -> dict:
settings = state.settings
if settings.ingest_port == settings.port:
raise HTTPException(
status_code=503,
detail="Ingest proxy is misconfigured: ingest_port matches API port",
)
target_url = f"{_ingest_runtime_base_url(settings)}{endpoint_path}"
def _post() -> tuple[int, bytes]:
request = urllib.request.Request(
target_url,
data=body,
method="POST",
headers={"Content-Type": content_type},
)
with urllib.request.urlopen(request, timeout=15.0) as response:
status = int(getattr(response, "status", 200))
payload = response.read()
return status, payload
try:
status, payload = await asyncio.to_thread(_post)
except urllib.error.HTTPError as exc:
detail = f"Ingest worker returned HTTP {exc.code}"
try:
error_payload = exc.read().decode("utf-8")
parsed = json.loads(error_payload)
if isinstance(parsed, dict) and parsed.get("detail"):
detail = str(parsed["detail"])
except Exception:
pass
raise HTTPException(status_code=exc.code, detail=detail) from exc
except urllib.error.URLError as exc:
raise HTTPException(status_code=503, detail=f"Ingest worker unreachable: {exc}") from exc
if not payload:
return {}
try:
decoded = json.loads(payload.decode("utf-8"))
except Exception as exc:
raise HTTPException(status_code=502, detail="Invalid JSON response from ingest worker") from exc
if not isinstance(decoded, dict):
raise HTTPException(status_code=502, detail="Unexpected response shape from ingest worker")
if status >= 400:
raise HTTPException(status_code=status, detail=str(decoded.get("detail") or "Ingest worker error"))
return decoded
def _capture_pipeline_status(state) -> tuple[bool, str | None]:
settings: Settings | None = getattr(state, "settings", None)
if settings is None:
return False, "Capture is unavailable because runtime settings are not initialized"