From 70ef3f9f1ce92c2f31428fecf2e73123d8fac7fd Mon Sep 17 00:00:00 2001 From: DCCONSTRUCTIONS Date: Thu, 29 Oct 2026 09:09:58 +0300 Subject: [PATCH] chore(storage): bound build retention, caches and test resources Track build ownership, qualified pins and bounded cache/log lifecycles. Move Vite fixtures to a job-owned server helper and preserve private outputs outside Git. --- .gitignore | 3 + AGENTS.md | 72 ++ .../test/advancedLaboratoryResults.test.mjs | 2 +- .../test/boardObservation.test.mjs | 2 +- .../test/canonicalRecordedLab.test.mjs | 2 +- .../test/contourHealth.test.mjs | 2 +- .../test/datasetGateway.test.mjs | 2 +- .../test/devicePluginContracts.test.mjs | 2 +- .../devicePluginFrontendBoundary.test.mjs | 2 +- .../test/devicePluginHostPersistence.test.mjs | 2 +- .../control-station/test/e29Evidence.test.mjs | 2 +- .../test/e30Engineering.test.mjs | 2 +- .../test/e30HumanReview.test.mjs | 2 +- apps/control-station/test/e30Review.test.mjs | 2 +- .../test/e40CaseReview.test.mjs | 2 +- .../test/e46cVideoReplay.test.mjs | 2 +- .../test/e46dTemporalFailureAudit.test.mjs | 2 +- .../test/e46eReadyStack.test.mjs | 2 +- .../test/e46fDashCamBakeoff.test.mjs | 2 +- .../e46gRectifiedDetectorBakeoff.test.mjs | 2 +- .../e46hFullRectifiedFrontReplay.test.mjs | 2 +- .../test/e46jRawFisheyeRealtime.test.mjs | 2 +- .../test/e47SemanticSlam.test.mjs | 2 +- .../test/environmentBackgroundMedia.test.mjs | 2 +- .../test/environmentSettings.test.mjs | 2 +- apps/control-station/test/ghostPins.test.mjs | 2 +- .../test/groundQualification.test.mjs | 2 +- .../test/insta360Panorama.test.mjs | 2 +- .../test/k1ActiveStreamRecovery.test.mjs | 2 +- .../test/k1ManualControl.test.mjs | 2 +- .../test/k1PreviewFrames.test.mjs | 2 +- .../test/k1SupervisorPresentation.test.mjs | 2 +- .../test/labViewProfile.test.mjs | 2 +- .../test/laboratoryEvidenceReport.test.mjs | 2 +- ...laboratoryRecordedEvidenceProfile.test.mjs | 2 +- .../test/lidarReplayQuality.test.mjs | 2 +- .../test/liveReceiverWatchdog.test.mjs | 2 +- .../test/liveViewerDiagnostics.test.mjs | 2 +- .../test/localSurface.test.mjs | 2 +- .../test/m47ReferenceGraph.test.mjs | 2 +- .../test/m48ObjectCentricQuality.test.mjs | 2 +- .../test/m48SmallStaticRegression.test.mjs | 2 +- .../test/m48sFixedClassDetector.test.mjs | 2 +- .../test/m48tRiskQuality.test.mjs | 2 +- .../test/m49PhysicalSafetyPlayback.test.mjs | 2 +- .../test/m49TgsFullShadow.test.mjs | 2 +- .../test/m4ReplayThreat.test.mjs | 2 +- .../test/missionPlanner.test.mjs | 2 +- .../test/networkProvisioning.test.mjs | 2 +- .../test/observationSessions.test.mjs | 2 +- .../test/observationSources.test.mjs | 2 +- .../test/observatoryCatalog.test.mjs | 2 +- .../test/observatoryCatalogMutations.test.mjs | 2 +- .../test/observatoryHooks.test.mjs | 2 +- .../test/observatoryLaboratorySetups.test.mjs | 2 +- .../test/observatoryRecordedJobs.test.mjs | 2 +- .../test/observatoryRecordedProgress.test.mjs | 2 +- .../test/observatoryRecordedRun.test.mjs | 2 +- .../test/observatoryWorkspace.test.mjs | 2 +- .../test/perceptionPreparation.test.mjs | 2 +- .../planningPresentationTelemetry.test.mjs | 2 +- .../test/planningProjectDeletion.test.mjs | 2 +- .../test/planningSceneStream.test.mjs | 2 +- .../test/planningSceneTools.test.mjs | 2 +- .../test/planningWholeRecording.test.mjs | 2 +- .../test/polygonRunArchive.test.mjs | 2 +- .../test/productShellContract.test.mjs | 2 +- .../test/recordedCameraBuffering.test.mjs | 2 +- .../test/recordedRerunCameraJournal.test.mjs | 2 +- .../test/recordedSessionAdmission.test.mjs | 2 +- .../recordedViewerResourceLifecycle.test.mjs | 2 +- .../rerunViewportAtomicAdmission.test.mjs | 2 +- .../test/rerunViewportPlayback.test.mjs | 2 +- .../rerunViewportProgressivePlayback.test.mjs | 2 +- .../test/roverConfiguration.test.mjs | 2 +- .../test/runtimeAcquisitionGuard.test.mjs | 2 +- .../test/runtimeStateOrdering.test.mjs | 2 +- .../test/sensorEnrollment.test.mjs | 2 +- .../test/sessionDisplayProfile.test.mjs | 2 +- .../test/sessionOverview.test.mjs | 2 +- .../test/sessionOverviewComparison.test.mjs | 2 +- .../test/spatialSceneLayout.test.mjs | 2 +- apps/control-station/test/support/README.md | 15 + .../test/support/vite-server.mjs | 62 ++ .../test/vegetationShadow.test.mjs | 2 +- .../test/viewerProfile.test.mjs | 2 +- .../test/viewerSettingsCommit.test.mjs | 2 +- .../test/viewerSettingsTarget.test.mjs | 2 +- .../test/viteServerLifecycle.test.mjs | 47 ++ .../test/workspaceLayout.test.mjs | 2 +- docs/03_ARTIFACT_POLICY.md | 6 + docs/STORAGE_RETENTION.md | 269 ++++++++ scripts/check_python.py | 84 +++ scripts/manage_map_gateway_link.py | 127 +++- scripts/manage_runtime_log_policy.py | 173 +++++ scripts/manage_telemetry_startup.py | 4 +- scripts/migrate_worker_tunnel_logs.py | 10 +- scripts/packaging/build_retention.py | 616 ++++++++++++++++++ src/k1link/cache_budget.py | 113 ++++ src/k1link/compute/fusion_epoch.py | 58 +- src/k1link/compute/integrated_perception.py | 95 +-- src/k1link/compute/results.py | 69 +- .../laboratory/canonical_rerun_overlay.py | 76 ++- src/k1link/launchd_logs.py | 58 ++ src/k1link/local_service_launchd.py | 40 +- src/k1link/observatory/portable_replay.py | 57 +- .../observatory/worker_tunnel_launchd.py | 11 +- src/k1link/rotating_process.py | 169 +++++ src/k1link/sessions/camera_frame.py | 11 +- src/k1link/sessions/media.py | 15 +- .../simulation/ai_polygon/editor_cache.py | 53 +- src/k1link/web/lidar_local_surface_service.py | 38 +- src/k1link/web/runtime_diagnostics.py | 28 +- tests/test_build_retention.py | 476 ++++++++++++++ tests/test_cache_budget.py | 111 ++++ tests/test_e10_integrated_perception.py | 48 ++ tests/test_local_service_launchd.py | 11 +- tests/test_rotating_process.py | 133 ++++ tests/test_runtime_log_policy.py | 131 ++++ 119 files changed, 3128 insertions(+), 331 deletions(-) create mode 100644 apps/control-station/test/support/README.md create mode 100644 apps/control-station/test/support/vite-server.mjs create mode 100644 apps/control-station/test/viteServerLifecycle.test.mjs create mode 100644 docs/STORAGE_RETENTION.md create mode 100644 scripts/check_python.py create mode 100644 scripts/manage_runtime_log_policy.py create mode 100644 scripts/packaging/build_retention.py create mode 100644 src/k1link/cache_budget.py create mode 100644 src/k1link/rotating_process.py create mode 100644 tests/test_build_retention.py create mode 100644 tests/test_cache_budget.py create mode 100644 tests/test_rotating_process.py create mode 100644 tests/test_runtime_log_policy.py diff --git a/.gitignore b/.gitignore index f443432b..3accb795 100644 --- a/.gitignore +++ b/.gitignore @@ -56,3 +56,6 @@ node_modules # Private experiment evidence and generated build archives. /outputs/ + +# Packaged WireGuard binaries are published artifacts, not source. +/apps/wireguard-client/build/ diff --git a/AGENTS.md b/AGENTS.md index 74f1fb1d..657cfce7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,9 +27,36 @@ links to that record for monorepo, storage, resource and live-only telemetry rul build-input packages per active build line; preserve separately designated qualified releases and required rollback artifacts. Do not accumulate a new full package after every iteration without retiring superseded intermediates. +- Build storage lifecycle is implemented by `scripts/packaging/build_retention.py`; + follow `docs/STORAGE_RETENTION.md`. New input generators return a persistent + active owner handle. After the remote job/transfer/qualification is confirmed + terminal, close only your own hold with `finish` (pin qualified/rollback + outcomes), review its plan and apply it as part of build completion. Never + expire active holds by age or declare unknown legacy inputs disposable. +- Run local Python validation through `scripts/check_python.py pytest|ruff|mypy` + (pass the usual file/selection arguments). It owns temporary caches, disables + persistent pytest/Ruff cache output, and cleans its own scratch after child + processes end. Never sweep another active job's cache or unknown crash residue. +- Runtime cache publication quotas and bounded service journals are defined in + `docs/STORAGE_RETENTION.md`. Existing replay/overlay data remains protected; + a full quota refuses a new copy rather than deleting recovery material. - Check disk space before large builds or captures. Keep task scratch work under `.runtime` and clean generated scratch at completion; do not scatter temporary project folders through the parent repository directory. +- Owner amendment, 2026-10-19: completed simulation/urban-infrastructure + engineering experiments must not retain unlimited raw frames, render arrays + and step-by-step traces by default. At closeout preserve a compact textual + report, exact inputs/configuration/source identities, result/limitations and + regression evidence; archive text with verified hashes, then retire the + explicitly inventoried disposable derived files after all owners stop. + Use one content-addressed text copy for duplicates. Keep only the limited + visual evidence needed by the final report. Do not leave a complete new + media export after every iteration or require the owner to clean it manually. + This is a closeout obligation for engineering-owned scratch, not permission + to TTL-delete application runs, scans, accepted maps, working code, offline + dependencies, installers, qualified releases or pinned rollback. Unknown or + active ownership blocks removal; retain a deletion receipt and link the + archive from the report/Ops. See the amendment in docs/STORAGE_RETENTION.md. - Other repositories, platform worktrees, infrastructure, DOC, workspace bridge, Site/SEO, BIM Viewer, Device Core, Design Guideline, and Gaussian Pipeline are separate ownership boundaries. Mission Core cleanup must not alter them. @@ -39,6 +66,14 @@ links to that record for monorepo, storage, resource and live-only telemetry rul monitoring requires an explicitly provisioned separate service; simulation evidence and recordings have a separate lifecycle and must not be deleted as part of telemetry cleanup. +- Owner amendment, 2026-10-20: new semantic-learning images, observations, + datasets, checkpoints and heavy experiments belong to a separate portable + persistent store on Worker 006, outside the source checkout and container + writable layer. Never accumulate them on the operator Mac or add a local + fallback. Core may keep viewer scenes, semantic results and bounded edit + metadata. Saving an edit is not dataset preparation or training acceptance; + retain the immutable algorithm result and human provenance separately. + See `docs/SEMANTIC_EDITOR.md` for the delivered scope and outstanding gates. ## Non-negotiable safety boundaries @@ -254,3 +289,40 @@ decoders before BLE/Wi-Fi/data-session evidence exists. - Spatial evidence uses 3D by default. Image-space reprojection may be offered as a 2D diagnostic mode inside the same reusable viewer. Primary evidence viewers must provide the canonical expand/restore action. + + +## Urban semantic agent contract — owner requirement, 2026-10-26 + +- Product foundation: read `docs/SCENE_SEMANTICS_PRODUCT_CONCEPT.md`. Each scan is + a standalone local scene, including unnamed/unmapped locations. Raw recorded + sensor points support localization; Gaussian observations support the current + semantic research. Never substitute Gaussian-derived geometry for raw points. +- No GPS/address/public-map prerequisite and no automatic cross-scan geographic + matching, overlap search, registration or merging. Those require a separate + explicit owner request. Named train/evaluation source lists do not authorize + geographic investigation. Preserve source lineage and evaluation honesty. +- Crosswalks are functionally important; the target includes all observed road + markings for scene context, interface/product value and difficult-task + validation. Do not reduce the scope to demo-only markings or crosswalks only. + +- For automated infrastructure annotation, dataset preparation and learning, + begin with live Ops MISSIONCOR-93 (agent contract) and MISSIONCOR-88 (product), + then `docs/SEMANTIC_AGENT_OPERATING_CONTRACT.md`. Reuse the current hypothesis + register and existing experiments; a new chat does not reset the investigation. +- The owner explicitly requests MISSIONCOR-93 to hold current architecture, + rules, bounded next steps and portable handoff. This is the scoped exception + to the earlier delivered-results-only Ops rule. Keep raw logs/media in local + engineering evidence; update the current card blocks after meaningful changes. +- Root owns the useful outcome, real dispatch, integration and final decision. + Use one reusable critic and an optional bounded research scout, at most two + active helpers and no nested delegation. Send compact briefs, not full history. +- New annotation cycles use the v2 objective/dispatch contract. Approved partial + annotations are distinct from completing the enclosing product work package. + Handle introduced critical regressions within the session or revert/isolate + the change. Do not declare success merely because a ledger or test completed. +- Choose reusable pipelines against actual inputs/outputs and accumulated + evidence before narrow tuning. Every closed hypothesis states tested scope, + supporting artifacts and a substantive condition for reopening. Do not repeat + unchanged searches or model variants under a new name. +- Worker access/power/runtime authority comes from the owner's current session + instructions, never from the card or an old experiment's training allowance. diff --git a/apps/control-station/test/advancedLaboratoryResults.test.mjs b/apps/control-station/test/advancedLaboratoryResults.test.mjs index 97797bef..048a6b70 100644 --- a/apps/control-station/test/advancedLaboratoryResults.test.mjs +++ b/apps/control-station/test/advancedLaboratoryResults.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchAdvancedLaboratoryResults; diff --git a/apps/control-station/test/boardObservation.test.mjs b/apps/control-station/test/boardObservation.test.mjs index d1029ee4..1acc5dca 100644 --- a/apps/control-station/test/boardObservation.test.mjs +++ b/apps/control-station/test/boardObservation.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {after,before,test} from 'node:test'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; let server,layout,source,fanout,catalog; before(async()=>{ server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}}); diff --git a/apps/control-station/test/canonicalRecordedLab.test.mjs b/apps/control-station/test/canonicalRecordedLab.test.mjs index c965e1ad..244a9adf 100644 --- a/apps/control-station/test/canonicalRecordedLab.test.mjs +++ b/apps/control-station/test/canonicalRecordedLab.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let canonicalMapGravityLocalPointToBodyGround; diff --git a/apps/control-station/test/contourHealth.test.mjs b/apps/control-station/test/contourHealth.test.mjs index 0154ce9c..bb37ac56 100644 --- a/apps/control-station/test/contourHealth.test.mjs +++ b/apps/control-station/test/contourHealth.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; let server,readContourSnapshot,contourSummary,workerAvailable; before(async()=>{ diff --git a/apps/control-station/test/datasetGateway.test.mjs b/apps/control-station/test/datasetGateway.test.mjs index ed7e2a48..89308517 100644 --- a/apps/control-station/test/datasetGateway.test.mjs +++ b/apps/control-station/test/datasetGateway.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseDatasetGatewayCatalog; diff --git a/apps/control-station/test/devicePluginContracts.test.mjs b/apps/control-station/test/devicePluginContracts.test.mjs index f815cb4a..59f74e16 100644 --- a/apps/control-station/test/devicePluginContracts.test.mjs +++ b/apps/control-station/test/devicePluginContracts.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseDevicePluginManifest; diff --git a/apps/control-station/test/devicePluginFrontendBoundary.test.mjs b/apps/control-station/test/devicePluginFrontendBoundary.test.mjs index 6551aa24..15384b71 100644 --- a/apps/control-station/test/devicePluginFrontendBoundary.test.mjs +++ b/apps/control-station/test/devicePluginFrontendBoundary.test.mjs @@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url"; import { dirname, join, resolve } from "node:path"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; const testRoot = dirname(fileURLToPath(import.meta.url)); const controlStationRoot = resolve(testRoot, ".."); diff --git a/apps/control-station/test/devicePluginHostPersistence.test.mjs b/apps/control-station/test/devicePluginHostPersistence.test.mjs index 7b7b54da..98327f2b 100644 --- a/apps/control-station/test/devicePluginHostPersistence.test.mjs +++ b/apps/control-station/test/devicePluginHostPersistence.test.mjs @@ -4,7 +4,7 @@ import { after, before, test } from "node:test"; import React, { createElement } from "react"; import { renderToStaticMarkup } from "react-dom/server"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let DEVICE_PLUGIN_SELECTED_MODEL_STORAGE_KEY; diff --git a/apps/control-station/test/e29Evidence.test.mjs b/apps/control-station/test/e29Evidence.test.mjs index 9a72a97c..e668efd1 100644 --- a/apps/control-station/test/e29Evidence.test.mjs +++ b/apps/control-station/test/e29Evidence.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseE29EvidenceCatalog; diff --git a/apps/control-station/test/e30Engineering.test.mjs b/apps/control-station/test/e30Engineering.test.mjs index 14791b25..c1e9a4be 100644 --- a/apps/control-station/test/e30Engineering.test.mjs +++ b/apps/control-station/test/e30Engineering.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseE30EngineeringCatalog; diff --git a/apps/control-station/test/e30HumanReview.test.mjs b/apps/control-station/test/e30HumanReview.test.mjs index 3044fc24..f09bf3be 100644 --- a/apps/control-station/test/e30HumanReview.test.mjs +++ b/apps/control-station/test/e30HumanReview.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseE30HumanReviewDraft; diff --git a/apps/control-station/test/e30Review.test.mjs b/apps/control-station/test/e30Review.test.mjs index 25665a43..f887c7e9 100644 --- a/apps/control-station/test/e30Review.test.mjs +++ b/apps/control-station/test/e30Review.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseE30ReviewCatalog; diff --git a/apps/control-station/test/e40CaseReview.test.mjs b/apps/control-station/test/e40CaseReview.test.mjs index ad0d4df5..a42f4146 100644 --- a/apps/control-station/test/e40CaseReview.test.mjs +++ b/apps/control-station/test/e40CaseReview.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseE40CaseCatalog; diff --git a/apps/control-station/test/e46cVideoReplay.test.mjs b/apps/control-station/test/e46cVideoReplay.test.mjs index 7203665a..a28c0f38 100644 --- a/apps/control-station/test/e46cVideoReplay.test.mjs +++ b/apps/control-station/test/e46cVideoReplay.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchE46CVideoOverlay; diff --git a/apps/control-station/test/e46dTemporalFailureAudit.test.mjs b/apps/control-station/test/e46dTemporalFailureAudit.test.mjs index 3902e300..d83a8cec 100644 --- a/apps/control-station/test/e46dTemporalFailureAudit.test.mjs +++ b/apps/control-station/test/e46dTemporalFailureAudit.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import test, { after, before } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchE46DTemporalFailureAudit; diff --git a/apps/control-station/test/e46eReadyStack.test.mjs b/apps/control-station/test/e46eReadyStack.test.mjs index e4a0d0ef..c96159f6 100644 --- a/apps/control-station/test/e46eReadyStack.test.mjs +++ b/apps/control-station/test/e46eReadyStack.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import test, { after, before } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchE46EReadyStack; diff --git a/apps/control-station/test/e46fDashCamBakeoff.test.mjs b/apps/control-station/test/e46fDashCamBakeoff.test.mjs index 08e86df4..8c7b58ef 100644 --- a/apps/control-station/test/e46fDashCamBakeoff.test.mjs +++ b/apps/control-station/test/e46fDashCamBakeoff.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import test, { after, before } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchE46FDashCamBakeoff; diff --git a/apps/control-station/test/e46gRectifiedDetectorBakeoff.test.mjs b/apps/control-station/test/e46gRectifiedDetectorBakeoff.test.mjs index ee6dc16f..c507e82f 100644 --- a/apps/control-station/test/e46gRectifiedDetectorBakeoff.test.mjs +++ b/apps/control-station/test/e46gRectifiedDetectorBakeoff.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import test, { after, before } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchE46GRectifiedDetectorBakeoff; diff --git a/apps/control-station/test/e46hFullRectifiedFrontReplay.test.mjs b/apps/control-station/test/e46hFullRectifiedFrontReplay.test.mjs index b3598662..9ef1d3ea 100644 --- a/apps/control-station/test/e46hFullRectifiedFrontReplay.test.mjs +++ b/apps/control-station/test/e46hFullRectifiedFrontReplay.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import test, { after, before } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchE46HFullRectifiedFrontReplay; diff --git a/apps/control-station/test/e46jRawFisheyeRealtime.test.mjs b/apps/control-station/test/e46jRawFisheyeRealtime.test.mjs index 0339f4e8..20252b8f 100644 --- a/apps/control-station/test/e46jRawFisheyeRealtime.test.mjs +++ b/apps/control-station/test/e46jRawFisheyeRealtime.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import test, { after, before } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchE46JRawFisheyeRealtime; diff --git a/apps/control-station/test/e47SemanticSlam.test.mjs b/apps/control-station/test/e47SemanticSlam.test.mjs index a7547d36..1c2ad8f8 100644 --- a/apps/control-station/test/e47SemanticSlam.test.mjs +++ b/apps/control-station/test/e47SemanticSlam.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchE47SemanticSlamResult; diff --git a/apps/control-station/test/environmentBackgroundMedia.test.mjs b/apps/control-station/test/environmentBackgroundMedia.test.mjs index 336989b3..873c5f92 100644 --- a/apps/control-station/test/environmentBackgroundMedia.test.mjs +++ b/apps/control-station/test/environmentBackgroundMedia.test.mjs @@ -3,7 +3,7 @@ import { after, before, test } from "node:test"; import React from "react"; import { renderToStaticMarkup } from "react-dom/server"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let backgroundMedia; diff --git a/apps/control-station/test/environmentSettings.test.mjs b/apps/control-station/test/environmentSettings.test.mjs index 7973b9be..35d137f9 100644 --- a/apps/control-station/test/environmentSettings.test.mjs +++ b/apps/control-station/test/environmentSettings.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let environment; diff --git a/apps/control-station/test/ghostPins.test.mjs b/apps/control-station/test/ghostPins.test.mjs index 7ecf3ee9..8bee912b 100644 --- a/apps/control-station/test/ghostPins.test.mjs +++ b/apps/control-station/test/ghostPins.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let ghostPins; diff --git a/apps/control-station/test/groundQualification.test.mjs b/apps/control-station/test/groundQualification.test.mjs index 74cad0bc..2e8b88fa 100644 --- a/apps/control-station/test/groundQualification.test.mjs +++ b/apps/control-station/test/groundQualification.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let decodeGroundQualification; diff --git a/apps/control-station/test/insta360Panorama.test.mjs b/apps/control-station/test/insta360Panorama.test.mjs index 6116db08..f9c0018f 100644 --- a/apps/control-station/test/insta360Panorama.test.mjs +++ b/apps/control-station/test/insta360Panorama.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {after,before,test} from 'node:test'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; let server,optics,exposure; before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});optics=await server.ssrLoadModule('../../plugins/insta360-x4/frontend/src/panoramaCalibration.ts');exposure=await server.ssrLoadModule('../../plugins/insta360-x4/frontend/src/panoramaExposure.ts');}); after(async()=>{await server?.close();}); diff --git a/apps/control-station/test/k1ActiveStreamRecovery.test.mjs b/apps/control-station/test/k1ActiveStreamRecovery.test.mjs index 5901ffbf..2f8adf49 100644 --- a/apps/control-station/test/k1ActiveStreamRecovery.test.mjs +++ b/apps/control-station/test/k1ActiveStreamRecovery.test.mjs @@ -4,7 +4,7 @@ import { after, before, test } from "node:test"; import React, { createElement } from "react"; import { renderToStaticMarkup } from "react-dom/server"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let activeStreamForceFinishAuthority; diff --git a/apps/control-station/test/k1ManualControl.test.mjs b/apps/control-station/test/k1ManualControl.test.mjs index 8a56e22a..2c7dc2a2 100644 --- a/apps/control-station/test/k1ManualControl.test.mjs +++ b/apps/control-station/test/k1ManualControl.test.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; import {createElement} from 'react'; import {renderToStaticMarkup} from 'react-dom/server'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; let server,Detail,presentation,enrolledDevice; before(async()=>{ diff --git a/apps/control-station/test/k1PreviewFrames.test.mjs b/apps/control-station/test/k1PreviewFrames.test.mjs index bafd1d17..33ade427 100644 --- a/apps/control-station/test/k1PreviewFrames.test.mjs +++ b/apps/control-station/test/k1PreviewFrames.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; import {execFileSync} from 'node:child_process'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; let server,previewFrames,assertRrd,previewFreshness,previewCamera; before(async()=>{ server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}}); diff --git a/apps/control-station/test/k1SupervisorPresentation.test.mjs b/apps/control-station/test/k1SupervisorPresentation.test.mjs index 3d8b66b6..bdbe20ec 100644 --- a/apps/control-station/test/k1SupervisorPresentation.test.mjs +++ b/apps/control-station/test/k1SupervisorPresentation.test.mjs @@ -4,7 +4,7 @@ import { after, before, test } from "node:test"; import React, { createElement } from "react"; import { renderToStaticMarkup } from "react-dom/server"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let normalizeXgridsK1MissionState; diff --git a/apps/control-station/test/labViewProfile.test.mjs b/apps/control-station/test/labViewProfile.test.mjs index 250c2be4..ec3c1854 100644 --- a/apps/control-station/test/labViewProfile.test.mjs +++ b/apps/control-station/test/labViewProfile.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server, fetchLabViewProfile, saveLabViewProfile, normalizeLabSceneSettings; diff --git a/apps/control-station/test/laboratoryEvidenceReport.test.mjs b/apps/control-station/test/laboratoryEvidenceReport.test.mjs index dda1cd6f..a402c59a 100644 --- a/apps/control-station/test/laboratoryEvidenceReport.test.mjs +++ b/apps/control-station/test/laboratoryEvidenceReport.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; import { readFile } from "node:fs/promises"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchLaboratoryValueReviewIndex; diff --git a/apps/control-station/test/laboratoryRecordedEvidenceProfile.test.mjs b/apps/control-station/test/laboratoryRecordedEvidenceProfile.test.mjs index e7dc1bb0..66b9fbcb 100644 --- a/apps/control-station/test/laboratoryRecordedEvidenceProfile.test.mjs +++ b/apps/control-station/test/laboratoryRecordedEvidenceProfile.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let laboratoryRecordedEvidenceDemand; diff --git a/apps/control-station/test/lidarReplayQuality.test.mjs b/apps/control-station/test/lidarReplayQuality.test.mjs index 4d17131e..b45ac53d 100644 --- a/apps/control-station/test/lidarReplayQuality.test.mjs +++ b/apps/control-station/test/lidarReplayQuality.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseLidarReplayCatalog; diff --git a/apps/control-station/test/liveReceiverWatchdog.test.mjs b/apps/control-station/test/liveReceiverWatchdog.test.mjs index eb0756ec..3e2c275e 100644 --- a/apps/control-station/test/liveReceiverWatchdog.test.mjs +++ b/apps/control-station/test/liveReceiverWatchdog.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let advanceLiveReceiverOpenWatchdog; diff --git a/apps/control-station/test/liveViewerDiagnostics.test.mjs b/apps/control-station/test/liveViewerDiagnostics.test.mjs index 7c56a2a6..c566f982 100644 --- a/apps/control-station/test/liveViewerDiagnostics.test.mjs +++ b/apps/control-station/test/liveViewerDiagnostics.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let createLiveViewerDiagnosticLifecycle; let createAbortFencedBuildVerifier; diff --git a/apps/control-station/test/localSurface.test.mjs b/apps/control-station/test/localSurface.test.mjs index 4cf9da34..386ddb6a 100644 --- a/apps/control-station/test/localSurface.test.mjs +++ b/apps/control-station/test/localSurface.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let parseLidarLocalSurfaceCatalog; diff --git a/apps/control-station/test/m47ReferenceGraph.test.mjs b/apps/control-station/test/m47ReferenceGraph.test.mjs index cbf3fcb7..b90735a0 100644 --- a/apps/control-station/test/m47ReferenceGraph.test.mjs +++ b/apps/control-station/test/m47ReferenceGraph.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchM47ReferenceGraphLab; diff --git a/apps/control-station/test/m48ObjectCentricQuality.test.mjs b/apps/control-station/test/m48ObjectCentricQuality.test.mjs index e9216885..869156f4 100644 --- a/apps/control-station/test/m48ObjectCentricQuality.test.mjs +++ b/apps/control-station/test/m48ObjectCentricQuality.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFileSync, readdirSync } from "node:fs"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let decodeM48GateStatus; diff --git a/apps/control-station/test/m48SmallStaticRegression.test.mjs b/apps/control-station/test/m48SmallStaticRegression.test.mjs index 5e1a596e..9a15f443 100644 --- a/apps/control-station/test/m48SmallStaticRegression.test.mjs +++ b/apps/control-station/test/m48SmallStaticRegression.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { existsSync, readFileSync } from "node:fs"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchM48SmallStaticRegression; diff --git a/apps/control-station/test/m48sFixedClassDetector.test.mjs b/apps/control-station/test/m48sFixedClassDetector.test.mjs index 9983ec18..53e7f6f3 100644 --- a/apps/control-station/test/m48sFixedClassDetector.test.mjs +++ b/apps/control-station/test/m48sFixedClassDetector.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchM48SFixedClassDetectorResult; diff --git a/apps/control-station/test/m48tRiskQuality.test.mjs b/apps/control-station/test/m48tRiskQuality.test.mjs index 44ca4848..5e588db5 100644 --- a/apps/control-station/test/m48tRiskQuality.test.mjs +++ b/apps/control-station/test/m48tRiskQuality.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; import { readFile } from "node:fs/promises"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchM48TRiskQualityResult; diff --git a/apps/control-station/test/m49PhysicalSafetyPlayback.test.mjs b/apps/control-station/test/m49PhysicalSafetyPlayback.test.mjs index cb49d744..60cd9061 100644 --- a/apps/control-station/test/m49PhysicalSafetyPlayback.test.mjs +++ b/apps/control-station/test/m49PhysicalSafetyPlayback.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let M49PhysicalSafetyPlaybackBuffer; diff --git a/apps/control-station/test/m49TgsFullShadow.test.mjs b/apps/control-station/test/m49TgsFullShadow.test.mjs index b95d4526..adc5fa06 100644 --- a/apps/control-station/test/m49TgsFullShadow.test.mjs +++ b/apps/control-station/test/m49TgsFullShadow.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchM49TgsFullShadowSpatialChunk; diff --git a/apps/control-station/test/m4ReplayThreat.test.mjs b/apps/control-station/test/m4ReplayThreat.test.mjs index d27e302e..19b96d27 100644 --- a/apps/control-station/test/m4ReplayThreat.test.mjs +++ b/apps/control-station/test/m4ReplayThreat.test.mjs @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchM4ThreatReplayResult; diff --git a/apps/control-station/test/missionPlanner.test.mjs b/apps/control-station/test/missionPlanner.test.mjs index 61685dfa..4ff4dc59 100644 --- a/apps/control-station/test/missionPlanner.test.mjs +++ b/apps/control-station/test/missionPlanner.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { before, after, test } from 'node:test'; -import { createServer } from 'vite'; +import { createServer } from './support/vite-server.mjs'; let server, api; before(async () => { server = await createServer({ appType: 'custom', logLevel: 'silent', server: { middlewareMode: true } }); api = await server.ssrLoadModule('/src/core/missions/planner.ts'); }); after(async () => { await server?.close(); }); diff --git a/apps/control-station/test/networkProvisioning.test.mjs b/apps/control-station/test/networkProvisioning.test.mjs index ed483294..c5678049 100644 --- a/apps/control-station/test/networkProvisioning.test.mjs +++ b/apps/control-station/test/networkProvisioning.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { before, after, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let observeProvisioningRequest; diff --git a/apps/control-station/test/observationSessions.test.mjs b/apps/control-station/test/observationSessions.test.mjs index ca422680..60d96439 100644 --- a/apps/control-station/test/observationSessions.test.mjs +++ b/apps/control-station/test/observationSessions.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let decodeObservationSessionCatalog; diff --git a/apps/control-station/test/observationSources.test.mjs b/apps/control-station/test/observationSources.test.mjs index 4b521ede..5a439e7b 100644 --- a/apps/control-station/test/observationSources.test.mjs +++ b/apps/control-station/test/observationSources.test.mjs @@ -4,7 +4,7 @@ import { after, before, test } from "node:test"; import { createElement } from "react"; import { renderToStaticMarkup } from "react-dom/server"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let xgridsK1Manifest; diff --git a/apps/control-station/test/observatoryCatalog.test.mjs b/apps/control-station/test/observatoryCatalog.test.mjs index 225919ac..6113830d 100644 --- a/apps/control-station/test/observatoryCatalog.test.mjs +++ b/apps/control-station/test/observatoryCatalog.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let applyObservatoryCatalogMutationOverlay; diff --git a/apps/control-station/test/observatoryCatalogMutations.test.mjs b/apps/control-station/test/observatoryCatalogMutations.test.mjs index 9c67628a..54e50768 100644 --- a/apps/control-station/test/observatoryCatalogMutations.test.mjs +++ b/apps/control-station/test/observatoryCatalogMutations.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let deleteObservatoryLabProjection; diff --git a/apps/control-station/test/observatoryHooks.test.mjs b/apps/control-station/test/observatoryHooks.test.mjs index cdbf6279..f6032c7c 100644 --- a/apps/control-station/test/observatoryHooks.test.mjs +++ b/apps/control-station/test/observatoryHooks.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import React from "react"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let useObservatoryRecordedJobs; diff --git a/apps/control-station/test/observatoryLaboratorySetups.test.mjs b/apps/control-station/test/observatoryLaboratorySetups.test.mjs index 48b9c8f1..34c784de 100644 --- a/apps/control-station/test/observatoryLaboratorySetups.test.mjs +++ b/apps/control-station/test/observatoryLaboratorySetups.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchObservatoryLaboratorySetups; diff --git a/apps/control-station/test/observatoryRecordedJobs.test.mjs b/apps/control-station/test/observatoryRecordedJobs.test.mjs index f241ce54..74cd2f67 100644 --- a/apps/control-station/test/observatoryRecordedJobs.test.mjs +++ b/apps/control-station/test/observatoryRecordedJobs.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchObservatoryRecordedJobs; diff --git a/apps/control-station/test/observatoryRecordedProgress.test.mjs b/apps/control-station/test/observatoryRecordedProgress.test.mjs index e48e4e17..699311a2 100644 --- a/apps/control-station/test/observatoryRecordedProgress.test.mjs +++ b/apps/control-station/test/observatoryRecordedProgress.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let decode; diff --git a/apps/control-station/test/observatoryRecordedRun.test.mjs b/apps/control-station/test/observatoryRecordedRun.test.mjs index 173d4a29..b8313a94 100644 --- a/apps/control-station/test/observatoryRecordedRun.test.mjs +++ b/apps/control-station/test/observatoryRecordedRun.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let admitObservatoryRecordedRunReview; diff --git a/apps/control-station/test/observatoryWorkspace.test.mjs b/apps/control-station/test/observatoryWorkspace.test.mjs index ab8087cc..806995f5 100644 --- a/apps/control-station/test/observatoryWorkspace.test.mjs +++ b/apps/control-station/test/observatoryWorkspace.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let productModel; diff --git a/apps/control-station/test/perceptionPreparation.test.mjs b/apps/control-station/test/perceptionPreparation.test.mjs index c7c7736f..7794c1ed 100644 --- a/apps/control-station/test/perceptionPreparation.test.mjs +++ b/apps/control-station/test/perceptionPreparation.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchPerceptionPreparationStatus; diff --git a/apps/control-station/test/planningPresentationTelemetry.test.mjs b/apps/control-station/test/planningPresentationTelemetry.test.mjs index 0e510c21..b62434a2 100644 --- a/apps/control-station/test/planningPresentationTelemetry.test.mjs +++ b/apps/control-station/test/planningPresentationTelemetry.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; let server,createReporter; before(async()=>{ diff --git a/apps/control-station/test/planningProjectDeletion.test.mjs b/apps/control-station/test/planningProjectDeletion.test.mjs index 4df5cfba..3008b129 100644 --- a/apps/control-station/test/planningProjectDeletion.test.mjs +++ b/apps/control-station/test/planningProjectDeletion.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import { before, after, test } from 'node:test'; import { readFile } from 'node:fs/promises'; -import { createServer } from 'vite'; +import { createServer } from './support/vite-server.mjs'; let server, api; before(async () => { server = await createServer({appType: 'custom', logLevel: 'silent', server: {middlewareMode: true}}); diff --git a/apps/control-station/test/planningSceneStream.test.mjs b/apps/control-station/test/planningSceneStream.test.mjs index c6ac50fe..0d7a550f 100644 --- a/apps/control-station/test/planningSceneStream.test.mjs +++ b/apps/control-station/test/planningSceneStream.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; import {readFileSync} from 'node:fs'; let server,start; before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});({startPlanningSceneStream:start}=await server.ssrLoadModule('/src/core/missions/planningSceneStream.ts'));}); diff --git a/apps/control-station/test/planningSceneTools.test.mjs b/apps/control-station/test/planningSceneTools.test.mjs index e1104c06..fdb19548 100644 --- a/apps/control-station/test/planningSceneTools.test.mjs +++ b/apps/control-station/test/planningSceneTools.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; import {createElement} from 'react'; import {renderToStaticMarkup} from 'react-dom/server'; import {readFileSync} from 'node:fs'; diff --git a/apps/control-station/test/planningWholeRecording.test.mjs b/apps/control-station/test/planningWholeRecording.test.mjs index ce2fa31a..b1ed9000 100644 --- a/apps/control-station/test/planningWholeRecording.test.mjs +++ b/apps/control-station/test/planningWholeRecording.test.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; import React from 'react'; import {renderToStaticMarkup} from 'react-dom/server'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; import {readFile} from 'node:fs/promises'; let server,usePlanner,Settings; diff --git a/apps/control-station/test/polygonRunArchive.test.mjs b/apps/control-station/test/polygonRunArchive.test.mjs index 9393f456..a580095d 100644 --- a/apps/control-station/test/polygonRunArchive.test.mjs +++ b/apps/control-station/test/polygonRunArchive.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let decodePolygonRunCatalog; diff --git a/apps/control-station/test/productShellContract.test.mjs b/apps/control-station/test/productShellContract.test.mjs index 4f732847..c0d027e6 100644 --- a/apps/control-station/test/productShellContract.test.mjs +++ b/apps/control-station/test/productShellContract.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let productModel; diff --git a/apps/control-station/test/recordedCameraBuffering.test.mjs b/apps/control-station/test/recordedCameraBuffering.test.mjs index a7f91fd0..f150f53d 100644 --- a/apps/control-station/test/recordedCameraBuffering.test.mjs +++ b/apps/control-station/test/recordedCameraBuffering.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchRecordedMediaArchive; diff --git a/apps/control-station/test/recordedRerunCameraJournal.test.mjs b/apps/control-station/test/recordedRerunCameraJournal.test.mjs index b89e4feb..74f52efe 100644 --- a/apps/control-station/test/recordedRerunCameraJournal.test.mjs +++ b/apps/control-station/test/recordedRerunCameraJournal.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server, readNativeRerunCameraEye; before(async () => { diff --git a/apps/control-station/test/recordedSessionAdmission.test.mjs b/apps/control-station/test/recordedSessionAdmission.test.mjs index 66dafbc0..b0856c37 100644 --- a/apps/control-station/test/recordedSessionAdmission.test.mjs +++ b/apps/control-station/test/recordedSessionAdmission.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let admission; diff --git a/apps/control-station/test/recordedViewerResourceLifecycle.test.mjs b/apps/control-station/test/recordedViewerResourceLifecycle.test.mjs index c68a14e0..04a053b5 100644 --- a/apps/control-station/test/recordedViewerResourceLifecycle.test.mjs +++ b/apps/control-station/test/recordedViewerResourceLifecycle.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server, createIsolatedRerunHost, keepRecordedBlueprintSession, createRecordedRerunFacade, createRecordedRerunOwner, relayIsolatedRerunInput; before(async () => { diff --git a/apps/control-station/test/rerunViewportAtomicAdmission.test.mjs b/apps/control-station/test/rerunViewportAtomicAdmission.test.mjs index 7f065cb2..669af6cd 100644 --- a/apps/control-station/test/rerunViewportAtomicAdmission.test.mjs +++ b/apps/control-station/test/rerunViewportAtomicAdmission.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let claimExclusiveLiveViewer; diff --git a/apps/control-station/test/rerunViewportPlayback.test.mjs b/apps/control-station/test/rerunViewportPlayback.test.mjs index 8a3858f3..3d9c32ae 100644 --- a/apps/control-station/test/rerunViewportPlayback.test.mjs +++ b/apps/control-station/test/rerunViewportPlayback.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let attemptRecordedAutoplay; diff --git a/apps/control-station/test/rerunViewportProgressivePlayback.test.mjs b/apps/control-station/test/rerunViewportProgressivePlayback.test.mjs index 6bad59a7..9cda1cc2 100644 --- a/apps/control-station/test/rerunViewportProgressivePlayback.test.mjs +++ b/apps/control-station/test/rerunViewportProgressivePlayback.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let canPublishRecordedPlaybackController; diff --git a/apps/control-station/test/roverConfiguration.test.mjs b/apps/control-station/test/roverConfiguration.test.mjs index 16936599..6357a84a 100644 --- a/apps/control-station/test/roverConfiguration.test.mjs +++ b/apps/control-station/test/roverConfiguration.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; let server,sameConfiguration; before(async()=>{server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}});({sameConfiguration}=await server.ssrLoadModule('/src/core/fleet/configurationEquality.ts'));}); after(async()=>server?.close()); diff --git a/apps/control-station/test/runtimeAcquisitionGuard.test.mjs b/apps/control-station/test/runtimeAcquisitionGuard.test.mjs index a13318ee..374af347 100644 --- a/apps/control-station/test/runtimeAcquisitionGuard.test.mjs +++ b/apps/control-station/test/runtimeAcquisitionGuard.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let guard; diff --git a/apps/control-station/test/runtimeStateOrdering.test.mjs b/apps/control-station/test/runtimeStateOrdering.test.mjs index d65871a8..6ff891c9 100644 --- a/apps/control-station/test/runtimeStateOrdering.test.mjs +++ b/apps/control-station/test/runtimeStateOrdering.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let selectMonotonicXgridsState; diff --git a/apps/control-station/test/sensorEnrollment.test.mjs b/apps/control-station/test/sensorEnrollment.test.mjs index c93e0ab5..b392d971 100644 --- a/apps/control-station/test/sensorEnrollment.test.mjs +++ b/apps/control-station/test/sensorEnrollment.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import {before,after,test} from 'node:test'; import {readFileSync,readdirSync} from 'node:fs'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; let server,api,resolveContribution,wirelessContributions,revealEnrollment; before(async()=>{ server=await createServer({appType:'custom',logLevel:'silent',server:{middlewareMode:true}}); diff --git a/apps/control-station/test/sessionDisplayProfile.test.mjs b/apps/control-station/test/sessionDisplayProfile.test.mjs index 3b6acc0e..8f0a49cf 100644 --- a/apps/control-station/test/sessionDisplayProfile.test.mjs +++ b/apps/control-station/test/sessionDisplayProfile.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import {before, after, test} from 'node:test'; -import {createServer} from 'vite'; +import {createServer} from './support/vite-server.mjs'; import {createElement} from 'react'; import {renderToStaticMarkup} from 'react-dom/server'; import {readFile} from 'node:fs/promises'; diff --git a/apps/control-station/test/sessionOverview.test.mjs b/apps/control-station/test/sessionOverview.test.mjs index 7c446e35..875f0e54 100644 --- a/apps/control-station/test/sessionOverview.test.mjs +++ b/apps/control-station/test/sessionOverview.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { before, after, test } from 'node:test'; -import { createServer } from 'vite'; +import { createServer } from './support/vite-server.mjs'; import { readFile } from 'node:fs/promises'; let server, api; before(async () => { diff --git a/apps/control-station/test/sessionOverviewComparison.test.mjs b/apps/control-station/test/sessionOverviewComparison.test.mjs index 59f44076..a34d26ae 100644 --- a/apps/control-station/test/sessionOverviewComparison.test.mjs +++ b/apps/control-station/test/sessionOverviewComparison.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import { before, after, test } from 'node:test'; -import { createServer } from 'vite'; +import { createServer } from './support/vite-server.mjs'; import { readFile } from 'node:fs/promises'; let server, api; before(async () => { diff --git a/apps/control-station/test/spatialSceneLayout.test.mjs b/apps/control-station/test/spatialSceneLayout.test.mjs index c7707a24..0f4fd788 100644 --- a/apps/control-station/test/spatialSceneLayout.test.mjs +++ b/apps/control-station/test/spatialSceneLayout.test.mjs @@ -3,7 +3,7 @@ import { readFile } from 'node:fs/promises'; import { before, after, test } from 'node:test'; import { createElement } from 'react'; import { renderToStaticMarkup } from 'react-dom/server'; -import { createServer } from 'vite'; +import { createServer } from './support/vite-server.mjs'; let server, SpatialScene; before(async () => { diff --git a/apps/control-station/test/support/README.md b/apps/control-station/test/support/README.md new file mode 100644 index 00000000..af87dcd4 --- /dev/null +++ b/apps/control-station/test/support/README.md @@ -0,0 +1,15 @@ +# SSR unit-test server + +Import `createServer` from `./support/vite-server.mjs` in tests, instead of from Vite. +The helper keeps normal project resolution and plugins, disables browser/SSR +prebundling after plugin configuration, and gives every server its own directory +under the repository `.runtime/frontend-unit-tests`. + +Keep the server alive for the whole test file: create it in `before`, and await +`server?.close()` in the file's existing `after` hook. A server created inside a +test must close in `finally`. Closing twice is safe. The helper cleans its own +cache after close and on initialization failure; it does not register a nested +`after` hook, which could close a file-scoped server before later tests use it. + +`npm run test:unit` executes files sequentially for the operator Mac's memory +budget. Production and development Vite configuration is unchanged. diff --git a/apps/control-station/test/support/vite-server.mjs b/apps/control-station/test/support/vite-server.mjs new file mode 100644 index 00000000..6938513a --- /dev/null +++ b/apps/control-station/test/support/vite-server.mjs @@ -0,0 +1,62 @@ +import { mkdir, mkdtemp, rm } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { createServer as createViteServer } from "vite"; + +export const testCacheRoot = fileURLToPath( + new URL("../../../../.runtime/frontend-unit-tests/", import.meta.url), +); + +// SSR unit tests compile modules; they never need the browser dependency scan. +// Each server owns its scratch directory, including failed initialization. +export async function createServer(options = {}) { + await mkdir(testCacheRoot, { recursive: true }); + const cacheDir = await mkdtemp(`${testCacheRoot}vite-`); + const noDiscovery = { noDiscovery: true, include: [] }; + let server; + try { + server = await createViteServer({ + ...options, + plugins: [ + ...(options.plugins ?? []), + { + name: "mission-core-ssr-unit-test", + configResolved(config) { + // React and other plugins can add includes in their config hooks. + // Disable both client and SSR prebundling after those hooks finish. + for (const environment of Object.values(config.environments)) { + environment.optimizeDeps.noDiscovery = true; + environment.optimizeDeps.include = []; + } + }, + }, + ], + cacheDir, + server: { ...options.server, middlewareMode: true, hmr: false, watch: null }, + optimizeDeps: { ...options.optimizeDeps, ...noDiscovery }, + environments: { + ...options.environments, + client: { + ...options.environments?.client, + optimizeDeps: { ...options.environments?.client?.optimizeDeps, ...noDiscovery }, + }, + ssr: { + ...options.environments?.ssr, + optimizeDeps: { ...options.environments?.ssr?.optimizeDeps, ...noDiscovery }, + }, + }, + }); + } catch (error) { + await rm(cacheDir, { recursive: true, force: true }); + throw error; + } + const close = server.close.bind(server); + let closing; + server.close = () => closing ??= (async () => { + try { + await close(); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } + })(); + return server; +} diff --git a/apps/control-station/test/vegetationShadow.test.mjs b/apps/control-station/test/vegetationShadow.test.mjs index 77e0e278..da378722 100644 --- a/apps/control-station/test/vegetationShadow.test.mjs +++ b/apps/control-station/test/vegetationShadow.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { access, readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let fetchVegetationBenchmarkResult; diff --git a/apps/control-station/test/viewerProfile.test.mjs b/apps/control-station/test/viewerProfile.test.mjs index 17a4ea19..3d8055d3 100644 --- a/apps/control-station/test/viewerProfile.test.mjs +++ b/apps/control-station/test/viewerProfile.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let LABORATORY_RECORDED_EVIDENCE_VIEWER_PROFILE; diff --git a/apps/control-station/test/viewerSettingsCommit.test.mjs b/apps/control-station/test/viewerSettingsCommit.test.mjs index 0972c612..c9284b55 100644 --- a/apps/control-station/test/viewerSettingsCommit.test.mjs +++ b/apps/control-station/test/viewerSettingsCommit.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let createLatestAsyncCommitter; diff --git a/apps/control-station/test/viewerSettingsTarget.test.mjs b/apps/control-station/test/viewerSettingsTarget.test.mjs index 88c780cc..cfc2642d 100644 --- a/apps/control-station/test/viewerSettingsTarget.test.mjs +++ b/apps/control-station/test/viewerSettingsTarget.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let viewerSettingsTargetIdentity; diff --git a/apps/control-station/test/viteServerLifecycle.test.mjs b/apps/control-station/test/viteServerLifecycle.test.mjs new file mode 100644 index 00000000..f263a8e4 --- /dev/null +++ b/apps/control-station/test/viteServerLifecycle.test.mjs @@ -0,0 +1,47 @@ +import assert from "node:assert/strict"; +import { access, readdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { test } from "node:test"; +import { createServer, testCacheRoot } from "./support/vite-server.mjs"; + +async function absent(path) { + await assert.rejects(access(path), { code: "ENOENT" }); +} + +test("SSR servers load real modules without dependency bundles and remove only their own cache", async () => { + assert.equal(testCacheRoot, fileURLToPath(new URL("../../../.runtime/frontend-unit-tests/", import.meta.url))); + const first = await createServer({ logLevel: "silent" }); + const second = await createServer({ configFile: false, logLevel: "silent" }); + try { + assert.notEqual(first.config.cacheDir, second.config.cacheDir); + for (const server of [first, second]) { + for (const name of ["client", "ssr"]) { + assert.equal(server.environments[name].config.optimizeDeps.noDiscovery, true); + assert.deepEqual(server.environments[name].config.optimizeDeps.include, []); + } + const loaded = await server.ssrLoadModule("/src/core/simulation/urbanMap.ts"); + assert.equal(typeof loaded.loadUrbanMap, "function"); + assert.deepEqual(await readdir(server.config.cacheDir), []); + } + const survivor = join(second.config.cacheDir, "owned-marker"); + await writeFile(survivor, "keep"); + await Promise.all([first.close(), first.close()]); + await absent(first.config.cacheDir); + await access(survivor); + } finally { + await first.close(); + await second.close(); + } + await absent(second.config.cacheDir); +}); + +test("failed Vite configuration removes its scratch directory", async () => { + const before = (await readdir(testCacheRoot)).sort(); + await assert.rejects(createServer({ + configFile: false, + logLevel: "silent", + plugins: [{ name: "intentional-startup-failure", config() { throw new Error("expected startup failure"); } }], + }), /expected startup failure/); + assert.deepEqual((await readdir(testCacheRoot)).sort(), before); +}); diff --git a/apps/control-station/test/workspaceLayout.test.mjs b/apps/control-station/test/workspaceLayout.test.mjs index 99f0beea..4a649da7 100644 --- a/apps/control-station/test/workspaceLayout.test.mjs +++ b/apps/control-station/test/workspaceLayout.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { readFile } from "node:fs/promises"; import { after, before, test } from "node:test"; -import { createServer } from "vite"; +import { createServer } from "./support/vite-server.mjs"; let server; let decodeObservationWorkspaceLayoutProfile; diff --git a/docs/03_ARTIFACT_POLICY.md b/docs/03_ARTIFACT_POLICY.md index 01dba9fc..be4f2ca9 100644 --- a/docs/03_ARTIFACT_POLICY.md +++ b/docs/03_ARTIFACT_POLICY.md @@ -58,3 +58,9 @@ provisioner should use a hidden prompt, stdin/file descriptor with strict permissions, or macOS Keychain. Logs and manifests record only that a credential was supplied, never its value or unredacted payload bytes. + +## Storage lifecycle + +See [Storage retention](STORAGE_RETENTION.md) for executable intermediate-build +retention, release/rollback pins, active build ownership, protected evidence, +cache boundaries and interrupted-cleanup recovery. diff --git a/docs/STORAGE_RETENTION.md b/docs/STORAGE_RETENTION.md new file mode 100644 index 00000000..96d3889a --- /dev/null +++ b/docs/STORAGE_RETENTION.md @@ -0,0 +1,269 @@ +# Mission Core storage lifecycle + +Policy revision: `operator-storage-v2` (2026-10-16). +Build-input policy remains `two-closed-inputs-per-line-v1`. +This implements the storage boundaries in `AGENTS.md` and supplements +[the artifact policy](03_ARTIFACT_POLICY.md). It applies only to the canonical +operator checkout; other repositories, boards, Worker 006 and Docker storage +are separate owners. No system-wide prune or periodic deletion timer is installed. Cache budgets +run at publication; service journal rotation runs in the owning writer. + +## Classes and enforcement + +| Data | Retention and mechanism | +| --- | --- | +| Source, configuration, secrets, `.git`, installed dependencies and active UI | Not disposable storage. No generic age-based cleanup. | +| Imported Gaussian worlds, recordings, evidence, missions, plans, accepted maps, session map versions | Durable application data. No TTL. Deletion belongs to the owning product workflow or an explicitly reviewed archive/removal operation. | +| Simulation qualifications, computation experiments/results, engineering materials | Preserve unique evidence and the exact input/configuration/result relationship. An old experiment is not a cache. Archive only with a verified destination and complete dependency inventory. | +| Qualified releases and rollback artifacts | Explicit pins; retain independently of the intermediate count. Retiring a release requires removing its pin by name and recording the reason. | +| Intermediate Linux build inputs | Keep two most recently **published, completed, unpinned** inputs per line, plus every transitive base of retained inputs. Lines are `node/node-only`, `node/node-core`, `x4/native`, `x4/package`, `x4/owner`. Enforced by `scripts/packaging/build_retention.py`. | +| Active/disconnected builds, transfers and qualifications | Persistent active hold, with owner token. No automatic expiry. Explicit terminal outcome releases the hold. Eight unfinished inputs per archive family block the next publication. Node profiles share this conservative unfinished limit. | +| Old or unknown inputs | Protected as `legacy-unreviewed`; importing into the registry requires a named protective pin. Neither mtime nor lack of a reference proves that a legacy file is disposable. | +| General artifact gateway cache | Existing LRU/pin implementation: default 8 GiB local quota and 2 GiB free-space reserve; pinned objects survive eviction. Configuration may override these defaults. Not handled by build retention. | +| Portable replay, integrated/canonical LAB overlays, editor scene assets | Existing generations are protected. New publication has a per-owner quota and a 2 GiB free-space reserve; no automatic eviction or TTL. Cache hits and sealed recovery remain available at quota. See the limits below. | +| Worker source CAS and sealed modular-node results | Separate Worker/result ownership. No new deletion or expiry; a source/result can be unique or required by a retained job. Existing source admission/free-space checks remain. | +| Vite unit-test cache | Each server owns a unique `.runtime/frontend-unit-tests` directory and removes it on close or failed creation. Existing test helper enforces this; tests run sequentially. Abandoned crash files need a separate verified cleanup. | +| Python check caches | `scripts/check_python.py pytest/ruff/mypy` creates one owned `.runtime/python-checks` temporary directory, disables persistent pytest/Ruff caches and redirects mypy there. Stop owned helper processes before cleanup, including failed checks. Four active/unreconciled check directories or a 512 MiB admission budget block the next check; 64 MiB of headroom is required before admission. Existing/foreign crash residue is preserved. Direct ad-hoc tool invocation is outside this managed entry point. | +| Compiler caches and other task scratch | Disposable only with no active owner. Node Linux build jobs already place Go/npm state inside their owned build folder; remote staging is a separate lifecycle. Never purge shared toolchains, downloaded offline dependencies or another job’s directory. | +| Operator monitoring | Live-only RAM: one latest snapshot per node, maximum 32 nodes, 192 KiB snapshot plus 32 KiB duplicate-comparison sample per node; 30-second expiry, one-second idle sweep and UTC daily reset. No local history database. UI/API use current observations only. Retire an obsolete replica only after live-mode acceptance with the scoped plan/apply tool; see [operator monitoring](OPERATOR_MONITORING.md). | +| Routine service logs | Core, Observatory/Gaussian worker tunnels, telemetry startup/tunnel and Map Gateway link use `rotating_process`: 8 MiB × (current + 4 backups), at most 40 MiB per service. Legacy journals remain intact and stop growing after migration. Scanner diagnostics use 5 MiB + 5 backups with 16 KiB records and private files after rotation. Existing Docker logs remain `local`, 5 MiB × 2 per container. Experiment/build/mission calculation logs remain evidence and are excluded. | + +A 6 GiB build-input soft budget is reported, not used to override pins. A +producer checks the uncompressed estimated payload plus ZIP overhead and leaves +at least 2 GiB free before staging. Existing Linux/qualification-specific space +checks still apply. If protected data consumes the budget, report it and stop +creating more inputs when the free-space guard fails; do not delete evidence. +The two-input rule is a count policy, not a promise of a total storage ceiling. + +## Build lifecycle + +The four generators (Node Linux, X4 native, X4 package, X4 owner wrapper) publish +through the same local helper. They write a uniquely owned temporary file, +validate manifest identity and base hashes, then publish without replacing an +existing path and persist the active hold. Their existing JSON response adds: + +```json +{"retention": {"path": "apps/node-agent/build/mission-core-node-linux-build-.pyz", "owner": "", "state": "active"}} +``` + +A failed writer removes only its own temporary file. A crash after publication +but before registry commit leaves a protected unknown input. The helper is +operator packaging code, not a new board/runtime dependency. Production inputs +are not rebuilt just to exercise retention. + +After the remote job and every dependent transfer/qualification actually end, +the owning engineer/agent must close the hold using the returned path and owner: + +```sh +.venv/bin/python scripts/packaging/build_retention.py finish "$input" \ + --owner "$owner" --outcome intermediate --reason "Build and transfer completed; no retained release uses this input" \ + > .runtime/build-retention/review-plan.json +``` + +Choose `failed` or `cancelled` only after the job has stopped. These inputs join +the two-input history; failure does not silently delete diagnostic evidence. +Choose `qualified` or `rollback` to close the active hold **and** add the named +permanent pin. Add another named pin before a later qualification/release starts +using an already completed input. Do not close someone else's active build. +A disconnected job remains active until terminal state is established. + +Review the returned plan (or generate a fresh one) and apply it as the final +build-storage step; this is part of build completion, not a user-facing manual +maintenance ritual. `finish` itself never deletes bytes. + +```sh +.venv/bin/python scripts/packaging/build_retention.py plan \ + > .runtime/build-retention/review-plan.json +.venv/bin/python scripts/packaging/build_retention.py apply \ + --plan .runtime/build-retention/review-plan.json +``` + +On a never-initialized checkout, `plan` is read-only and does not create the +control directory; save its output to an existing task-owned directory instead. +An older plan is refused if a file, lifecycle state or pin changes. Review and +regenerate it. Do not edit the plan to force deletion. A malformed package, +missing/changed base, unexplained missing registered input, or unsafe path blocks +**all** deletions in that operation. + +Explicit legacy enrollment and release pinning: + +```sh +.venv/bin/python scripts/packaging/build_retention.py adopt "$input" \ + --pin legacy-review --reason "Retained provenance; exact evidence record path" +.venv/bin/python scripts/packaging/build_retention.py pin "$input" \ + --pin release-0.1.3 --reason "Qualified release and its evidence record" +.venv/bin/python scripts/packaging/build_retention.py unpin "$input" \ + --pin legacy-review --reason "Reviewed as superseded intermediate; no release or rollback depends on it" +``` + +`unpin` is an explicit decision, not an automatic inference from time or a failed +build log. All unknown inputs remain protected even without registry enrollment. + +## Integrity, interruption and audit + +Only exact build-input filenames directly under `apps/node-agent/build` and +`plugins/insta360-x4/build` are eligible. Installers, `.deb` releases, qualified +subdirectories, rollback copies and runtime data are outside the allowlist. +Symlinks and traversal paths are refused. Publications and maintenance share an +OS file lock; generators cannot race an applied plan. External tools must use +the same helper rather than mutating managed inputs in place. + +The plan verifies full archive hashes, manifest IDs, profiles and dependency +closure. Apply independently recomputes the plan under lock and checks each file +again before unlink. Dependants are removed before their bases, so an interrupted +operation does not strand a retained delta. Every unlink is journaled under +`.runtime/build-retention/receipts`, including the planned identity, actual removed +paths, status and free-space observations. There is no recursive directory delete. + +An interrupted apply can be reconciled using the receipt basename: + +```sh +.venv/bin/python scripts/packaging/build_retention.py recover "$receipt_basename" +``` + +Recovery only reconciles already journaled missing files; it performs no deletion. +After reviewing the receipt, create a new plan for the remaining files. Receipts +and lifecycle records are small engineering evidence, not raw telemetry; preserve +them. A crash before an unlink is distinguishable from one after it by the file's +presence and verified identity. + +`candidate_bytes_upper_bound` is logical file size, **not** promised reclaimed +space: hardlinks/APFS clones can share blocks. Receipts report filesystem free +space before/after; concurrent system activity can affect that delta. + +## Acceptance + +`tests/test_build_retention.py` covers separate lines, transitive bases, release +and rollback pins, legacy protection, active owners and restart, stale/edited +plans, unsafe paths, hash changes, publication failure, missing bases, capacity +refusal, concurrent publication, partial deletion, crash recovery and hardlinks. +It also executes all four real producer wrappers with tiny synthetic input +fixtures. Existing delta reuse and artifact-cache tests remain applicable. + +The initial live adoption preserves reviewed historical inputs and leaves new +unreviewed inputs protected. No old source bundle is declared disposable merely +because this policy has been installed. + + +## Local derived-cache budgets + +`src/k1link/cache_budget.py` provides one admission/publication lock across local +processes, a full logical-byte inventory and a 2 GiB free-space reserve. Unknown +files, existing generations, partial outputs and sidecars count against capacity. +Symlink/special-file inventories are refused, never followed or deleted. Up to +10,000 files are admitted by default (4,096 for editor assets). Quotas are +conservative logical sizes; hardlinks/APFS clones do not authorize deletion. + +| Cache owner | Publication quota | At capacity | +| --- | ---: | --- | +| Exact camera JPEG frames | 256 MiB | Return the validated decoded frame without a new disk copy; retained frames still work. | +| LiDAR validation proofs | 16 MiB | Validate the original normally; skip the optional proof write. | +| Prepared camera media sidecars | 64 MiB | Use the validated manifest in memory; skip the optional sidecar write. | +| Perception overlays | 1 GiB | Refuse a new cached generation; retain existing generations. | +| Calibrated fusion overlays | 1 GiB | Same. | +| Integrated perception overlays | 4 GiB | Same; reconstruct admission in memory if its optional sidecar cannot fit, so an existing sealed overlay remains usable. | +| Canonical LAB overlays + replay | 4 GiB combined | Reuse existing admitted output; refuse new publication when insufficient room. | +| Portable replay + camera proxies | 4 GiB combined | Same. | +| Editor scene assets | 4 GiB | Account for all declared, unfinished transfers before accepting a new manifest or chunk. Do not discard partial uploads or ready assets. | + +Larger renderers check room before work and again under the publication lock. +The final check counts staged bytes already on disk, plus sidecar headroom. This +bounds accumulated published copies; it is **not an OS filesystem quota** or a +promise that transient renderer scratch never exceeds the publication budget. +Existing bounded renderer inputs/outputs/timeouts and `finally` cleanup still +apply. Crash residue is counted and protected, so it can stop further admission; +its owner must be investigated before removal. No broad crash-directory sweep +is enabled. A quota cannot both preserve arbitrary unique data and allow +unlimited new copies; capacity refusal is intentional and explicit. + +General artifact/recording caches retain their established LRU/pin contracts. +No new automatic removal is applied to simulation worlds, source media, plans, +accepted geometry, qualifications, results, offline dependencies or rollback. +The earlier Vite SSR helper still owns/cleans each test cache and disables +unnecessary dependency prebundling. Ordinary development sessions and external +user commands are not silently enrolled into a global cleanup job. + +## Bounded service journals and migration + +`src/k1link/rotating_process.py` supervises the exact existing command and drains +merged stdout/stderr through a bounded binary writer. Rotation splits even a +large single write, retains current + four backups and holds an exclusive lock. +It does not copy/truncate a file concurrently written by a service. Binary bytes +are preserved within the retention window. Signals reach the child; launchd +continues to own the whole process group. If disk writes fail, the pipe is still +drained with a bounded loss counter so logging cannot deadlock Core. A recovery +marker reports dropped bytes when writing becomes possible again. + +The outer `uv run --no-sync --project` uses the existing Mac execution boundary; +no packages are synchronized. Its pre-Python bootstrap stdout/stderr goes to +`/dev/null`; bootstrap failure is diagnosed through launchd exit status and the +hash-gated rollback check. Child output, including Python exceptions, goes to +`*.managed.log`. No credentials, SSH arguments, routes or Docker settings change. + +The original command/environment/scheduling fields are preserved by +`scripts/manage_runtime_log_policy.py`. Apply requires an exact current plan, +saves the original plist under `.runtime/storage-maintenance/log-policy`, reloads +one existing service and verifies Core health or stable helper state. Failed +acceptance restores the exact previous declaration and checks it. Plans and +receipts contain hashes and service metadata, never environment secrets. + +```sh +.venv/bin/python scripts/manage_runtime_log_policy.py plan core > .runtime/core-log-plan.json +.venv/bin/python scripts/manage_runtime_log_policy.py apply core --plan .runtime/core-log-plan.json +``` + +Other explicit owners: `observatory`, `gaussian`, `telemetry-startup`, +`telemetry-tunnel`, `map`. Existing journals are left byte-for-byte intact as a +one-time legacy baseline; they are not added to the rotating set or compressed +in place. Existing launch-agent generators emit the bounded writer declaration, +so a subsequent normal update does not restore unbounded output. A fresh plan +after installation is unchanged. No new long-running service besides each +existing service's output supervisor is introduced. + +## Cache/log acceptance + +Tests cover exact quotas, free-space reserve, protected unknown files, concurrent +publication, unfinished editor reservations, optional camera-cache fallback, +sealed-overlay recovery at capacity, bounded binary rotation across restart, +exclusive writers, linked-path rejection, child exit/signal handling, private +rotated diagnostics, stale migration refusal and exact rollback on failed health. +The Python-check wrapper is tested on successful and failed child exits while +preserving another job's directory. Live acceptance separately verifies all +six declarations, Core/API/catalog health, unchanged existing-cache hashes and +zero owned test-cache residue. No high-volume live log or renderer load test is +run on the operator Mac. + + +## Simulation experiment closeout — owner amendment 2026-10-19 + +The owner explicitly authorized retiring historical engineering frames, render +arrays and simulation trial traces after detailed textual preservation. This +supplements the evidence rule above; it does not remove protection from product +state, input worlds, working source, offline dependencies, releases or rollback. + +For future engineering-owned simulation/infrastructure trials, closeout is part +of completing the experiment, not a later request for the owner to free disk: + +1. Before capture/export, declare the exact owned temporary directory, expected + bytes and a finite capture limit. Check free space and reuse identical + source/observations by identity instead of exporting another complete copy. +2. Once all writers/remote owners are confirmed terminal, write the hypothesis, + inputs/configuration/source identities, observed result, quality/time, + failures and next decision. Preserve regression evidence and the small set + of images referenced by the final report. A failed experiment also closes. +3. Store exact textual material once per content hash; preserve the original + path-to-hash index. Verify the archive by reading it before deleting originals. +4. Review the exact file-level list, exclude sources/product data/releases and + active or unknown owners, then unlink only unchanged disposable files. + Journal removals and available space. No recursive age-based sweep. +5. Link the archive from the report and relevant Ops card. State explicitly + which original media is gone and requires rendering or running again. + +The 2026-10-19 operation is recorded in +`outputs/SIMULATION_EXPERIMENT_ARCHIVE_2026-10-19/README.md`, its plan, SHA-256 +inventory, archive verification and deletion receipt. Its helper is a one-shot +reviewed operation, not a scheduled garbage collector. Ad-hoc engineering +scripts have no universal disk quota: they must implement the declared capture +bound and perform closeout. Existing cache quotas and service-log rotation keep +their separate writer-owned enforcement. This amendment does not claim that a +filesystem-wide automatic limit or remote Worker cleanup has been installed. diff --git a/scripts/check_python.py b/scripts/check_python.py new file mode 100644 index 00000000..85f37328 --- /dev/null +++ b/scripts/check_python.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Run a local Python check with disposable job-owned caches. + +Only this invocation's scratch is removed, after its process group has ended. +Existing caches, source, dependencies and results are outside this lifecycle. +""" + +import argparse +import os +import signal +import subprocess +import tempfile +import time +from contextlib import suppress +from pathlib import Path + +from k1link.cache_budget import cache_publication + + +def stop_group(process): + try: + os.killpg(process.pid, signal.SIGTERM) + except ProcessLookupError: + return + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + process.poll() + try: + os.killpg(process.pid, 0) + except ProcessLookupError: + return + time.sleep(0.05) + with suppress(ProcessLookupError): + os.killpg(process.pid, signal.SIGKILL) + process.wait(timeout=5) + + +def run(tool, arguments, *, root=None): + root = root or Path(__file__).resolve().parents[1] + parent = root / ".runtime/python-checks" + ancestor = parent + while not ancestor.exists(): + ancestor = ancestor.parent + if ancestor.resolve() != ancestor: + raise ValueError("Check scratch ancestor must be canonical") + parent.mkdir(parents=True, exist_ok=True, mode=0o700) + if parent.resolve() != parent: + raise ValueError("Check scratch must be canonical") + with cache_publication(parent, 64 * 1024**2, limit=512 * 1024**2, max_files=50000): + if sum(p.is_dir() for p in parent.iterdir()) >= 4: + raise ValueError("Four active or unreconciled check directories; new check refused") + owned = tempfile.TemporaryDirectory(prefix=tool + "-", dir=parent) + with owned as scratch: + env = dict( + os.environ, + PYTHONDONTWRITEBYTECODE="1", + RUFF_NO_CACHE="true", + MYPY_CACHE_DIR=str(Path(scratch) / "mypy"), + TMPDIR=scratch, + ) + command = [str(root / ".venv/bin/python"), "-m", tool] + if tool == "pytest": + command += ["-p", "no:cacheprovider", "--basetemp", str(Path(scratch) / "pytest")] + if tool == "ruff": + command += ["check", "--no-cache"] + process = subprocess.Popen( + [*command, *arguments], cwd=root, env=env, start_new_session=True + ) + try: + return process.wait() + finally: + stop_group(process) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("tool", choices=["pytest", "mypy", "ruff"]) + parser.add_argument("arguments", nargs=argparse.REMAINDER) + args = parser.parse_args() + return run(args.tool, args.arguments) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/manage_map_gateway_link.py b/scripts/manage_map_gateway_link.py index 4a0db646..fdf1c51c 100644 --- a/scripts/manage_map_gateway_link.py +++ b/scripts/manage_map_gateway_link.py @@ -4,6 +4,7 @@ No remote command, NAS configuration, provider credential or cache is changed. The user LaunchAgent reconnects independently of the Core process. """ + from __future__ import annotations import argparse @@ -19,6 +20,8 @@ import tempfile import time from pathlib import Path +from k1link.launchd_logs import bounded_launchd_output + LABEL = "com.nodedc.mission-core.map-gateway-link" PORT = 18103 @@ -26,21 +29,47 @@ PORT = 18103 def payload(target: str, runtime: Path) -> bytes: if not re.fullmatch(r"[a-zA-Z0-9_][a-zA-Z0-9_.-]*@[a-zA-Z0-9][a-zA-Z0-9.-]*", target): raise ValueError("SSH target must be an explicit user@host") - return plistlib.dumps({ - "Label": LABEL, - "ProgramArguments": [ - "/usr/bin/ssh", "-N", "-T", "-o", "BatchMode=yes", - "-o", "StrictHostKeyChecking=yes", "-o", "ExitOnForwardFailure=yes", - "-o", "ConnectTimeout=10", "-o", "ServerAliveInterval=15", - "-o", "ServerAliveCountMax=3", "-o", "PermitLocalCommand=no", - "-o", "ForwardAgent=no", "-o", "ForwardX11=no", - "-L", f"127.0.0.1:{PORT}:127.0.0.1:{PORT}", target, - ], - "RunAtLoad": True, "KeepAlive": True, "ThrottleInterval": 30, - "ExitTimeOut": 10, - "StandardOutPath": str(runtime / "stdout.log"), - "StandardErrorPath": str(runtime / "stderr.log"), - }, sort_keys=True) + return plistlib.dumps( + bounded_launchd_output( + { + "Label": LABEL, + "ProgramArguments": [ + "/usr/bin/ssh", + "-N", + "-T", + "-o", + "BatchMode=yes", + "-o", + "StrictHostKeyChecking=yes", + "-o", + "ExitOnForwardFailure=yes", + "-o", + "ConnectTimeout=10", + "-o", + "ServerAliveInterval=15", + "-o", + "ServerAliveCountMax=3", + "-o", + "PermitLocalCommand=no", + "-o", + "ForwardAgent=no", + "-o", + "ForwardX11=no", + "-L", + f"127.0.0.1:{PORT}:127.0.0.1:{PORT}", + target, + ], + "RunAtLoad": True, + "KeepAlive": True, + "ThrottleInterval": 30, + "ExitTimeOut": 10, + "StandardOutPath": str(runtime / "stdout.log"), + "StandardErrorPath": str(runtime / "stderr.log"), + }, + Path(__file__).resolve().parents[1], + ), + sort_keys=True, + ) def digest(value: bytes | None) -> str: @@ -50,9 +79,13 @@ def digest(value: bytes | None) -> str: def health() -> bool: connection = http.client.HTTPConnection("127.0.0.1", PORT, timeout=2) try: - connection.request("GET", "/healthz", headers={ - "x-nodedc-user-id": "mission-core-loopback-operator", - }) + connection.request( + "GET", + "/healthz", + headers={ + "x-nodedc-user-id": "mission-core-loopback-operator", + }, + ) response = connection.getresponse() raw = response.read(65537) if response.status != 200 or len(raw) > 65536: @@ -66,18 +99,29 @@ def health() -> bool: def loaded() -> bool: - return subprocess.run(["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"], - capture_output=True, timeout=5, check=False).returncode == 0 + return ( + subprocess.run( + ["launchctl", "print", f"gui/{os.getuid()}/{LABEL}"], + capture_output=True, + timeout=5, + check=False, + ).returncode + == 0 + ) def unload() -> None: - subprocess.run(["launchctl", "bootout", f"gui/{os.getuid()}/{LABEL}"], - capture_output=True, timeout=20, check=False) + subprocess.run( + ["launchctl", "bootout", f"gui/{os.getuid()}/{LABEL}"], + capture_output=True, + timeout=20, + check=False, + ) deadline = time.monotonic() + 20 while loaded(): if time.monotonic() > deadline: raise RuntimeError("Map Gateway link did not finish unloading") - time.sleep(.2) + time.sleep(0.2) def write_atomic(path: Path, value: bytes) -> None: @@ -112,15 +156,22 @@ def main() -> None: if previous is not None and plistlib.loads(previous).get("Label") != LABEL: raise ValueError("Refusing a foreign LaunchAgent") desired = payload(args.target, runtime) - plan = {"label": LABEL, "agent_path": str(agent), "target": args.target, - "local_bind": f"127.0.0.1:{PORT}", "remote_bind": f"127.0.0.1:{PORT}", - "current_sha256": digest(previous), "desired_sha256": digest(desired), - "remote_mutation": False} + plan = { + "label": LABEL, + "agent_path": str(agent), + "target": args.target, + "local_bind": f"127.0.0.1:{PORT}", + "remote_bind": f"127.0.0.1:{PORT}", + "current_sha256": digest(previous), + "desired_sha256": digest(desired), + "remote_mutation": False, + } if args.action == "plan": print(json.dumps(plan, indent=2)) return - if (args.expected_current_sha256 != digest(previous) - or args.expected_desired_sha256 != digest(desired)): + if args.expected_current_sha256 != digest(previous) or args.expected_desired_sha256 != digest( + desired + ): raise ValueError("Map Gateway link plan changed before apply") was_loaded = loaded() if previous == desired and was_loaded and health(): @@ -137,20 +188,28 @@ def main() -> None: if was_loaded: unload() write_atomic(agent, desired) - subprocess.run(["launchctl", "bootstrap", f"gui/{os.getuid()}", str(agent)], - capture_output=True, timeout=20, check=True) + subprocess.run( + ["launchctl", "bootstrap", f"gui/{os.getuid()}", str(agent)], + capture_output=True, + timeout=20, + check=True, + ) deadline = time.monotonic() + 40 while not health(): if time.monotonic() > deadline: raise RuntimeError("Map Gateway link did not pass health acceptance") - time.sleep(.5) + time.sleep(0.5) except BaseException: unload() if previous is not None: write_atomic(agent, previous) if was_loaded: - subprocess.run(["launchctl", "bootstrap", f"gui/{os.getuid()}", str(agent)], - capture_output=True, timeout=20, check=True) + subprocess.run( + ["launchctl", "bootstrap", f"gui/{os.getuid()}", str(agent)], + capture_output=True, + timeout=20, + check=True, + ) else: agent.unlink(missing_ok=True) raise diff --git a/scripts/manage_runtime_log_policy.py b/scripts/manage_runtime_log_policy.py new file mode 100644 index 00000000..7e232bfa --- /dev/null +++ b/scripts/manage_runtime_log_policy.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Hash-gated bounded journals for existing, explicitly owned local LaunchAgents. + +Only stdout/stderr ownership changes. Arguments, environment, schedules, SSH +trust and forwarding endpoints stay byte-for-byte equivalent after unwrapping. +Previous declarations and journals are preserved for rollback and diagnosis. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import plistlib +import subprocess +import time +from pathlib import Path + +from manage_mission_core_launch_agent import _reload_launch_agent, _wait_for_health, _write_atomic +from migrate_worker_tunnel_logs import reload_agent + +from k1link.launchd_logs import bounded_launchd_output, service_command, service_log_path + +LABELS = { + "core": "com.nodedc.mission-core.local", + "observatory": "com.nodedc.observatory-worker-tunnel.local", + "gaussian": "com.nodedc.gaussian-pipeline-tunnel.local", + "telemetry-startup": "com.nodedc.telemetry-startup.local", + "telemetry-tunnel": "com.nodedc.telemetry-tunnel.local", + "map": "com.nodedc.mission-core.map-gateway-link", +} + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def plan(root, name, *, home=None): + home = home or Path.home() + root = root.resolve(strict=True) + label = LABELS[name] + agent = home / "Library/LaunchAgents" / f"{label}.plist" + if agent.is_symlink() or not agent.is_file(): + raise ValueError("Missing or unsafe existing LaunchAgent") + before = agent.read_bytes() + document = plistlib.loads(before) + if document.get("Label") != label: + raise ValueError("Foreign LaunchAgent") + command = service_command(document) + if name == "core": + if document.get("WorkingDirectory") != str(root) or command[-2:] != ["k1link", "serve"]: + raise ValueError("Unexpected canonical Core declaration") + elif name == "telemetry-startup": + if str(root / "scripts/manage_telemetry_startup.py") not in command: + raise ValueError("Unexpected startup owner") + elif command[0] != "/usr/bin/ssh": + raise ValueError("Unexpected tunnel command") + desired = bounded_launchd_output(document, root) + assert service_command(desired) == command + for key in set(document) | set(desired): + if key not in {"ProgramArguments", "StandardOutPath", "StandardErrorPath"} and document.get( + key + ) != desired.get(key): + raise ValueError("Service policy changed") + payload = plistlib.dumps(desired, sort_keys=True) + result = { + "schema": "missioncore.runtime-log-policy/v1", + "name": name, + "label": label, + "root": str(root), + "agent": str(agent), + "before_sha256": digest(before), + "desired_sha256": digest(payload), + "changed": before != payload, + "journal": str(service_log_path(desired)), + "max_bytes": 8388608, + "backups": 4, + "commands_and_environment_preserved": True, + } + return result, before, payload + + +def accept(name, label): + if name == "core": + if not _wait_for_health(45): + raise RuntimeError("Core health failed") + return {"operational": True} + target = f"gui/{os.getuid()}/{label}" + previous = None + stable = 0 + for _ in range(15): + result = subprocess.run( + ["launchctl", "print", target], capture_output=True, text=True, timeout=5 + ) + state = result.stdout + if name == "telemetry-startup" and "last exit code = 0" in state: + return {"last_exit_code": 0} + pid = next( + (line.strip() for line in state.splitlines() if line.strip().startswith("pid = ")), None + ) + stable = stable + 1 if pid and pid == previous and "state = running" in state else 0 + if stable >= 5: + return {"stable_process": pid} + previous = pid + time.sleep(1) + raise RuntimeError("LaunchAgent did not reach a stable accepted state") + + +def apply(expected): + current, before, payload = plan(Path(expected["root"]), expected["name"]) + if current != expected: + raise ValueError("Stale log policy plan") + if not current["changed"]: + return {**current, "applied": False} + path = Path(current["agent"]) + root = Path(current["root"]) + backup = ( + root + / ".runtime/storage-maintenance/log-policy" + / current["label"] + / f"{current['before_sha256']}.plist" + ) + if backup.exists() and backup.read_bytes() != before: + raise ValueError("Rollback identity collision") + if not backup.exists(): + _write_atomic(backup, before) + _write_atomic(path, payload) + try: + if current["name"] == "core": + _reload_launch_agent(path) + else: + reload_agent(path, current["label"]) + proof = accept(current["name"], current["label"]) + except BaseException: + _write_atomic(path, before) + if current["name"] == "core": + _reload_launch_agent(path) + else: + reload_agent(path, current["label"]) + accept(current["name"], current["label"]) + raise + receipt = { + **current, + "applied": True, + "backup": str(backup), + "accepted": proof, + "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + } + _write_atomic(backup.with_suffix(".receipt.json"), json.dumps(receipt, indent=2).encode()) + return receipt + + +def main(): + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("action", choices=["plan", "apply"]) + p.add_argument("name", choices=LABELS) + p.add_argument("--plan", type=Path) + a = p.parse_args() + if a.action == "plan": + value = plan(Path(__file__).resolve().parents[1], a.name)[0] + else: + if not a.plan: + p.error("apply requires --plan") + expected = json.loads(a.plan.read_text()) + if expected["name"] != a.name: + p.error("plan owner does not match") + value = apply(expected) + print(json.dumps(value, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/manage_telemetry_startup.py b/scripts/manage_telemetry_startup.py index 86cb87ae..258ffd81 100644 --- a/scripts/manage_telemetry_startup.py +++ b/scripts/manage_telemetry_startup.py @@ -21,7 +21,7 @@ from pathlib import Path from manage_mission_core_launch_agent import _wait_for_health, _write_atomic from migrate_worker_tunnel_logs import reload_agent -from k1link.launchd_logs import launchd_log_path, prepare_launchd_log +from k1link.launchd_logs import bounded_launchd_output, launchd_log_path, prepare_launchd_log from k1link.web.compute_contour_network import _replace_environment_value STARTUP = "com.nodedc.telemetry-startup.local" @@ -194,6 +194,8 @@ def plan(stack: Path, ssh_alias: str, repository: Path, agents: Path): StandardOutPath="/dev/null", StandardErrorPath=str(launchd_log_path("telemetry-tunnel.log")), ) + startup = bounded_launchd_output(startup, repository) + tunnel = bounded_launchd_output(tunnel, repository) core_path = agents / (CORE + ".plist") core = plistlib.loads(private_file(core_path)) if core.get("Label") != CORE or core.get("WorkingDirectory") != str(repository): diff --git a/scripts/migrate_worker_tunnel_logs.py b/scripts/migrate_worker_tunnel_logs.py index c558d4c8..063d6021 100644 --- a/scripts/migrate_worker_tunnel_logs.py +++ b/scripts/migrate_worker_tunnel_logs.py @@ -15,7 +15,12 @@ from pathlib import Path from manage_mission_core_launch_agent import _write_atomic -from k1link.launchd_logs import launchd_log_path, prepare_launchd_log +from k1link.launchd_logs import ( + bounded_launchd_output, + launchd_log_path, + prepare_launchd_log, + service_command, +) LABELS = { "observatory": "com.nodedc.observatory-worker-tunnel.local", @@ -48,10 +53,11 @@ def main(): raise ValueError("LaunchAgent cannot be a symlink") previous = agent.read_bytes() desired = plistlib.loads(previous) - if desired["Label"] != label or desired["ProgramArguments"][0] != "/usr/bin/ssh": + if desired["Label"] != label or service_command(desired)[0] != "/usr/bin/ssh": raise ValueError("Unexpected tunnel declaration") log = launchd_log_path(a.tunnel + "-worker-tunnel.log") desired.update(StandardOutPath=str(log), StandardErrorPath=str(log)) + desired = bounded_launchd_output(desired, Path(__file__).resolve().parents[1]) payload = plistlib.dumps(desired, sort_keys=True) plan = dict( label=label, diff --git a/scripts/packaging/build_retention.py b/scripts/packaging/build_retention.py new file mode 100644 index 00000000..02473a42 --- /dev/null +++ b/scripts/packaging/build_retention.py @@ -0,0 +1,616 @@ +"""Operator-side lifecycle for intermediate Linux inputs, never runtime/evidence GC. + +Only four exact archive families in two build directories are eligible. Unknown +legacy files stay protected. Producers publish atomically with a persistent +active hold; completing a build explicitly releases that hold. No TTL can guess +that a remote build, disconnected transfer or qualification has finished. +""" + +from __future__ import annotations + +import argparse +import fcntl +import hashlib +import json +import os +import re +import shutil +import stat +import time +import uuid +import zipfile +from contextlib import contextmanager +from pathlib import Path + +SCHEMA = "missioncore.build-retention/v1" +POLICY = "two-closed-inputs-per-line-v1" +KEEP = 2 +MAX_ACTIVE_PER_FAMILY = 8 +RESERVE = 2 * 1024**3 +SOFT_BUDGET = 6 * 1024**3 +ROOTS = { + "apps/node-agent/build": ("mission-core-node-linux-build-",), + "plugins/insta360-x4/build": ( + "mission-core-x4-build-", + "mission-core-x4-package-build-", + "mission-core-x4-owner-build-", + ), +} +PATTERN = re.compile(r"(.+)-([a-f0-9]{24})\.pyz\Z") + + +class RetentionError(RuntimeError): + pass + + +def _canonical(value): + return json.dumps(value, sort_keys=True, ensure_ascii=True, separators=(",", ":")).encode() + + +def _stamp(s): + return [s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns, s.st_ctime_ns, s.st_nlink] + + +def _plain(path, *, directory=False): + s = path.lstat() + if not (stat.S_ISDIR(s.st_mode) if directory else stat.S_ISREG(s.st_mode)): + raise RetentionError(f"Not a plain {'directory' if directory else 'file'}: {path}") + return s + + +def _atomic(path, value): + if path.exists() or path.is_symlink(): + _plain(path) + temporary = path.with_name("." + path.name + "." + uuid.uuid4().hex + ".tmp") + try: + with temporary.open("xb") as stream: + os.chmod(temporary, 0o600) + stream.write(_canonical(value) + b"\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + fd = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(fd) + finally: + os.close(fd) + finally: + temporary.unlink(missing_ok=True) + + +class BuildRetention: + def __init__(self, root): + supplied = Path(root).absolute() + if supplied.is_symlink(): + raise RetentionError("Repository root is a symlink") + self.root = supplied.resolve(strict=True) + self.control = self.root / ".runtime/build-retention" + self.state_path = self.control / "state.json" + + def _directory(self, relative, *, create=False): + current = self.root + for part in Path(relative).parts: + if part in (".", "..", "/"): + raise RetentionError("Unsafe directory") + current /= part + if create and not current.exists() and not current.is_symlink(): + current.mkdir(mode=0o700, exist_ok=True) + _plain(current, directory=True) + return current + + def _path(self, relative): + p = Path(relative) + if p.is_absolute() or str(p.parent) not in ROOTS: + raise RetentionError("Path is outside managed build-input families") + match = PATTERN.fullmatch(p.name) + if not match or match[1] + "-" not in ROOTS[str(p.parent)]: + raise RetentionError("Only intermediate build inputs are managed") + return self._directory(p.parent) / p.name + + @contextmanager + def _lock(self, *, write=False): + # A fresh read-only plan does not create even a lock or state directory. + if not self.control.exists() and not self.control.is_symlink() and not write: + yield + return + self._directory(".runtime/build-retention", create=write) + lock = self.control / "lock" + if not write and not lock.exists(): + raise RetentionError("Incomplete retention control directory") + fd = os.open( + lock, (os.O_RDWR | os.O_CREAT if write else os.O_RDONLY) | os.O_NOFOLLOW, 0o600 + ) + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise RetentionError("Invalid retention lock") + fcntl.flock(fd, fcntl.LOCK_EX if write else fcntl.LOCK_SH) + yield + finally: + os.close(fd) + + def _state(self): + if not self.state_path.exists() and not self.state_path.is_symlink(): + return {"schema": SCHEMA, "revision": 0, "inputs": {}} + _plain(self.state_path) + state = json.loads(self.state_path.read_text()) + if state.get("schema") != SCHEMA or not isinstance(state.get("inputs"), dict): + raise RetentionError("Unknown retention registry schema") + return state + + def _save(self, state): + state["revision"] += 1 + _atomic(self.state_path, state) + + def _read(self, relative, *, physical=None): + path = physical or self._path(relative) + before = _plain(path) + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "rb") as stream: + if _stamp(before) != _stamp(os.fstat(stream.fileno())): + raise RetentionError("Input changed while opening") + digest = hashlib.file_digest(stream, "sha256").hexdigest() + stream.seek(0) + with zipfile.ZipFile(stream) as archive: + name = ( + "manifest.json" + if "/mission-core-x4-owner-build-" in relative + else "source.json" + ) + if len([x for x in archive.namelist() if x == name]) != 1: + raise RetentionError("Missing or duplicate build manifest") + if archive.getinfo(name).file_size > 16 * 1024**2: + raise RetentionError("Build manifest is too large") + raw = archive.read(name) + manifest = json.loads(raw) + if _stamp(before) != _stamp(os.fstat(stream.fileno())): + raise RetentionError("Input changed while reading") + if _stamp(before) != _stamp(_plain(path)): + raise RetentionError("Input path changed while reading") + match = PATTERN.fullmatch(Path(relative).name) + if not match or hashlib.sha256(raw).hexdigest()[:24] != match[2]: + raise RetentionError("Build manifest identity differs from filename") + prefix = match[1] + schema = manifest.get("schema") + if ( + prefix == "mission-core-node-linux-build" + and schema == "missioncore.node.linux-build-source/v1" + ): + profile = manifest.get("profile") + if profile not in {"node-only", "node-core"}: + raise RetentionError("Unknown Node build profile") + line = "node/" + profile + elif ( + prefix in {"mission-core-x4-build", "mission-core-x4-package-build"} + and schema == "missioncore.insta360.build-source/v1" + ): + kind = manifest.get("kind", "native") + if kind != ("native" if prefix == "mission-core-x4-build" else "package"): + raise RetentionError("X4 kind differs from filename") + line = "x4/" + kind + elif ( + prefix == "mission-core-x4-owner-build" + and schema == "missioncore.insta360.owner-wrapper-build/v1" + ): + line = "x4/owner" + else: + raise RetentionError("Unknown build manifest schema/family") + base = manifest.get("base") + if base is not None: + if not isinstance(base, dict) or set(base) != {"name", "sha256"}: + raise RetentionError("Invalid base reference") + if Path(base["name"]).name != base["name"] or not re.fullmatch( + r"[a-f0-9]{64}", base["sha256"] + ): + raise RetentionError("Unsafe base reference") + base = {"path": str(Path(relative).parent / base["name"]), "sha256": base["sha256"]} + self._path(base["path"]) + return { + "path": relative, + "line": line, + "sha256": digest, + "bytes": before.st_size, + "stamp": _stamp(before), + "base": base, + } + + def _inventory(self): + rows, errors = {}, [] + for directory, prefixes in ROOTS.items(): + if not (self.root / directory).exists() and not (self.root / directory).is_symlink(): + continue + try: + root = self._directory(directory) + for p in sorted(root.iterdir()): + # Recognizable but malformed archives block deletion, rather than disappearing. + if p.suffix != ".pyz" or not p.name.startswith(prefixes): + continue + relative = str(p.relative_to(self.root)) + try: + self._path(relative) + rows[relative] = self._read(relative) + except ( + RetentionError, + OSError, + ValueError, + KeyError, + TypeError, + zipfile.BadZipFile, + ) as exc: + errors.append(f"{relative}: {exc}") + except (RetentionError, OSError) as exc: + errors.append(f"{directory}: {exc}") + return rows, errors + + def _plan(self): + state = self._state() + rows, errors = self._inventory() + reasons = {name: [] for name in rows} + eligible = {} + for name, record in state["inputs"].items(): + if not record.get("deleted") and name not in rows: + errors.append(f"Registered input missing: {name}") + for name, row in rows.items(): + record = state["inputs"].get(name) + if not record: + reasons[name].append("legacy-unreviewed") + else: + if record.get("deleted") or any( + record.get(k) != row[k] for k in ("sha256", "bytes", "line", "base") + ): + errors.append(f"Registered identity changed: {name}") + if record["state"] == "active": + reasons[name].append("active-build:" + record["owner"]) + elif record["state"] != "closed": + errors.append(f"Invalid lifecycle state: {name}") + for pin, reason in sorted(record["pins"].items()): + reasons[name].append(f"pin:{pin}:{reason}") + if record["state"] == "closed" and not record["pins"]: + eligible.setdefault(row["line"], []).append(name) + base = row["base"] + if base and ( + base["path"] not in rows or rows[base["path"]]["sha256"] != base["sha256"] + ): + errors.append(f"Missing or changed base: {name}") + for names in eligible.values(): + names.sort(key=lambda n: (state["inputs"][n]["published_ns"], n), reverse=True) + for name in names[:KEEP]: + reasons[name].append("latest-two-completed-in-line") + # Protect the entire dependency closure, including legacy/active/pinned roots. + visiting, visited = set(), set() + + def protect(name): + if name in visiting: + errors.append(f"Cyclic base graph: {name}") + return + if name in visited: + return + visiting.add(name) + base = rows[name]["base"] + if base and base["path"] in rows: + reasons[base["path"]].append("base-of:" + name) + protect(base["path"]) + visiting.remove(name) + visited.add(name) + + for name in sorted(rows): + if reasons[name]: + protect(name) + + # Validate even candidate-only dependency components before any unlink. + def cycle(name, chain): + if name in chain: + errors.append(f"Cyclic base graph: {name}") + return + base = rows[name]["base"] + if base and base["path"] in rows: + cycle(base["path"], chain | {name}) + + for name in rows: + cycle(name, set()) + decisions = [ + dict( + row, + action="retain" if reasons[name] or errors else "delete", + reasons=sorted(set(reasons[name])) + or (["blocked-by-inventory-error"] if errors else ["superseded-completed-input"]), + ) + for name, row in sorted(rows.items()) + ] + total = sum(x["bytes"] for x in decisions) + result = { + "schema": "missioncore.build-retention-plan/v1", + "policy": POLICY, + "root": str(self.root), + "registry_sha256": hashlib.sha256(_canonical(state)).hexdigest(), + "inputs": decisions, + "errors": sorted(set(errors)), + "total_logical_bytes": total, + "soft_budget_bytes": SOFT_BUDGET, + "over_soft_budget": total > SOFT_BUDGET, + "candidate_bytes_upper_bound": sum( + x["bytes"] for x in decisions if x["action"] == "delete" + ), + } + result["plan_id"] = hashlib.sha256(_canonical(result)).hexdigest() + return result + + def plan(self): + with self._lock(): + return self._plan() + + def _record(self, state, row, *, active, reason, pin=None): + name = row["path"] + previous = state["inputs"].get(name) + if previous and not previous.get("deleted"): + raise RetentionError("Input already registered; use finish/pin/unpin") + record = {k: row[k] for k in ("sha256", "bytes", "line", "base")} + record.update( + state="active" if active else "closed", + published_ns=time.time_ns() if active else row["stamp"][3], + owner=uuid.uuid4().hex, + reason=reason, + pins={pin: reason} if pin else {}, + ) + state["inputs"][name] = record + self._save(state) + return record["owner"] + + def adopt(self, relative, *, pin, reason): + """Legacy enrollment always pins; it never silently makes a file disposable.""" + if not pin or not reason.strip(): + raise RetentionError("A legacy hold and a reason are required") + with self._lock(write=True): + return self._record( + self._state(), self._read(relative), active=False, pin=pin, reason=reason + ) + + def pin(self, relative, *, pin, reason, remove=False): + if not pin or not reason.strip(): + raise RetentionError("A pin identity and reason are required") + with self._lock(write=True): + state = self._state() + record = state["inputs"][relative] + row = self._read(relative) + if record.get("deleted") or row["sha256"] != record["sha256"]: + raise RetentionError("Registered input changed") + if remove: + if pin not in record["pins"]: + raise RetentionError("Unknown pin") + del record["pins"][pin] + else: + record["pins"][pin] = reason + record["reason"] = reason + self._save(state) + + def finish(self, relative, *, owner, outcome, reason): + if ( + outcome not in {"intermediate", "failed", "cancelled", "qualified", "rollback"} + or not reason.strip() + ): + raise RetentionError("Explicit terminal outcome and reason required") + with self._lock(write=True): + state = self._state() + record = state["inputs"][relative] + row = self._read(relative) + if record.get("deleted") or record["sha256"] != row["sha256"]: + raise RetentionError("Registered input changed") + if record["state"] != "active" or record["owner"] != owner: + raise RetentionError("Build owner changed or build is already closed") + record.update(state="closed", outcome=outcome, reason=reason) + if outcome in {"qualified", "rollback"}: + record["pins"][outcome] = reason + self._save(state) + # A finish only releases a hold. Destructive work uses a reviewable plan. + return self.plan() + + @contextmanager + def publish(self, output, *, required_bytes=0): + """Atomic publication + persistent hold; failed staging removes only its own temp.""" + output = Path(output).absolute() + relative = str(output.relative_to(self.root)) + with self._lock(write=True): + path = self._path(relative) + if path.exists() or path.is_symlink(): + raise FileExistsError(path) + state = self._state() + # Family prefix gives a conservative count before the archive exists. + prefix = PATTERN.fullmatch(path.name)[1] + active = sum( + 1 + for n, r in state["inputs"].items() + if not r.get("deleted") + and r["state"] == "active" + and Path(n).name.startswith(prefix + "-") + ) + if active >= MAX_ACTIVE_PER_FAMILY: + raise RetentionError( + "Eight unfinished inputs in this family; finish or cancel their owners first" + ) + if required_bytes < 0 or shutil.disk_usage(path.parent).free < RESERVE + required_bytes: + raise RetentionError("Insufficient build space; preserve 2 GiB after staging") + temporary = path.with_name(".retention-" + uuid.uuid4().hex + ".part") + try: + yield temporary + row = self._read(relative, physical=temporary) + seen, base = {relative}, row["base"] + while base: + if base["path"] in seen: + raise RetentionError("Cyclic publication base graph") + seen.add(base["path"]) + dependency = self._read(base["path"]) + if dependency["sha256"] != base["sha256"]: + raise RetentionError("Publication base changed") + base = dependency["base"] + os.chmod(temporary, 0o600) + with temporary.open("rb") as stream: + os.fsync(stream.fileno()) + # No replace: a non-cooperating publisher must not lose its file. + os.link(temporary, path, follow_symlinks=False) + temporary.unlink() + # A crash before registry commit leaves an unknown, protected file. + self._record(state, row, active=True, reason="Awaiting explicit build outcome") + finally: + temporary.unlink(missing_ok=True) + + def apply(self, expected): + with self._lock(write=True): + current = self._plan() + if expected != current: + raise RetentionError("Stale or edited plan; generate a fresh plan") + if current["errors"]: + raise RetentionError("Inventory errors block all deletions") + state = self._state() + candidates = [x for x in current["inputs"] if x["action"] == "delete"] + + # Delete dependants before bases: interruption must leave a usable graph. + def depth(row): + count, base = 0, row["base"] + by_path = {x["path"]: x for x in current["inputs"]} + while base: + count += 1 + base = by_path[base["path"]]["base"] + return count + + candidates.sort(key=lambda row: (-depth(row), row["path"])) + receipt_dir = self._directory(".runtime/build-retention/receipts", create=True) + receipt_path = receipt_dir / (uuid.uuid4().hex + ".json") + receipt = { + "schema": "missioncore.build-retention-receipt/v1", + "plan_id": current["plan_id"], + "started_ns": time.time_ns(), + "status": "applying", + "plan": current, + "removed": [], + "free_before": shutil.disk_usage(self.root).free, + } + _atomic(receipt_path, receipt) + try: + # All bytes were verified by _plan under the shared publication lock. + # Metadata is checked again immediately before each unlink. + for row in candidates: + path = self._path(row["path"]) + if _stamp(_plain(path)) != row["stamp"]: + raise RetentionError("Input changed before unlink") + receipt["next"] = row["path"] + _atomic(receipt_path, receipt) + path.unlink() + receipt["removed"].append( + {"path": row["path"], "sha256": row["sha256"], "bytes": row["bytes"]} + ) + state["inputs"][row["path"]]["deleted"] = True + self._save(state) + _atomic(receipt_path, receipt) + receipt["status"] = "complete" + except BaseException as exc: + receipt.update(status="interrupted", error=str(exc)) + raise + finally: + receipt.update( + finished_ns=time.time_ns(), free_after=shutil.disk_usage(self.root).free + ) + _atomic(receipt_path, receipt) + return dict(receipt, receipt=str(receipt_path)) + + def recover(self, receipt_name): + """Reconcile only journaled unlinks after a process/storage interruption.""" + if not re.fullmatch(r"[a-f0-9]{32}\.json", receipt_name): + raise RetentionError("Invalid receipt name") + with self._lock(write=True): + path = self._directory(".runtime/build-retention/receipts") / receipt_name + _plain(path) + receipt = json.loads(path.read_text()) + if receipt["schema"] != "missioncore.build-retention-receipt/v1" or receipt[ + "status" + ] not in {"applying", "interrupted"}: + raise RetentionError("Receipt does not need recovery") + state = self._state() + planned = {x["path"]: x for x in receipt["plan"]["inputs"] if x["action"] == "delete"} + journaled = {x["path"] for x in receipt["removed"]} | {receipt.get("next")} + recovered = [] + for name in sorted(n for n in journaled if n is not None): + row = planned[name] + record = state["inputs"][name] + if ( + record["sha256"] != row["sha256"] + or record["state"] != "closed" + or record["pins"] + ): + raise RetentionError("Recovery input was changed or protected") + candidate = self._path(name) + if candidate.exists() or candidate.is_symlink(): + if self._read(name)["sha256"] != row["sha256"]: + raise RetentionError("Recovery input identity changed") + elif not record.get("deleted"): + record["deleted"] = True + recovered.append(name) + self._save(state) + receipt.update( + status="reconciled", reconciled_ns=time.time_ns(), recovered_missing=recovered + ) + _atomic(path, receipt) + return {"recovered_missing": recovered, "receipt": str(path), "deleted_now": 0} + + +def publish_input(output, *, required_bytes=0): + """Producer hook; this module is operator tooling, not an onboard dependency.""" + return BuildRetention(Path(__file__).resolve().parents[2]).publish( + output, required_bytes=required_bytes + ) + + +def input_hold(output): + """Small lifecycle handle included in the producer's existing JSON response.""" + store = BuildRetention(Path(__file__).resolve().parents[2]) + relative = str(Path(output).absolute().relative_to(store.root)) + with store._lock(): + record = store._state()["inputs"][relative] + return {"path": relative, "owner": record["owner"], "state": record["state"]} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[2]) + commands = parser.add_subparsers(dest="command", required=True) + commands.add_parser("plan") + apply = commands.add_parser("apply") + apply.add_argument("--plan", type=Path, required=True) + recover = commands.add_parser("recover") + recover.add_argument("receipt", help="Basename of an interrupted receipt") + for name in ("adopt", "pin", "unpin", "finish"): + child = commands.add_parser(name) + child.add_argument("path", help="Repository-relative intermediate input path") + child.add_argument("--reason", required=True) + if name == "finish": + child.add_argument( + "--owner", required=True, help="Owner from plan/registry active-build reason" + ) + child.add_argument( + "--outcome", + choices=("intermediate", "failed", "cancelled", "qualified", "rollback"), + required=True, + ) + else: + child.add_argument("--pin", required=True) + args = parser.parse_args() + store = BuildRetention(args.root) + if args.command == "plan": + result = store.plan() + elif args.command == "apply": + result = store.apply(json.loads(args.plan.read_text())) + elif args.command == "recover": + result = store.recover(args.receipt) + elif args.command == "adopt": + store.adopt(args.path, pin=args.pin, reason=args.reason) + result = store.plan() + elif args.command == "finish": + result = store.finish(args.path, owner=args.owner, outcome=args.outcome, reason=args.reason) + else: + store.pin(args.path, pin=args.pin, reason=args.reason, remove=args.command == "unpin") + result = store.plan() + print(json.dumps(result, indent=2, sort_keys=True)) + if result.get("errors"): + raise SystemExit(2) + + +if __name__ == "__main__": + main() diff --git a/src/k1link/cache_budget.py b/src/k1link/cache_budget.py new file mode 100644 index 00000000..675ffdcf --- /dev/null +++ b/src/k1link/cache_budget.py @@ -0,0 +1,113 @@ +"""Publication budgets for local derived caches; never evicts retained data. + +Existing generations, unknown files and in-flight files all count. Budget +exhaustion refuses a new disk copy; callers that can work without it may skip it. +This is a publication quota, not a filesystem quota for renderer scratch output. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import threading +from contextlib import contextmanager +from pathlib import Path + +GiB = 1024**3 +MiB = 1024**2 +LIMITS = { + "camera-frame-cache": 256 * MiB, + "lidar-read-cache": 16 * MiB, + "camera-media-index": 64 * MiB, + "perception-overlays": GiB, + "calibrated-fusion-overlays": GiB, + "integrated-perception-overlays": 4 * GiB, + "laboratory-rerun-overlays": 4 * GiB, + "observatory-portable-replay-cache": 4 * GiB, + "editor-cache": 4 * GiB, +} +FREE_RESERVE = 2 * GiB +_LOCK = threading.RLock() +_LOCK_NAME = ".publication-budget.lock" + + +class CacheCapacityError(ValueError): + pass + + +def usage(root: Path) -> tuple[int, int]: + total = count = 0 + for base, directories, files in os.walk(root, followlinks=False): + for name in directories + files: + p = Path(base) / name + s = p.lstat() + if stat.S_ISDIR(s.st_mode): + continue + if not stat.S_ISREG(s.st_mode): + raise CacheCapacityError("Cache contains an unsafe path; preserved") + if p == root / _LOCK_NAME: + continue + total += s.st_size + count += 1 + if count > 100000: + raise CacheCapacityError("Cache inventory exceeds its file budget; preserved") + return total, count + + +@contextmanager +def cache_publication( + root: Path, + additional_bytes: int, + *, + kind=None, + limit=None, + reserve=FREE_RESERVE, + max_files=10000, + error_type=CacheCapacityError, +): + """Lock admission through publication. Count temporary bytes already on disk. + + additional_bytes includes only bytes not yet in this root; a file renamed + within it contributes zero additional bytes. Callers include sidecar overhead. + Unknown legacy contents stay in place even if already above the new limit. + """ + root = root.expanduser().absolute() + maximum = LIMITS[kind or root.name] if limit is None else limit + if type(additional_bytes) is not int or additional_bytes < 0 or maximum < 1: + raise ValueError("Invalid cache publication budget") + ancestor = root + while not ancestor.exists(): + ancestor = ancestor.parent + if ancestor.resolve() != ancestor: + raise CacheCapacityError("Cache ancestor is not canonical") + root.mkdir(mode=0o700, parents=True, exist_ok=True) + if root.resolve() != root or not stat.S_ISDIR(root.lstat().st_mode): + raise CacheCapacityError("Cache root is not canonical") + with _LOCK: + fd = os.open(root / _LOCK_NAME, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600) + try: + s = os.fstat(fd) + if not stat.S_ISREG(s.st_mode) or s.st_nlink != 1 or s.st_uid != os.getuid(): + raise CacheCapacityError("Unsafe cache publication lock") + # Operator cache publication is Mac/Linux owned, never the remote Worker. + import fcntl + + fcntl.flock(fd, fcntl.LOCK_EX) + current, count = usage(root) + if current + additional_bytes > maximum or count >= max_files: + raise CacheCapacityError("Достигнут лимит кэша. Сохранённые данные не удалены.") + if shutil.disk_usage(root).free < additional_bytes + reserve: + raise CacheCapacityError("Недостаточно свободного места для новой копии кэша.") + yield + except CacheCapacityError as exc: + if error_type is CacheCapacityError: + raise + raise error_type(str(exc)) from exc + finally: + os.close(fd) + + +def require_cache_room(root: Path, additional_bytes=0, **kwargs): + with cache_publication(root, additional_bytes, **kwargs): + pass diff --git a/src/k1link/compute/fusion_epoch.py b/src/k1link/compute/fusion_epoch.py index 3f80aaf5..c1ca8ae1 100644 --- a/src/k1link/compute/fusion_epoch.py +++ b/src/k1link/compute/fusion_epoch.py @@ -18,6 +18,7 @@ import rerun as rr from rerun.components import FillMode from k1link.artifacts import write_json_atomic +from k1link.cache_budget import cache_publication, require_cache_room from k1link.sessions import SessionIntegrityError from .jobs import CameraComputeJob, validate_camera_compute_job @@ -104,31 +105,43 @@ class RecordedCalibratedFusionStore: cached = _read_cache(output, sidecar, fusion, recording_id) if cached is not None: return cached + require_cache_room( + self.cache_root, + 65536, + kind="calibrated-fusion-overlays", + error_type=RecordedPerceptionOverlayError, + ) payload = _render_fusion( fusion, application_id=application_id, recording_id=recording_id, ) - temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp") - try: - with temporary.open("xb") as stream: - stream.write(payload) - stream.flush() - os.fsync(stream.fileno()) - os.chmod(temporary, 0o600) - os.replace(temporary, output) - write_json_atomic( - sidecar, - { - "schema_version": "missioncore.calibrated-fusion-overlay-cache/v1", - "fusion_id": fusion.fusion_id, - "recording_id": recording_id, - "byte_length": len(payload), - "sha256": hashlib.sha256(payload).hexdigest(), - }, - ) - finally: - temporary.unlink(missing_ok=True) + with cache_publication( + self.cache_root, + len(payload) + 65536, + kind="calibrated-fusion-overlays", + error_type=RecordedPerceptionOverlayError, + ): + temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp") + try: + with temporary.open("xb") as stream: + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(temporary, 0o600) + os.replace(temporary, output) + write_json_atomic( + sidecar, + { + "schema_version": "missioncore.calibrated-fusion-overlay-cache/v1", + "fusion_id": fusion.fusion_id, + "recording_id": recording_id, + "byte_length": len(payload), + "sha256": hashlib.sha256(payload).hexdigest(), + }, + ) + finally: + temporary.unlink(missing_ok=True) return payload def _latest(self, session_id: str) -> RecordedCalibratedFusion | None: @@ -540,9 +553,8 @@ def _read_labels(path: Path) -> list[str]: value = json.loads(path.read_text(encoding="utf-8")) except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: raise SessionIntegrityError("calibrated fusion labels are unavailable") from exc - if ( - not isinstance(value, list) - or any(not isinstance(item, str) or not 1 <= len(item) <= 256 for item in value) + if not isinstance(value, list) or any( + not isinstance(item, str) or not 1 <= len(item) <= 256 for item in value ): raise SessionIntegrityError("calibrated fusion labels are invalid") return value diff --git a/src/k1link/compute/integrated_perception.py b/src/k1link/compute/integrated_perception.py index 5ec139b5..2011cdda 100644 --- a/src/k1link/compute/integrated_perception.py +++ b/src/k1link/compute/integrated_perception.py @@ -28,6 +28,7 @@ from k1link.artifact_gateway import ( ArtifactStoreUnavailable, ) from k1link.artifacts import write_json_atomic +from k1link.cache_budget import CacheCapacityError, cache_publication, require_cache_room from k1link.sessions import SessionIntegrityError from .jobs import CameraComputeJob, validate_camera_compute_job @@ -498,6 +499,12 @@ class IntegratedPerceptionOverlayStore: ) return cached self._set_status(key, state="preparing", phase="rendering") + require_cache_room( + self.cache_root, + 65536, + kind="integrated-perception-overlays", + error_type=RecordedPerceptionOverlayError, + ) payload = _render( result, application_id=application_id, @@ -506,29 +513,35 @@ class IntegratedPerceptionOverlayStore: temporary_root=cache, ) self._set_status(key, state="preparing", phase="cache-write") - temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp") - try: - with temporary.open("xb") as stream: - stream.write(payload) - stream.flush() - os.fsync(stream.fileno()) - os.chmod(temporary, 0o600) - os.replace(temporary, output) - write_json_atomic( - sidecar, - { - "schema_version": OVERLAY_CACHE_SCHEMA, - "renderer_version": OVERLAY_RENDERER_VERSION, - "session_id": session_id, - "result_id": result.result_id, - "result_created_at_utc": result.created_at_utc, - "recording_id": recording_id, - "byte_length": len(payload), - "sha256": hashlib.sha256(payload).hexdigest(), - }, - ) - finally: - temporary.unlink(missing_ok=True) + with cache_publication( + self.cache_root, + len(payload) + 65536, + kind="integrated-perception-overlays", + error_type=RecordedPerceptionOverlayError, + ): + temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp") + try: + with temporary.open("xb") as stream: + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(temporary, 0o600) + os.replace(temporary, output) + write_json_atomic( + sidecar, + { + "schema_version": OVERLAY_CACHE_SCHEMA, + "renderer_version": OVERLAY_RENDERER_VERSION, + "session_id": session_id, + "result_id": result.result_id, + "result_created_at_utc": result.created_at_utc, + "recording_id": recording_id, + "byte_length": len(payload), + "sha256": hashlib.sha256(payload).hexdigest(), + }, + ) + finally: + temporary.unlink(missing_ok=True) self._set_status( key, state="ready", @@ -770,9 +783,7 @@ class IntegratedPerceptionOverlayStore: or descriptor.result_id != result.result_id or descriptor.created_at_utc != result.created_at_utc ): - raise RecordedPerceptionOverlayError( - "integrated perception admission identity changed" - ) + raise RecordedPerceptionOverlayError("integrated perception admission identity changed") cache_root = _private_directory(self.cache_root) session_cache = _private_child(cache_root, descriptor.session_id) self._write_admission_document( @@ -790,17 +801,24 @@ class IntegratedPerceptionOverlayStore: session_cache: Path, admission: _OverlayAdmission, ) -> None: - write_json_atomic( - session_cache / "admission.json", - { - "schema_version": OVERLAY_ADMISSION_SCHEMA, - "renderer_version": OVERLAY_RENDERER_VERSION, - "session_id": admission.session_id, - "result_id": admission.result_id, - "result_json_sha256": admission.result_json_sha256, - "result_created_at_utc": admission.result_created_at_utc, - }, - ) + try: + with cache_publication( + session_cache.parent, 65536, kind="integrated-perception-overlays" + ): + write_json_atomic( + session_cache / "admission.json", + { + "schema_version": OVERLAY_ADMISSION_SCHEMA, + "renderer_version": OVERLAY_RENDERER_VERSION, + "session_id": admission.session_id, + "result_id": admission.result_id, + "result_json_sha256": admission.result_json_sha256, + "result_created_at_utc": admission.result_created_at_utc, + }, + ) + except CacheCapacityError: + # A full disk cache must not prevent recovery of an already sealed overlay. + pass def _latest_descriptor(self, session_id: str) -> _ResultDescriptor | None: try: @@ -1274,8 +1292,7 @@ def _read_result_descriptor(result_root: Path) -> _ResultDescriptor: or root.name != f"e10-integrated-perception-{identity_sha256}" or hashlib.sha256(_canonical_json(identity)).hexdigest() != identity_sha256 or result.get("acceptance_state") != "accepted" - or result.get("publication_scope") - != "recorded-integrated-realtime-qualification-only" + or result.get("publication_scope") != "recorded-integrated-realtime-qualification-only" or not isinstance(session_id, str) or _SAFE_RECORDING_ID.fullmatch(session_id) is None or not isinstance(job_id, str) diff --git a/src/k1link/compute/results.py b/src/k1link/compute/results.py index a87db277..40019658 100644 --- a/src/k1link/compute/results.py +++ b/src/k1link/compute/results.py @@ -16,6 +16,7 @@ import numpy as np import rerun as rr from k1link.artifacts import write_json_atomic +from k1link.cache_budget import cache_publication, require_cache_room from k1link.sessions import SessionIntegrityError from .jobs import CameraComputeJob, validate_camera_compute_job @@ -222,6 +223,12 @@ class RecordedPerceptionOverlayStore: cached = _read_cached_overlay(output, sidecar, result) if cached is not None: return cached + require_cache_room( + self.cache_root, + 65536, + kind="perception-overlays", + error_type=RecordedPerceptionOverlayError, + ) payload = _render_overlay( result, application_id=application_id, @@ -229,26 +236,32 @@ class RecordedPerceptionOverlayStore: ffmpeg_path=self.ffmpeg_path, ffprobe_path=self.ffprobe_path, ) - temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp") - try: - with temporary.open("xb") as stream: - stream.write(payload) - stream.flush() - os.fsync(stream.fileno()) - os.chmod(temporary, 0o600) - os.replace(temporary, output) - write_json_atomic( - sidecar, - { - "schema_version": "missioncore.perception-overlay-cache/v1", - "result_id": result.result_id, - "recording_id": recording_id, - "byte_length": len(payload), - "sha256": hashlib.sha256(payload).hexdigest(), - }, - ) - finally: - temporary.unlink(missing_ok=True) + with cache_publication( + self.cache_root, + len(payload) + 65536, + kind="perception-overlays", + error_type=RecordedPerceptionOverlayError, + ): + temporary = output.with_name(f".{output.name}.{os.getpid()}.tmp") + try: + with temporary.open("xb") as stream: + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(temporary, 0o600) + os.replace(temporary, output) + write_json_atomic( + sidecar, + { + "schema_version": "missioncore.perception-overlay-cache/v1", + "result_id": result.result_id, + "recording_id": recording_id, + "byte_length": len(payload), + "sha256": hashlib.sha256(payload).hexdigest(), + }, + ) + finally: + temporary.unlink(missing_ok=True) return payload def _latest_result(self, session_id: str) -> RecordedPerceptionResult | None: @@ -408,10 +421,7 @@ def _render_overlay( f"{detection.class_name} · {detection.score:.0%}" for detection in frame.detections ], - colors=[ - _class_color(detection.class_id) - for detection in frame.detections - ], + colors=[_class_color(detection.class_id) for detection in frame.detections], show_labels=True, ), ) @@ -431,16 +441,9 @@ def _render_overlay( def _camera_source_bytes(job: CameraComputeJob) -> bytes: - epoch = ( - job.job_root - / "input" - / "camera" - / job.source_id - / f"epoch-{job.codec_epoch}" - ) + epoch = job.job_root / "input" / "camera" / job.source_id / f"epoch-{job.codec_epoch}" paths = [epoch / "init.mp4"] + [ - epoch / "segments" / f"{sequence}.m4s" - for sequence in range(1, job.segment_count + 1) + epoch / "segments" / f"{sequence}.m4s" for sequence in range(1, job.segment_count + 1) ] total = sum(path.stat().st_size for path in paths) if total > MAX_OVERLAY_SOURCE_BYTES: diff --git a/src/k1link/laboratory/canonical_rerun_overlay.py b/src/k1link/laboratory/canonical_rerun_overlay.py index 9b30bcc0..793548d9 100644 --- a/src/k1link/laboratory/canonical_rerun_overlay.py +++ b/src/k1link/laboratory/canonical_rerun_overlay.py @@ -32,6 +32,8 @@ import rerun as rr import rerun_bindings as bindings from PIL import Image +from k1link.cache_budget import cache_publication, require_cache_room + APPLICATION_ID: Final = "nodedc_mission_core_recorded" SESSION_TIMELINE: Final = "session_time" RENDERER_VERSION: Final = "upstream-rerun-0.36.3-encoded-optimized-v6" @@ -223,6 +225,12 @@ def canonical_lab_overlay( _memory_cache[key] = restored return restored + require_cache_room( + cache, + MAX_OVERLAY_BYTES, + kind="laboratory-rerun-overlays", + error_type=CanonicalLabOverlayError, + ) temporary = cache / f".{identity}.{uuid4().hex}.rrd" proxy: Path | None = None source: Path | None = None @@ -237,20 +245,23 @@ def canonical_lab_overlay( raise CanonicalLabOverlayError("canonical LAB overlay size is invalid") digest = _sha256(temporary) os.chmod(temporary, 0o600) - os.replace(temporary, output) - _write_json_atomic( - sidecar, - { - "schema_version": "missioncore.canonical-lab-rerun-overlay/v1", - "renderer_version": RENDERER_VERSION, - "result_id": result_id, - "result_sha256": result_sha256, - "recording_id": recording_id, - "base_generation_sha256": base_generation_sha256, - "byte_length": stat.st_size, - "sha256": digest, - }, - ) + with cache_publication( + cache, 65536, kind="laboratory-rerun-overlays", error_type=CanonicalLabOverlayError + ): + os.replace(temporary, output) + _write_json_atomic( + sidecar, + { + "schema_version": "missioncore.canonical-lab-rerun-overlay/v1", + "renderer_version": RENDERER_VERSION, + "result_id": result_id, + "result_sha256": result_sha256, + "recording_id": recording_id, + "base_generation_sha256": base_generation_sha256, + "byte_length": stat.st_size, + "sha256": digest, + }, + ) artifact = CanonicalLabOverlayArtifact(output, stat.st_size, digest) _memory_cache[key] = artifact return artifact @@ -327,6 +338,12 @@ def canonical_lab_replay( _replay_memory_cache[key] = restored return restored + require_cache_room( + cache, + MAX_REPLAY_BYTES, + kind="laboratory-rerun-overlays", + error_type=CanonicalLabOverlayError, + ) temporary = cache / f".{identity}.{uuid4().hex}.replay.rrd" try: completed = subprocess.run( @@ -371,20 +388,23 @@ def canonical_lab_replay( stat = temporary.stat() digest = _sha256(temporary) os.chmod(temporary, 0o600) - os.replace(temporary, output) - _write_json_atomic( - sidecar, - { - "schema_version": "missioncore.canonical-lab-rerun-replay/v1", - "renderer_version": REPLAY_RENDERER_VERSION, - "result_id": result_id, - "recording_id": recording_id, - "base_generation_sha256": base_generation_sha256, - "overlay_sha256": overlay.sha256, - "byte_length": stat.st_size, - "sha256": digest, - }, - ) + with cache_publication( + cache, 65536, kind="laboratory-rerun-overlays", error_type=CanonicalLabOverlayError + ): + os.replace(temporary, output) + _write_json_atomic( + sidecar, + { + "schema_version": "missioncore.canonical-lab-rerun-replay/v1", + "renderer_version": REPLAY_RENDERER_VERSION, + "result_id": result_id, + "recording_id": recording_id, + "base_generation_sha256": base_generation_sha256, + "overlay_sha256": overlay.sha256, + "byte_length": stat.st_size, + "sha256": digest, + }, + ) artifact = CanonicalLabReplayArtifact(output, stat.st_size, digest) _replay_memory_cache[key] = artifact return artifact diff --git a/src/k1link/launchd_logs.py b/src/k1link/launchd_logs.py index 7ee9051d..e302fd77 100644 --- a/src/k1link/launchd_logs.py +++ b/src/k1link/launchd_logs.py @@ -31,3 +31,61 @@ def prepare_launchd_log(path: Path) -> None: os.fchmod(descriptor, 0o600) finally: os.close(descriptor) + + +def bounded_launchd_output(document: dict, repository: Path, *, uv_path=None) -> dict: + """Preserve a declared command behind a single bounded output owner. + + uv is the accepted Mac privacy execution boundary for this checkout. Its + bootstrap output is discarded; child output and tracebacks go to the owned + journal. launchd still owns the full process group and the original policy. + """ + result = dict(document) + arguments = list(result["ProgramArguments"]) + if "k1link.rotating_process" in arguments: + service_command(result) # Validate the existing owner instead of nesting wrappers. + result["StandardOutPath"] = result["StandardErrorPath"] = "/dev/null" + return result + journal = result.get("StandardErrorPath") or result.get("StandardOutPath") + if not journal or journal == "/dev/null": + raise ValueError("An explicit service journal is required") + path = Path(journal) + if not path.is_absolute() or path.suffix != ".log": + raise ValueError("Invalid service journal") + # Legacy output is kept intact. Fresh managed generations alone rotate. + managed = path.with_name(path.stem + ".managed.log") + result["ProgramArguments"] = [ + str(uv_path or "/opt/homebrew/bin/uv"), + "run", + "--no-sync", + "--project", + str(repository), + "python", + "-m", + "k1link.rotating_process", + "--log", + str(managed), + "--", + *arguments, + ] + result["StandardOutPath"] = result["StandardErrorPath"] = "/dev/null" + return result + + +def service_command(document: dict) -> list[str]: + arguments = list(document["ProgramArguments"]) + if "k1link.rotating_process" in arguments: + index = arguments.index("k1link.rotating_process") + if arguments[index + 1 : index + 2] != ["--log"] or arguments[index + 3 : index + 4] != [ + "--" + ]: + raise ValueError("Invalid managed journal command") + return arguments[index + 4 :] + return arguments + + +def service_log_path(document: dict) -> Path: + arguments = document["ProgramArguments"] + if "k1link.rotating_process" in arguments: + return Path(arguments[arguments.index("k1link.rotating_process") + 2]) + return Path(document["StandardErrorPath"]) diff --git a/src/k1link/local_service_launchd.py b/src/k1link/local_service_launchd.py index 86b32b9e..90bba9b3 100644 --- a/src/k1link/local_service_launchd.py +++ b/src/k1link/local_service_launchd.py @@ -10,19 +10,13 @@ from dataclasses import dataclass from pathlib import Path from typing import Final, cast -from k1link.launchd_logs import launchd_log_path +from k1link.launchd_logs import bounded_launchd_output, launchd_log_path, service_log_path MISSION_CORE_LAUNCH_AGENT_LABEL: Final = "com.nodedc.mission-core.local" MISSION_CORE_LAUNCH_AGENT_SCHEMA: Final = "missioncore.local-launch-agent-plan/v1" -OBSERVATORY_LOCAL_WORKER_ENABLED_ENV: Final = ( - "MISSIONCORE_OBSERVATORY_WORKER_LOCAL_ENABLED" -) -OBSERVATORY_SOURCE_CAS_ROOT_ENV: Final = ( - "MISSIONCORE_OBSERVATORY_WORKER_SOURCE_CAS_ROOT" -) -OBSERVATORY_RESULT_STAGING_ROOT_ENV: Final = ( - "MISSIONCORE_OBSERVATORY_WORKER_RESULT_STAGING_ROOT" -) +OBSERVATORY_LOCAL_WORKER_ENABLED_ENV: Final = "MISSIONCORE_OBSERVATORY_WORKER_LOCAL_ENABLED" +OBSERVATORY_SOURCE_CAS_ROOT_ENV: Final = "MISSIONCORE_OBSERVATORY_WORKER_SOURCE_CAS_ROOT" +OBSERVATORY_RESULT_STAGING_ROOT_ENV: Final = "MISSIONCORE_OBSERVATORY_WORKER_RESULT_STAGING_ROOT" ARTIFACT_STORE_ROOT_ENV: Final = "MISSIONCORE_ARTIFACT_STORE_ROOT" @@ -62,7 +56,7 @@ class MissionCoreLaunchAgentPlan: "desired_program_arguments": list(self.desired_program_arguments), "current_process_type": self.current_process_type, "desired_process_type": "Interactive", - "desired_log_path": plistlib.loads(self.desired_payload)["StandardOutPath"], + "desired_log_path": str(service_log_path(plistlib.loads(self.desired_payload))), "changes": { "repository_migration": self.current_working_directory != self.desired_working_directory, @@ -72,16 +66,13 @@ class MissionCoreLaunchAgentPlan: if self.preserved_data_directory is not None else None ), - "dependency_sync_disabled": "--no-sync" - in self.desired_program_arguments, + "dependency_sync_disabled": "--no-sync" in self.desired_program_arguments, "self_health_watchdog": True, "bounded_launchd_exit_timeout_seconds": 20, "keep_alive": True, "process_group_owned": True, "operator_interactive_resources": True, - "local_observatory_worker_enabled": ( - self.local_observatory_worker_enabled - ), + "local_observatory_worker_enabled": (self.local_observatory_worker_enabled), }, } @@ -113,9 +104,8 @@ def plan_mission_core_launch_agent( raise MissionCoreLaunchAgentError("current launch agent working directory is invalid") if expected_current_repository is None and current_working_directory != str(repository): raise MissionCoreLaunchAgentError("current launch agent targets another repository") - if ( - expected_current_repository is not None - and current_working_directory != str(expected_current_repository) + if expected_current_repository is not None and current_working_directory != str( + expected_current_repository ): raise MissionCoreLaunchAgentError( "current launch agent does not target the expected current repository" @@ -133,11 +123,7 @@ def plan_mission_core_launch_agent( # accepted local execution boundary. ``--no-sync`` keeps launch startup # deterministic and prevents dependency mutation during recovery. uv_entrypoint = Path(current_arguments[0]) - if ( - not uv_entrypoint.is_absolute() - or uv_entrypoint.name != "uv" - or not uv_entrypoint.exists() - ): + if not uv_entrypoint.is_absolute() or uv_entrypoint.name != "uv" or not uv_entrypoint.exists(): raise MissionCoreLaunchAgentError("Mission Core uv entrypoint is unavailable") current_repository = Path(current_working_directory) repository_migration = current_repository != repository @@ -201,6 +187,8 @@ def plan_mission_core_launch_agent( "StandardOutPath": str(log_path), "StandardErrorPath": str(log_path), } + desired = bounded_launchd_output(desired, repository, uv_path=uv_entrypoint) + desired_program_arguments = tuple(desired["ProgramArguments"]) desired_payload = plistlib.dumps(desired, fmt=plistlib.FMT_XML, sort_keys=True) return MissionCoreLaunchAgentPlan( agent_path=path, @@ -244,9 +232,7 @@ def _private_local_worker_directory(path: Path, label: str) -> Path: or stat.S_IMODE(metadata.st_mode) != 0o700 or metadata.st_uid != os.getuid() ): - raise MissionCoreLaunchAgentError( - f"{label} is not a private canonical directory" - ) + raise MissionCoreLaunchAgentError(f"{label} is not a private canonical directory") return resolved diff --git a/src/k1link/observatory/portable_replay.py b/src/k1link/observatory/portable_replay.py index b73cb4fb..b6425c64 100644 --- a/src/k1link/observatory/portable_replay.py +++ b/src/k1link/observatory/portable_replay.py @@ -18,6 +18,7 @@ from typing import Any, cast import numpy as np import rerun as rr +from k1link.cache_budget import cache_publication, require_cache_room from k1link.laboratory.canonical_rerun_overlay import ( APPLICATION_ID, CanonicalLabOverlayArtifact, @@ -198,6 +199,12 @@ class PortableReplayService: self.cache.mkdir(mode=0o700, parents=True, exist_ok=True) if self.cache.is_symlink() or shutil.disk_usage(self.cache).free < 3 * 1024**3: raise PortableReplayError("replay cache has insufficient safe space") + require_cache_room( + self.cache, + 1024**3, + kind="observatory-portable-replay-cache", + error_type=PortableReplayError, + ) with tempfile.TemporaryDirectory(prefix=".pack-", dir=self.cache) as temporary: root = Path(temporary) proxy = self._video(epoch, root) @@ -231,10 +238,16 @@ class PortableReplayService: "sha256": artifact.sha256, "byte_length": artifact.byte_length, } - staged = self.cache / f".{key}.json" - staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8") - os.chmod(staged, 0o600) - os.replace(staged, self.cache / f"{key}.json") + with cache_publication( + self.cache, + 65536, + kind="observatory-portable-replay-cache", + error_type=PortableReplayError, + ): + staged = self.cache / f".{key}.json" + staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8") + os.chmod(staged, 0o600) + os.replace(staged, self.cache / f"{key}.json") return artifact def _composition_key( @@ -381,6 +394,12 @@ class PortableReplayService: self.cache.mkdir(mode=0o700, parents=True, exist_ok=True) if self.cache.is_symlink() or shutil.disk_usage(self.cache).free < 3 * 1024**3: raise PortableReplayError("replay cache has insufficient safe space") + require_cache_room( + self.cache, + 1024**3, + kind="observatory-portable-replay-cache", + error_type=PortableReplayError, + ) with tempfile.TemporaryDirectory( prefix=".pack-composition-", dir=self.cache ) as temporary: @@ -416,10 +435,16 @@ class PortableReplayService: "sha256": artifact.sha256, "byte_length": artifact.byte_length, } - staged = self.cache / f".{key}.json" - staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8") - os.chmod(staged, 0o600) - os.replace(staged, self.cache / f"{key}.json") + with cache_publication( + self.cache, + 65536, + kind="observatory-portable-replay-cache", + error_type=PortableReplayError, + ): + staged = self.cache / f".{key}.json" + staged.write_text(json.dumps(metadata, sort_keys=True), encoding="utf-8") + os.chmod(staged, 0o600) + os.replace(staged, self.cache / f"{key}.json") return artifact def _camera(self, session_id: str, bundle: dict[str, Any]) -> RecordedMediaEpoch: @@ -519,11 +544,17 @@ class PortableReplayService: digest = hashlib.file_digest(stream, "sha256").hexdigest() metadata = {"sha256": digest, "byte_length": proxy.stat().st_size} os.chmod(proxy, 0o600) - os.replace(proxy, saved) - staged = root / "camera.json" - staged.write_text(json.dumps(metadata), encoding="utf-8") - os.chmod(staged, 0o600) - os.replace(staged, saved_manifest) + with cache_publication( + self.cache, + 65536, + kind="observatory-portable-replay-cache", + error_type=PortableReplayError, + ): + os.replace(proxy, saved) + staged = root / "camera.json" + staged.write_text(json.dumps(metadata), encoding="utf-8") + os.chmod(staged, 0o600) + os.replace(staged, saved_manifest) return saved diff --git a/src/k1link/observatory/worker_tunnel_launchd.py b/src/k1link/observatory/worker_tunnel_launchd.py index 7d0bfb00..df25cac8 100644 --- a/src/k1link/observatory/worker_tunnel_launchd.py +++ b/src/k1link/observatory/worker_tunnel_launchd.py @@ -10,14 +10,10 @@ from dataclasses import dataclass from pathlib import Path from typing import Final -from k1link.launchd_logs import launchd_log_path +from k1link.launchd_logs import bounded_launchd_output, launchd_log_path -OBSERVATORY_WORKER_TUNNEL_LABEL: Final = ( - "com.nodedc.observatory-worker-tunnel.local" -) -OBSERVATORY_WORKER_TUNNEL_SCHEMA: Final = ( - "missioncore.observatory-worker-tunnel-plan/v1" -) +OBSERVATORY_WORKER_TUNNEL_LABEL: Final = "com.nodedc.observatory-worker-tunnel.local" +OBSERVATORY_WORKER_TUNNEL_SCHEMA: Final = "missioncore.observatory-worker-tunnel-plan/v1" OBSERVATORY_WORKER_TUNNEL_PORT: Final = 18080 @@ -97,6 +93,7 @@ def plan_observatory_worker_tunnel_launch_agent( "StandardOutPath": str(log_path), "StandardErrorPath": str(log_path), } + desired = bounded_launchd_output(desired, Path(__file__).resolve().parents[3]) payload = plistlib.dumps(desired, fmt=plistlib.FMT_XML, sort_keys=True) return ObservatoryWorkerTunnelLaunchAgentPlan( agent_path=target_path, diff --git a/src/k1link/rotating_process.py b/src/k1link/rotating_process.py new file mode 100644 index 00000000..612ba638 --- /dev/null +++ b/src/k1link/rotating_process.py @@ -0,0 +1,169 @@ +"""Bounded binary stdout/stderr journal for one launchd-owned child process. + +The parent drains a pipe and owns rotation; no copy/truncate race with a writer. +It does not change the child's arguments, environment, credentials or network. +""" + +from __future__ import annotations + +import argparse +import fcntl +import os +import selectors +import signal +import stat +import subprocess +import time +from pathlib import Path + +MAX_BYTES = 8 * 1024**2 +BACKUPS = 4 + + +class Journal: + def __init__(self, path: Path, *, max_bytes=MAX_BYTES, backups=BACKUPS): + if max_bytes < 1 or not 1 <= backups <= 20: + raise ValueError("Invalid journal limits") + self.path = path.absolute() + self.max_bytes, self.backups = max_bytes, backups + self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + if self.path.parent.resolve() != self.path.parent: + raise ValueError("Journal parent is not canonical") + self.lock = self._open(self.path.with_name(self.path.name + ".lock")) + try: + fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + self.fd = self._open(self.path) + except BaseException: + os.close(self.lock) + raise + + @staticmethod + def _open(path): + fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_APPEND | os.O_NOFOLLOW, 0o600) + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid(): + os.close(fd) + raise ValueError("Journal must be an owned, unlinked regular file") + os.fchmod(fd, 0o600) + return fd + + def _rotate(self): + # Validate every managed destination before changing the rotation set. + paths = [self.path] + [Path(f"{self.path}.{i}") for i in range(1, self.backups + 1)] + for p in paths: + if p.exists() or p.is_symlink(): + s = p.lstat() + if not stat.S_ISREG(s.st_mode) or s.st_nlink != 1 or s.st_uid != os.getuid(): + raise ValueError("Unsafe journal rotation target") + named = self.path.stat() + opened = os.fstat(self.fd) + if (named.st_dev, named.st_ino) != (opened.st_dev, opened.st_ino): + raise ValueError("Journal identity changed") + os.close(self.fd) + self.fd = -1 + try: + paths[-1].unlink(missing_ok=True) + for index in range(self.backups - 1, -1, -1): + if paths[index].exists(): + os.replace(paths[index], paths[index + 1]) + finally: + self.fd = self._open(self.path) + + def write(self, payload: bytes): + view = memoryview(payload) + while view: + space = self.max_bytes - os.fstat(self.fd).st_size + if space <= 0: + self._rotate() + space = self.max_bytes + written = os.write(self.fd, view[:space]) + if written <= 0: + raise OSError("Journal write made no progress") + view = view[written:] + + def close(self): + if self.fd >= 0: + os.close(self.fd) + self.fd = -1 + if self.lock >= 0: + os.close(self.lock) + self.lock = -1 + + +def supervise(command, path: Path, *, max_bytes=MAX_BYTES, backups=BACKUPS): + journal = Journal(path, max_bytes=max_bytes, backups=backups) + child = None + previous = {} + deadline = None + dropped = 0 + try: + child = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + assert child.stdout is not None + + def stop(signum, _frame): + nonlocal deadline + if child.poll() is None: + child.send_signal(signum) + deadline = time.monotonic() + 12 + + for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP): + previous[signum] = signal.signal(signum, stop) + with selectors.DefaultSelector() as selector: + selector.register(child.stdout, selectors.EVENT_READ) + exited = None + eof = False + while True: + if deadline is not None and time.monotonic() >= deadline and child.poll() is None: + child.kill() + ready = selector.select(0.25) + if ready: + chunk = os.read(child.stdout.fileno(), 65536) + if not chunk: + selector.unregister(child.stdout) + eof = True + try: + if dropped: + journal.write( + f"\n[journal recovered; dropped {dropped} bytes]\n".encode() + ) + dropped = 0 + journal.write(chunk) + except (OSError, ValueError): + # A full/unavailable disk must not deadlock the operator service. + # The loss counter is bounded state, not an in-memory log backlog. + dropped = min(2**63 - 1, dropped + len(chunk)) + if child.poll() is not None: + if eof: + break + exited = exited or time.monotonic() + if time.monotonic() - exited >= 2: + break # A descendant must not keep a dead service's pipe alive forever. + child.stdout.close() + code = child.wait() + return code if code >= 0 else 128 - code + finally: + if child is not None and child.poll() is None: + child.terminate() + try: + child.wait(timeout=12) + except subprocess.TimeoutExpired: + child.kill() + child.wait() + for signum, handler in previous.items(): + signal.signal(signum, handler) + journal.close() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--log", type=Path, required=True) + parser.add_argument("command", nargs=argparse.REMAINDER) + args = parser.parse_args() + command = args.command[1:] if args.command[:1] == ["--"] else args.command + if not command: + parser.error("child command is required") + return supervise(command, args.log) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/k1link/sessions/camera_frame.py b/src/k1link/sessions/camera_frame.py index f0e2a020..353eb75c 100644 --- a/src/k1link/sessions/camera_frame.py +++ b/src/k1link/sessions/camera_frame.py @@ -10,6 +10,8 @@ from contextlib import suppress from dataclasses import dataclass from pathlib import Path +from k1link.cache_budget import CacheCapacityError, cache_publication + from .media import RecordedMediaEpoch, RecordedMediaInspector, RecordedMediaManifest from .models import SessionIntegrityError from .store import SessionStore @@ -133,7 +135,14 @@ class RecordedCameraFrameService: return cached self._require_latest(lane, ticket) frame = self._decode(manifest, epoch, sequence) - _publish_cached_jpeg(cache_path, frame.payload) + try: + with cache_publication( + self._cache_root, len(frame.payload), kind="camera-frame-cache" + ): + _publish_cached_jpeg(cache_path, frame.payload) + except CacheCapacityError: + # The validated decoded frame is still usable without a disk copy. + pass self._require_latest(lane, ticket) return frame finally: diff --git a/src/k1link/sessions/media.py b/src/k1link/sessions/media.py index 6f5a0e3b..decb818d 100644 --- a/src/k1link/sessions/media.py +++ b/src/k1link/sessions/media.py @@ -15,6 +15,7 @@ from pathlib import Path from typing import Any, TypeGuard from k1link import media_fragments as _fragment_timing +from k1link.cache_budget import CacheCapacityError, cache_publication from .models import RecordedMediaArtifact, ReplayCommand, SessionIntegrityError @@ -255,11 +256,15 @@ class RecordedMediaInspector: if root is None: return payload = _encode_prepared_sidecar(manifest, identity) - _write_sidecar_atomic( - root, - _sidecar_name(manifest.session_id, manifest.artifact_id), - payload, - ) + try: + with cache_publication(root, len(payload), kind="camera-media-index"): + _write_sidecar_atomic( + root, + _sidecar_name(manifest.session_id, manifest.artifact_id), + payload, + ) + except CacheCapacityError: + pass def get_prepared( self, diff --git a/src/k1link/simulation/ai_polygon/editor_cache.py b/src/k1link/simulation/ai_polygon/editor_cache.py index 90d54555..7be3919d 100644 --- a/src/k1link/simulation/ai_polygon/editor_cache.py +++ b/src/k1link/simulation/ai_polygon/editor_cache.py @@ -8,6 +8,7 @@ import shutil import threading from pathlib import Path +from k1link.cache_budget import cache_publication from k1link.simulation.ai_polygon.plans import PlanStore from k1link.simulation.ai_polygon.worlds import write_json @@ -75,7 +76,8 @@ class EditorCache: else: if shutil.disk_usage(self.root).free < LIMIT + 512 * 1024**2: raise ValueError("Недостаточно места для локальной копии сцены.") - path.mkdir(mode=0o700, exist_ok=True) + with cache_publication(self.root, 65536, kind="editor-cache", max_files=4096): + path.mkdir(mode=0o700, exist_ok=True) row = { "key": key, "identity": identity, @@ -85,9 +87,13 @@ class EditorCache: "error": None, } if world.get("local_scene"): - row.update(status="ready", files=self.worlds.projects.cache_files(world), - local_scene=world["local_scene"]) - write_json(path / "manifest.json", row) + row.update( + status="ready", + files=self.worlds.projects.cache_files(world), + local_scene=world["local_scene"], + ) + with cache_publication(self.root, 65536, kind="editor-cache", max_files=4096): + write_json(path / "manifest.json", row) return row def pending(self): @@ -137,7 +143,20 @@ class EditorCache: and files["collision.glb"]["sha256"] != row["identity"]["collider_sha256"] ): raise ValueError("Collider identity mismatch") - row.update(files=files, status="uploading") + # Reserve all declared remaining transfers in the existing manifests. + # No extra reservation files or abandoned-expiry deletion are needed. + remaining = sum(a["byte_length"] for a in files.values()) - sum( + a.get("uploaded_bytes", 0) for a in row.get("files", {}).values() + ) + with cache_publication( + self.root, + self._pending_bytes(exclude=key) + remaining + 65536, + kind="editor-cache", + max_files=4096, + ): + row.update(files=files, status="uploading") + write_json(path / "manifest.json", row) + return self.get(key) elif action == "chunk": name = body.get("name") if name not in FILES or name not in row["files"] or row["status"] != "uploading": @@ -154,7 +173,15 @@ class EditorCache: raise ValueError("Invalid editor chunk") if shutil.disk_usage(path).free < len(payload) + 512 * 1024**2: raise ValueError("Недостаточно места для сцены.") - with (path / (name + ".part")).open("ab") as stream: + with ( + cache_publication( + self.root, + self._pending_bytes() + 65536, + kind="editor-cache", + max_files=4096, + ), + (path / (name + ".part")).open("ab") as stream, + ): stream.write(payload) elif action == "complete": for name, asset in row["files"].items(): @@ -180,6 +207,20 @@ class EditorCache: write_json(path / "manifest.json", row) return self.get(key) + def _pending_bytes(self, exclude=None): + remaining = 0 + for manifest in self.root.glob("*/manifest.json"): + if manifest.parent.name == exclude: + continue + row = self.get(manifest.parent.name) + if row.get("local_scene") or row["status"] not in {"queued", "preparing", "uploading"}: + continue + remaining += sum( + max(0, a["byte_length"] - a.get("uploaded_bytes", 0)) + for a in row.get("files", {}).values() + ) + return remaining + def asset(self, key, name): row = self.get(key) if row["status"] != "ready" or name not in FILES: diff --git a/src/k1link/web/lidar_local_surface_service.py b/src/k1link/web/lidar_local_surface_service.py index da82a9e1..2ac25621 100644 --- a/src/k1link/web/lidar_local_surface_service.py +++ b/src/k1link/web/lidar_local_surface_service.py @@ -13,6 +13,7 @@ from pathlib import Path from typing import Final from uuid import uuid4 +from k1link.cache_budget import CacheCapacityError, cache_publication from k1link.compute.lidar_field_review import E10LidarFieldSource from k1link.compute.lidar_ground import LidarGroundError from k1link.compute.lidar_local_surface import ( @@ -68,9 +69,7 @@ class K1LocalSurfaceReadService: ) -> None: if max_entries < 1: raise ValueError("LiDAR reader cache must retain at least one entry") - self.cache_root = ( - cache_root.expanduser().absolute() if cache_root is not None else None - ) + self.cache_root = cache_root.expanduser().absolute() if cache_root is not None else None self.max_entries = max_entries self._lock = threading.RLock() self._models: OrderedDict[Path, _ModelEntry] = OrderedDict() @@ -124,10 +123,7 @@ class K1LocalSurfaceReadService: ) -> tuple[K1LocalSurfaceV1, E10LidarFieldSource]: model = self._model(model_path) source_pack_id = model.identity.get("source_pack_id") - if ( - not isinstance(source_pack_id, str) - or _E10_PACK_ID.fullmatch(source_pack_id) is None - ): + if not isinstance(source_pack_id, str) or _E10_PACK_ID.fullmatch(source_pack_id) is None: raise LidarGroundError("K1 local-surface source id is invalid") source_path = source_root / source_pack_id if not source_path.is_dir(): @@ -254,19 +250,23 @@ class K1LocalSurfaceReadService: separators=(",", ":"), sort_keys=True, ).encode("utf-8") - descriptor = os.open( - temporary, - os.O_WRONLY | os.O_CREAT | os.O_EXCL, - 0o600, - ) try: - with os.fdopen(descriptor, "wb") as stream: - stream.write(payload) - stream.flush() - os.fsync(stream.fileno()) - os.replace(temporary, destination) - finally: - temporary.unlink(missing_ok=True) + with cache_publication(root, len(payload), kind="lidar-read-cache"): + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_EXCL, + 0o600, + ) + try: + with os.fdopen(descriptor, "wb") as stream: + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, destination) + finally: + temporary.unlink(missing_ok=True) + except CacheCapacityError: + return def _evict_models(self) -> None: while len(self._models) > self.max_entries: diff --git a/src/k1link/web/runtime_diagnostics.py b/src/k1link/web/runtime_diagnostics.py index 70431f57..7c72a154 100644 --- a/src/k1link/web/runtime_diagnostics.py +++ b/src/k1link/web/runtime_diagnostics.py @@ -3,6 +3,7 @@ from __future__ import annotations import json import logging import os +import stat from datetime import UTC, datetime from logging.handlers import RotatingFileHandler from pathlib import Path @@ -116,7 +117,7 @@ class ScannerDiagnosticJsonFormatter(logging.Formatter): for field in _EXTRA_FIELDS: value = getattr(record, field, None) if value is not None and isinstance(value, (str, int, bool)): - document[field] = value + document[field] = value[:256] if isinstance(value, str) else value if record.exc_info is not None: exception_type, _exception, traceback = record.exc_info if exception_type is not None: @@ -137,7 +138,28 @@ class ScannerDiagnosticJsonFormatter(logging.Formatter): for value in properties ): document["write_characteristic_properties"] = sorted(set(properties)) - return json.dumps(document, ensure_ascii=False, separators=(",", ":")) + payload = json.dumps(document, ensure_ascii=False, separators=(",", ":")) + # An oversized extra field cannot bypass the rotation budget in one record. + for field in reversed(_EXTRA_FIELDS): + if len(payload.encode("utf-8")) <= 16384: + break + document.pop(field, None) + document["fields_omitted"] = True + payload = json.dumps(document, ensure_ascii=False, separators=(",", ":")) + return payload + + +class PrivateRotatingFileHandler(RotatingFileHandler): + def _open(self): + descriptor = os.open( + self.baseFilename, os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600 + ) + info = os.fstat(descriptor) + if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_uid != os.getuid(): + os.close(descriptor) + raise ValueError("Invalid diagnostic journal") + os.fchmod(descriptor, 0o600) + return os.fdopen(descriptor, "a", encoding=self.encoding, errors=self.errors) def configure_scanner_diagnostics(logs_root: Path) -> Path: @@ -151,7 +173,7 @@ def configure_scanner_diagnostics(logs_root: Path) -> Path: if getattr(handler, _HANDLER_MARKER, None) == str(target): return target - handler = RotatingFileHandler( + handler = PrivateRotatingFileHandler( target, maxBytes=5 * 1024 * 1024, backupCount=5, diff --git a/tests/test_build_retention.py b/tests/test_build_retention.py new file mode 100644 index 00000000..8aada2a9 --- /dev/null +++ b/tests/test_build_retention.py @@ -0,0 +1,476 @@ +"""Lifecycle, dependency and failure acceptance for local intermediate retention.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import zipfile +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from unittest.mock import patch + +import pytest + +MODULE = Path(__file__).resolve().parents[1] / "scripts/packaging/build_retention.py" +spec = importlib.util.spec_from_file_location("build_retention", MODULE) +retention = importlib.util.module_from_spec(spec) +spec.loader.exec_module(retention) +Store = retention.BuildRetention +Error = retention.RetentionError +NODE = "apps/node-agent/build" +X4 = "plugins/insta360-x4/build" + + +@pytest.fixture +def store(tmp_path): + for directory in (NODE, X4): + (tmp_path / directory).mkdir(parents=True) + return Store(tmp_path) + + +def content(index, *, line="node/node-only", base=None): + if line.startswith("node/"): + manifest = { + "schema": "missioncore.node.linux-build-source/v1", + "profile": line.split("/")[1], + } + directory, prefix, member = NODE, "mission-core-node-linux-build", "source.json" + elif line == "x4/owner": + manifest = {"schema": "missioncore.insta360.owner-wrapper-build/v1"} + directory, prefix, member = X4, "mission-core-x4-owner-build", "manifest.json" + else: + kind = line.split("/")[1] + manifest = {"schema": "missioncore.insta360.build-source/v1"} + if kind == "package": + manifest["kind"] = kind + directory, prefix, member = ( + X4, + "mission-core-x4-" + ("package-" if kind == "package" else "") + "build", + "source.json", + ) + manifest["test_nonce"] = index + if base: + manifest["base"] = base + raw = json.dumps(manifest).encode() + relative = f"{directory}/{prefix}-{hashlib.sha256(raw).hexdigest()[:24]}.pyz" + return relative, member, raw + + +def make(store, index, *, line="node/node-only", base=None, managed=True, outcome="intermediate"): + relative, member, raw = content(index, line=line, base=base) + output = store.root / relative + if managed: + with ( + store.publish(output, required_bytes=1024) as temporary, + zipfile.ZipFile(temporary, "x") as archive, + ): + archive.writestr(member, raw) + owner = store._state()["inputs"][relative]["owner"] + if outcome: + store.finish(relative, owner=owner, outcome=outcome, reason="test outcome") + else: + with zipfile.ZipFile(output, "x") as archive: + archive.writestr(member, raw) + return relative + + +def actions(store): + plan = store.plan() + assert not plan["errors"], plan["errors"] + return {x["path"]: x["action"] for x in plan["inputs"]} + + +def base_ref(store, relative): + return { + "name": Path(relative).name, + "sha256": hashlib.sha256((store.root / relative).read_bytes()).hexdigest(), + } + + +def test_plan_is_read_only_and_legacy_is_protected(store): + old = make(store, 1, managed=False) + assert actions(store)[old] == "retain" + assert not store.control.exists() + plan = store.plan() + receipt = store.apply(plan) + assert receipt["removed"] == [] and (store.root / old).exists() + + +def test_two_completed_per_independent_line(store): + names = {} + for line in ("node/node-only", "node/node-core", "x4/native", "x4/package", "x4/owner"): + names[line] = [make(store, i, line=line) for i in range(4)] + plan = store.plan() + assert sum(x["action"] == "delete" for x in plan["inputs"]) == 10 + receipt = store.apply(plan) + assert len(receipt["removed"]) == 10 + for line in names: + assert [(store.root / n).exists() for n in names[line]] == [False, False, True, True] + assert store.apply(store.plan())["removed"] == [] + + +def test_transitive_base_closure_keeps_exact_old_bytes(store): + base = make(store, 0) + delta = make(store, 1, base=base_ref(store, base)) + tail = make(store, 2, base=base_ref(store, delta)) + make(store, 3) + assert all(actions(store)[n] == "retain" for n in (base, delta, tail)) + store.apply(store.plan()) + assert not store.plan()["errors"] + + +@pytest.mark.parametrize("outcome", ["qualified", "rollback"]) +def test_pins_are_extra_to_two_intermediates_and_need_explicit_release(store, outcome): + pin = make(store, 0, outcome=outcome) + normal = [make(store, i) for i in range(1, 4)] + assert actions(store)[pin] == "retain" + assert actions(store)[normal[0]] == "delete" + plan = store.plan() + store.pin(normal[0], pin="external-release", reason="qualified externally") + with pytest.raises(Error, match="Stale"): + store.apply(plan) + store.pin(pin, pin=outcome, reason="explicit retirement", remove=True) + assert actions(store)[pin] == "delete" + + +@pytest.mark.parametrize("outcome", ["intermediate", "failed", "cancelled"]) +def test_active_owner_survives_restarts_until_explicit_terminal_result(store, outcome): + active = make(store, 0, outcome=None) + for i in range(1, 4): + make(store, i) + restarted = Store(store.root) + assert actions(restarted)[active] == "retain" + with pytest.raises(Error, match="owner"): + restarted.finish(active, owner="wrong", outcome=outcome, reason="done") + owner = restarted._state()["inputs"][active]["owner"] + restarted.finish(active, owner=owner, outcome=outcome, reason="confirmed terminal") + assert actions(restarted)[active] == "delete" + + +def test_legacy_adoption_cannot_silently_make_data_disposable(store): + old = make(store, 0, managed=False) + store.adopt(old, pin="legacy-review", reason="unique provenance") + for i in range(1, 4): + make(store, i) + assert actions(store)[old] == "retain" + store.pin(old, pin="legacy-review", remove=True, reason="confirmed intermediate only") + assert actions(store)[old] == "delete" + + +def test_unknown_releases_evidence_and_noninput_files_never_selected(store): + protected = [ + ".runtime/mission-core/recordings/evidence.pyz", + "private/releases/a.pyz", + NODE + "/mission-core-node-install-" + "f" * 24 + ".pyz", + NODE + "/qualified/result.json", + X4 + "/sdk/unique.zip", + ] + for n in protected: + path = store.root / n + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"unique") + for i in range(3): + make(store, i) + store.apply(store.plan()) + assert all((store.root / n).read_bytes() == b"unique" for n in protected) + + +@pytest.mark.parametrize("mutation", ["bytes", "new-input", "edited-plan", "pin"]) +def test_stale_plan_rejected_before_any_unlink(store, mutation): + names = [make(store, i) for i in range(4)] + plan = store.plan() + if mutation == "bytes": + with (store.root / names[0]).open("ab") as stream: + stream.write(b"changed") + elif mutation == "new-input": + make(store, 5, managed=False) + elif mutation == "edited-plan": + plan["inputs"][0]["action"] = "surprise" + else: + store.pin(names[0], pin="new-release", reason="new qualification") + with pytest.raises(Error, match="Stale"): + store.apply(plan) + assert all((store.root / n).exists() for n in names) + + +def test_symlink_and_path_escape_fail_closed(store, tmp_path): + names = [make(store, i) for i in range(3)] + path = store.root / names[0] + path.unlink() + path.symlink_to(store.root / names[1]) + plan = store.plan() + assert plan["errors"] and all(x["action"] == "retain" for x in plan["inputs"]) + with pytest.raises(Error, match="errors"): + store.apply(plan) + for name in ("../outside.pyz", "/tmp/a.pyz", ".runtime/mission-core/a.pyz"): + with pytest.raises(Error): + store._path(name) + shutil.rmtree(store.root / X4) + (store.root / X4).symlink_to(store.root / NODE, target_is_directory=True) + assert store.plan()["errors"] + + +def test_changed_base_and_malformed_archive_block_all_deletions(store): + base = make(store, 0) + make(store, 1, base=base_ref(store, base)) + for i in range(2, 5): + make(store, i) + with (store.root / base).open("ab") as f: + f.write(b"corrupt") + plan = store.plan() + assert any("base" in x for x in plan["errors"]) + assert all(x["action"] == "retain" for x in plan["inputs"]) + bad = store.root / NODE / "mission-core-node-linux-build-notanid.pyz" + bad.write_bytes(b"incomplete") + assert any("notanid" in x for x in store.plan()["errors"]) + + +def test_failed_publication_removes_only_own_temporary(store): + relative, _, _ = content(0) + before = set((store.root / NODE).iterdir()) + with pytest.raises(ValueError), store.publish(store.root / relative) as temporary: + temporary.write_bytes(b"partial") + raise ValueError("compiler failed") + assert set((store.root / NODE).iterdir()) == before + assert not store._state()["inputs"] + + +def test_publication_rejects_missing_base_without_exposing_archive(store): + relative, member, raw = content( + 1, base={"name": "mission-core-node-linux-build-" + "a" * 24 + ".pyz", "sha256": "b" * 64} + ) + with ( + pytest.raises(FileNotFoundError), + store.publish(store.root / relative) as temporary, + zipfile.ZipFile(temporary, "x") as z, + ): + z.writestr(member, raw) + assert not (store.root / relative).exists() + assert not list((store.root / NODE).glob(".retention-*")) + + +def test_capacity_refusal_preserves_all_inputs(store): + for i in range(8): + make(store, i, outcome=None) + relative, _, _ = content(8) + with pytest.raises(Error, match="unfinished"), store.publish(store.root / relative): + pytest.fail("must not start") + disk = shutil.disk_usage(store.root) + with patch.object( + retention.shutil, "disk_usage", return_value=type(disk)(disk.total, disk.used, 0) + ): + other, _, _ = content(0, line="x4/native") + with pytest.raises(Error, match="space"), store.publish(store.root / other): + pytest.fail("must not start") + assert len(store.plan()["inputs"]) == 8 + + +def test_concurrent_publications_have_distinct_persistent_owners(store): + with ThreadPoolExecutor(max_workers=2) as pool: + names = list(pool.map(lambda i: make(store, i, outcome=None), range(2))) + state = store._state() + assert len({state["inputs"][n]["owner"] for n in names}) == 2 + assert not store.plan()["errors"] + + +def test_unlink_failure_is_journaled_and_remaining_graph_is_valid(store): + base = make(store, 0) + delta = make(store, 1, base=base_ref(store, base)) + make(store, 2) + make(store, 3) + unlink = Path.unlink + + def fail(path, *args, **kwargs): + if str(path) == str(store.root / base): + raise OSError("simulated busy storage") + return unlink(path, *args, **kwargs) + + with patch.object(Path, "unlink", fail), pytest.raises(OSError, match="simulated"): + store.apply(store.plan()) + assert not (store.root / delta).exists() and (store.root / base).exists() + receipt_path = next((store.control / "receipts").glob("*.json")) + receipt = json.loads(receipt_path.read_text()) + assert receipt["status"] == "interrupted" and receipt["removed"][0]["path"] == delta + assert not store.plan()["errors"] + assert store.recover(receipt_path.name)["deleted_now"] == 0 + store.apply(store.plan()) + assert not (store.root / base).exists() + + +def test_recover_crash_between_unlink_and_registry_commit(store): + old = make(store, 0) + make(store, 1) + make(store, 2) + with ( + patch.object(store, "_save", side_effect=OSError("simulated state write failure")), + pytest.raises(OSError, match="state write"), + ): + store.apply(store.plan()) + assert not (store.root / old).exists() and store.plan()["errors"] + receipt_path = next((store.control / "receipts").glob("*.json")) + result = store.recover(receipt_path.name) + assert result["recovered_missing"] == [old] and result["deleted_now"] == 0 + assert not store.plan()["errors"] + + +def test_hardlinked_other_copy_survives_and_bytes_are_only_upper_bound(store): + old = make(store, 0) + other = store.root / "rollback-copy.pyz" + os.link(store.root / old, other) + expected = other.read_bytes() + make(store, 1) + make(store, 2) + assert store.plan()["candidate_bytes_upper_bound"] == len(expected) + store.apply(store.plan()) + assert other.read_bytes() == expected + + +def load_producer(relative, monkeypatch): + source = MODULE.parents[2] / relative + monkeypatch.syspath_prepend(str(source.parent)) + module_spec = importlib.util.spec_from_file_location("producer_" + source.stem, source) + module = importlib.util.module_from_spec(module_spec) + module_spec.loader.exec_module(module) + return module + + +def producer_hooks(module, store, monkeypatch): + monkeypatch.setattr(module, "publish_input", store.publish) + + def hold(output): + relative = str(output.relative_to(store.root)) + return {"owner": store._state()["inputs"][relative]["owner"], "path": relative} + + monkeypatch.setattr(module, "input_hold", hold) + + +@pytest.mark.parametrize("kind", ["native", "package", "owner", "node"]) +def test_actual_producers_publish_valid_archives_and_active_holds(store, monkeypatch, capsys, kind): + # Exercise the real producer wrappers with tiny synthetic inputs. No SDK execution, + # compiler, board, network or production build is involved. + def write(name, data=b"fixture"): + path = store.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return path + + def document(name, data): + return write(name, json.dumps(data).encode()) + + xroot = store.root / "plugins/insta360-x4" + nroot = store.root / "apps/node-agent" + for name in ("bridge.cpp", "bridge.h", "tests/fake_sdk.cpp", "tests/check_abi.py"): + write("plugins/insta360-x4/native/" + name) + for name in ( + "build_native.py", + "build_native_entry.py", + "native_build_entry.py", + "fetch_sdk.py", + "install", + "install_release.py", + "owner_release_entry.py", + "build_owner_release.py", + "preinst", + "postinst", + "prerm", + "postrm", + ): + write("plugins/insta360-x4/packaging/" + name) + lock = document("plugins/insta360-x4/packaging/sdk-lock.json", {"files": []}) + if kind == "native": + module = load_producer( + "plugins/insta360-x4/packaging/build_source_artifact.py", monkeypatch + ) + monkeypatch.setattr(module, "ROOT", xroot) + monkeypatch.setattr(module, "LOCK", lock) + monkeypatch.setattr(module, "verify", lambda *args: None) + elif kind == "package": + module = load_producer( + "plugins/insta360-x4/packaging/build_package_artifact.py", monkeypatch + ) + monkeypatch.setattr(module, "ROOT", xroot) + monkeypatch.setattr(module, "REPOSITORY", store.root) + monkeypatch.setattr(module, "verify", lambda *args: None) + document("plugins/insta360-x4/packaging/python-lock.json", {"wheels": []}) + for name in ("libmissioncore_x4.so", "provenance.json"): + write("plugins/insta360-x4/build/native/" + name) + for name in ( + "scripts/packaging/debian.py", + "apps/node-agent/packaging/insta360_profile.py", + "apps/node-agent/packaging/install_owner_release.py", + "apps/node-agent/packaging/can_maintenance.py", + "apps/node-agent/packaging/vesc_hall_recovery.py", + "src/k1link/__init__.py", + "src/k1link/fleet/__init__.py", + "src/k1link/fleet/sensors.py", + "src/k1link/fleet/trust.py", + ): + write(name) + elif kind == "owner": + module = load_producer("plugins/insta360-x4/packaging/build_owner_builder.py", monkeypatch) + monkeypatch.setattr(module, "ROOT", xroot) + report = document( + "qualified-report.json", {"sha256": "f" * 64, "bytes": 0, "file": "qualified.deb"} + ) + else: + module = load_producer("apps/node-agent/packaging/build_linux_source.py", monkeypatch) + monkeypatch.setattr(module, "NODE", nroot) + monkeypatch.setattr(module, "REPO", store.root) + # DG stays inside this tiny fixture; no duplicate source checkout. + dg = store.root / "design-fixture" + monkeypatch.setattr(module, "DG", dg) + for name in ( + "package.json", + "package-lock.json", + "tsconfig.base.json", + "apps/catalog/package.json", + ): + write("design-fixture/" + name) + monkeypatch.setattr(module, "files", lambda root: []) + monkeypatch.setattr( + module.subprocess, "check_output", lambda *args, **kwargs: module.DG_COMMIT + ) + document("apps/node-agent/packaging/linux-toolchains.json", {"files": []}) + document("apps/node-agent/packaging/realsense-bundle.json", {"wheels": []}) + package = write("mission-core-insta360-x4_0.1.0_amd64.deb") + digest = hashlib.sha256(package.read_bytes()).hexdigest() + document( + "apps/node-agent/packaging/insta360-profile.json", + {"version": "0.1.0", "bytes": 7, "sha256": digest}, + ) + write("plugins/vesc/build/native-runtime/native.so") + document( + "plugins/vesc/packaging/native-runtime.json", + {"file": "native.so", "bytes": 7, "sha256": digest}, + ) + document("plugins/vesc/packaging/firmware-catalog.json", {"items": []}) + write("plugins/vesc/build/package-catalog/vesc_pkg_all.rcc") + document("plugins/vesc/packaging/package-catalog.json", {"bytes": 7, "sha256": digest}) + write("plugins/usb-can/build/sdk/libcontrolcanfd.so") + monkeypatch.setattr(module, "USB_CAN_SDK_SHA256", digest) + write("apps/node-agent/packaging/linux_build_entry.py") + producer_hooks(module, store, monkeypatch) + if kind == "node": + result = module.build(package, node_only=True) + elif kind == "owner": + module.build(report) + result = json.loads(capsys.readouterr().out) + else: + result = module.build() + path = Path(result["artifact"]) + assert path.exists() and result["sha256"] == hashlib.sha256(path.read_bytes()).hexdigest() + owner = result["retention"]["owner"] + record = store._state()["inputs"][str(path.relative_to(store.root))] + assert record["state"] == "active" and record["owner"] == owner + assert not store.plan()["errors"] and not list(path.parent.glob(".retention-*")) + + +def test_late_legacy_adoption_does_not_make_an_old_input_newest(store): + old = make(store, 0, managed=False) + os.utime(store.root / old, ns=(1_000_000_000, 1_000_000_000)) + for i in range(1, 4): + make(store, i) + store.adopt(old, pin="review", reason="legacy record") + store.pin(old, pin="review", reason="confirmed obsolete intermediate", remove=True) + assert actions(store)[old] == "delete" diff --git a/tests/test_cache_budget.py b/tests/test_cache_budget.py new file mode 100644 index 00000000..3c413ffd --- /dev/null +++ b/tests/test_cache_budget.py @@ -0,0 +1,111 @@ +import hashlib +from types import SimpleNamespace + +import pytest + +from k1link import cache_budget as budget + + +def test_quota_preserves_unknown_existing_and_counts_pending_files(tmp_path): + root = tmp_path / "cache" + root.mkdir() + (root / "unknown-result").write_bytes(b"evidence") + (root / ".ongoing.tmp").write_bytes(b"x" * 4) + with ( + pytest.raises(budget.CacheCapacityError), + budget.cache_publication(root, 5, limit=16, reserve=0), + ): + pytest.fail("admitted over quota") + assert (root / "unknown-result").read_bytes() == b"evidence" + assert (root / ".ongoing.tmp").read_bytes() == b"x" * 4 + with budget.cache_publication(root, 4, limit=16, reserve=0): + (root / "new").write_bytes(b"y" * 4) + assert budget.usage(root) == (16, 3) + with pytest.raises(budget.CacheCapacityError): + budget.require_cache_room(root, 1, limit=16, reserve=0) + + +def test_quota_free_reserve_and_unsafe_paths(tmp_path, monkeypatch): + monkeypatch.setattr(budget.shutil, "disk_usage", lambda _: SimpleNamespace(free=10)) + with pytest.raises(budget.CacheCapacityError): + budget.require_cache_room(tmp_path / "cache", 1, limit=100, reserve=10) + root = tmp_path / "unsafe" + root.mkdir() + outside = tmp_path / "source" + outside.write_text("keep") + (root / "data").symlink_to(outside) + with pytest.raises(budget.CacheCapacityError): + budget.require_cache_room(root, 0, limit=100, reserve=0) + assert outside.read_text() == "keep" + + +def test_quota_serializes_process_publications(tmp_path): + import subprocess + import sys + + script = """from pathlib import Path +from k1link.cache_budget import cache_publication,CacheCapacityError +import sys,time +try: + with cache_publication(Path(sys.argv[1]),6,limit=10,reserve=0): + time.sleep(.1) + (Path(sys.argv[1])/sys.argv[2]).write_bytes(b"123456") +except CacheCapacityError:sys.exit(2) +""" + commands = [[sys.executable, "-c", script, str(tmp_path), str(i)] for i in range(2)] + children = [subprocess.Popen(c) for c in commands] + assert sorted(p.wait(timeout=10) for p in children) == [0, 2] + assert budget.usage(tmp_path)[0] == 6 + + +def test_editor_reserves_full_pending_transfers_and_keeps_ready_on_quota(tmp_path, monkeypatch): + from k1link.simulation.ai_polygon.editor_cache import EditorCache + + worlds = { + str(i): { + "world_id": str(i), + "sha256": str(i) * 64, + "status": "available", + "settings": {"prepared": True}, + } + for i in (1, 2) + } + cache = EditorCache(tmp_path, SimpleNamespace(get=lambda key: worlds[key])) + rows = [cache.request(str(i)) for i in (1, 2)] + payload = b"a" * 8 + files = { + n: {"byte_length": len(payload), "sha256": hashlib.sha256(payload).hexdigest()} + for n in ("scene.sog", "collision.glb") + } + before = budget.usage(cache.root)[0] + monkeypatch.setitem(budget.LIMITS, "editor-cache", before + 65536 + 30) + cache.update(rows[0]["key"], {"action": "manifest", "files": files}) + # Second transfer cannot consume bytes already promised to the first. + with pytest.raises(budget.CacheCapacityError): + cache.update(rows[1]["key"], {"action": "manifest", "files": files}) + assert cache.get(rows[0]["key"])["status"] == "uploading" + assert cache.get(rows[1]["key"])["status"] == "queued" + + +def test_camera_cache_capacity_does_not_fail_decoded_frame(tmp_path, monkeypatch): + # Exercise the actual extraction path, replacing only immutable media decoding. + import threading + from collections import OrderedDict + + from k1link.sessions.camera_frame import RecordedCameraFrame, RecordedCameraFrameService + + service = RecordedCameraFrameService.__new__(RecordedCameraFrameService) + service._cache_root = tmp_path + service._coordination = threading.Condition() + service._lanes = OrderedDict() + service._max_decode_lanes = 1 + segment = SimpleNamespace(sha256="f" * 64) + manifest = SimpleNamespace( + generation_sha256="g", artifact_id="a", epochs=[SimpleNamespace(segments=[segment])] + ) + monkeypatch.setattr(service, "_source_manifest", lambda *a, **k: manifest) + frame = RecordedCameraFrame(b"0123456789", "image/jpeg", 1, 1, "x") + monkeypatch.setattr(service, "_decode", lambda *a: frame) + monkeypatch.setitem(budget.LIMITS, "camera-frame-cache", 5) + assert service.extract("s", 0) == frame + assert not list(tmp_path.glob("*.jpg")) diff --git a/tests/test_e10_integrated_perception.py b/tests/test_e10_integrated_perception.py index 61e03aaf..8f3491b6 100644 --- a/tests/test_e10_integrated_perception.py +++ b/tests/test_e10_integrated_perception.py @@ -753,3 +753,51 @@ def test_e10_projection_keeps_only_nearest_point_per_pixel() -> None: assert pixels.shape == (1, 2) assert depths.tolist() == [2.0] assert source.tolist() == [0] + + +def test_sealed_overlay_still_recovers_when_cache_is_over_quota(tmp_path, monkeypatch): + from k1link.cache_budget import LIMITS + + roots = [tmp_path / name for name in ("jobs", "results", "lidar")] + for root in roots: + root.mkdir() + result = _write_result_descriptor( + roots[1], session_id="session-1", created_at_utc="2026-07-29T12:00:00Z" + ) + cache_root = tmp_path / "cache" + cached = cache_root / "session-1" / result.name + cached.mkdir(parents=True) + output = cached / "recording-1.rrd" + payload = b"RRF2sealed-overlay" + output.write_bytes(payload) + (cached / "recording-1.rrd.cache.json").write_text( + json.dumps( + { + "schema_version": integrated_module.OVERLAY_CACHE_SCHEMA, + "renderer_version": integrated_module.OVERLAY_RENDERER_VERSION, + "result_id": result.name, + "recording_id": "recording-1", + "byte_length": len(payload), + "sha256": hashlib.sha256(payload).hexdigest(), + } + ) + ) + monkeypatch.setitem(LIMITS, "integrated-perception-overlays", 1) + monkeypatch.setattr( + integrated_module, + "validate_integrated_perception_result", + lambda *a, **k: pytest.fail("must reuse sealed evidence"), + ) + store = IntegratedPerceptionOverlayStore( + jobs_root=roots[0], + results_root=roots[1], + lidar_packs_root=roots[2], + cache_root=cache_root, + ffmpeg_path=tmp_path / "ffmpeg", + ) + result = store.materialize( + "session-1", application_id="nodedc_mission_core_recorded", recording_id="recording-1" + ) + assert result.path == output.resolve() + assert output.read_bytes() == payload + assert not (cache_root / "session-1" / "admission.json").exists() diff --git a/tests/test_local_service_launchd.py b/tests/test_local_service_launchd.py index 0e8df045..86a07c38 100644 --- a/tests/test_local_service_launchd.py +++ b/tests/test_local_service_launchd.py @@ -5,6 +5,7 @@ from pathlib import Path import pytest +from k1link.launchd_logs import service_command, service_log_path from k1link.local_service_launchd import ( MissionCoreLaunchAgentError, plan_mission_core_launch_agent, @@ -46,13 +47,16 @@ def test_launch_agent_plan_disables_sync_and_enables_watchdog(tmp_path: Path) -> ) desired = plistlib.loads(plan.desired_payload) - assert desired["ProgramArguments"] == [ + assert service_command(desired) == [ str(uv_entrypoint), "run", "--no-sync", "k1link", "serve", ] + assert "k1link.rotating_process" in desired["ProgramArguments"] + assert service_log_path(desired).name == "k1link-serve-launchd.managed.log" + assert desired["StandardOutPath"] == desired["StandardErrorPath"] == "/dev/null" assert desired["EnvironmentVariables"]["MISSIONCORE_SERVICE_WATCHDOG"] == "1" assert desired["KeepAlive"] is True assert desired["RunAtLoad"] is True @@ -267,10 +271,7 @@ def test_launch_agent_migration_retains_existing_private_data_directory( desired = plistlib.loads(plan.desired_payload) assert plan.preserved_data_directory == configured_data_directory - assert ( - desired["EnvironmentVariables"]["MISSIONCORE_DATA_DIR"] - == str(configured_data_directory) - ) + assert desired["EnvironmentVariables"]["MISSIONCORE_DATA_DIR"] == str(configured_data_directory) def test_launch_agent_migration_rejects_symlinked_data_directory(tmp_path: Path) -> None: diff --git a/tests/test_rotating_process.py b/tests/test_rotating_process.py new file mode 100644 index 00000000..4122d9b8 --- /dev/null +++ b/tests/test_rotating_process.py @@ -0,0 +1,133 @@ +import signal +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +from k1link.launchd_logs import bounded_launchd_output, service_command, service_log_path +from k1link.rotating_process import Journal, supervise + + +def retained(path, backups): + return b"".join( + p.read_bytes() + for p in [Path(f"{path}.{i}") for i in range(backups, 0, -1)] + [path] + if p.exists() + ) + + +def test_binary_rotation_is_exact_and_bounded_across_restart(tmp_path): + p = tmp_path / "test.log" + j = Journal(p, max_bytes=7, backups=2) + j.write(bytes(range(21))) + j.close() + assert retained(p, 2) == bytes(range(21)) + j = Journal(p, max_bytes=7, backups=2) + j.write(bytes(range(21, 35))) + j.close() + assert retained(p, 2) == bytes(range(14, 35)) + assert all(x.stat().st_size <= 7 for x in tmp_path.glob("test.log*") if x.suffix != ".lock") + + +def test_journal_owns_writer_and_refuses_linked_targets(tmp_path): + p = tmp_path / "test.log" + j = Journal(p, max_bytes=4, backups=1) + with pytest.raises(BlockingIOError): + Journal(p, max_bytes=4, backups=1) + outside = tmp_path / "restore" + outside.write_bytes(b"preserve") + Path(f"{p}.1").symlink_to(outside) + j.write(b"1234") + with pytest.raises(ValueError): + j.write(b"5") + j.close() + assert outside.read_bytes() == b"preserve" + + +def test_child_stdout_stderr_and_exit_code(tmp_path): + p = tmp_path / "child.log" + result = supervise( + [ + sys.executable, + "-c", + 'import os;os.write(1,b"stdout\\x00");os.write(2,b"stderr");raise SystemExit(7)', + ], + p, + max_bytes=100, + backups=2, + ) + assert result == 7 and p.read_bytes() == b"stdout\x00stderr" + + +def test_signal_reaches_child_and_supervisor_exits(tmp_path): + path = tmp_path / "child.log" + code = ( + "import signal,time,os;signal.signal(signal.SIGTERM,lambda *a:exit(0));" + 'os.write(1,b"ready");time.sleep(30)' + ) + proc = subprocess.Popen( + [ + sys.executable, + "-m", + "k1link.rotating_process", + "--log", + str(path), + "--", + sys.executable, + "-c", + code, + ] + ) + try: + for _ in range(100): + if path.exists() and path.read_bytes() == b"ready": + break + time.sleep(0.02) + else: + pytest.fail("child failed to start") + proc.send_signal(signal.SIGTERM) + assert proc.wait(timeout=5) == 0 + finally: + if proc.poll() is None: + proc.kill() + proc.wait() + + +def test_wrapping_preserves_command_environment_and_network_policy(tmp_path): + d = { + "Label": "example", + "ProgramArguments": [ + "/usr/bin/ssh", + "-N", + "-R", + "127.0.0.1:18080:127.0.0.1:8000", + "mission-gpu", + ], + "EnvironmentVariables": {"PRIVATE_VALUE": "not-printed"}, + "StandardErrorPath": str(tmp_path / "old.log"), + "KeepAlive": True, + } + result = bounded_launchd_output(d, tmp_path) + assert service_command(result) == d["ProgramArguments"] + assert result["EnvironmentVariables"] == d["EnvironmentVariables"] + assert result["KeepAlive"] is True + assert service_log_path(result) == tmp_path / "old.managed.log" + assert result["StandardOutPath"] == result["StandardErrorPath"] == "/dev/null" + assert bounded_launchd_output(result, tmp_path) == result + assert d["StandardErrorPath"] == str(tmp_path / "old.log") + + +def test_existing_wrapper_cannot_restore_unbounded_launchd_output(tmp_path): + value = bounded_launchd_output( + { + "ProgramArguments": ["/usr/bin/ssh", "-N", "existing"], + "StandardErrorPath": str(tmp_path / "old.log"), + }, + tmp_path, + ) + value["StandardOutPath"] = value["StandardErrorPath"] = str(tmp_path / "old.log") + updated = bounded_launchd_output(value, tmp_path) + assert updated["StandardErrorPath"] == updated["StandardOutPath"] == "/dev/null" + assert updated["ProgramArguments"].count("k1link.rotating_process") == 1 diff --git a/tests/test_runtime_log_policy.py b/tests/test_runtime_log_policy.py new file mode 100644 index 00000000..fab33d26 --- /dev/null +++ b/tests/test_runtime_log_policy.py @@ -0,0 +1,131 @@ +import importlib.util +import plistlib +import sys +from pathlib import Path + +import pytest + +SCRIPT = Path(__file__).parents[1] / "scripts/manage_runtime_log_policy.py" +# Script imports its canonical sibling management helpers. + +sys.path.insert(0, str(SCRIPT.parent)) +spec = importlib.util.spec_from_file_location("runtime_log_policy", SCRIPT) +manager = importlib.util.module_from_spec(spec) +spec.loader.exec_module(manager) + + +def fixture(tmp_path): + root = tmp_path / "repo" + root.mkdir() + home = tmp_path / "home" + path = home / "Library/LaunchAgents/com.nodedc.mission-core.local.plist" + path.parent.mkdir(parents=True) + value = { + "Label": "com.nodedc.mission-core.local", + "ProgramArguments": ["/opt/homebrew/bin/uv", "run", "--no-sync", "k1link", "serve"], + "WorkingDirectory": str(root), + "EnvironmentVariables": {"keep": "private"}, + "KeepAlive": True, + "StandardErrorPath": str(home / "Library/Logs/core.log"), + "StandardOutPath": str(home / "Library/Logs/core.log"), + } + path.write_bytes(plistlib.dumps(value)) + return root, home, path + + +def test_plan_preserves_foreign_fields_and_apply_refuses_stale(tmp_path, monkeypatch): + root, home, path = fixture(tmp_path) + original = path.read_bytes() + plan, before, desired = manager.plan(root, "core", home=home) + assert before == original and path.read_bytes() == original + assert plistlib.loads(desired)["EnvironmentVariables"] == {"keep": "private"} + monkeypatch.setattr(Path, "home", lambda: home) + value = plistlib.loads(original) + value["KeepAlive"] = False + path.write_bytes(plistlib.dumps(value)) + with pytest.raises(ValueError, match="Stale"): + manager.apply(plan) + assert plistlib.loads(path.read_bytes())["KeepAlive"] is False + + +def test_failed_acceptance_restores_exact_declaration(tmp_path, monkeypatch): + root, home, path = fixture(tmp_path) + plan, before, _ = manager.plan(root, "core", home=home) + monkeypatch.setattr(Path, "home", lambda: home) + calls = [] + monkeypatch.setattr(manager, "_reload_launch_agent", lambda p: calls.append(p)) + + def acceptance(*args): + if len(calls) == 1: + raise RuntimeError("failed canary") + return {"restored": True} + + monkeypatch.setattr(manager, "accept", acceptance) + with pytest.raises(RuntimeError, match="failed canary"): + manager.apply(plan) + assert path.read_bytes() == before and len(calls) == 2 + assert list((root / ".runtime/storage-maintenance/log-policy").rglob("*.plist")) + + +def test_scanner_records_and_rotated_permissions_are_bounded(tmp_path): + import logging + import stat + + from k1link.web.runtime_diagnostics import ( + _EXTRA_FIELDS, + PrivateRotatingFileHandler, + ScannerDiagnosticJsonFormatter, + ) + + record = logging.LogRecord("test", logging.INFO, "x", 1, "x" * 100000, (), None) + for field in _EXTRA_FIELDS: + setattr(record, field, "я" * 100000) + formatter = ScannerDiagnosticJsonFormatter() + payload = formatter.format(record) + assert len(payload.encode()) <= 16384 + path = tmp_path / "diagnostic.log" + handler = PrivateRotatingFileHandler(path, maxBytes=200, backupCount=2, encoding="utf-8") + handler.setFormatter(formatter) + for _ in range(4): + handler.emit(logging.LogRecord("test", logging.INFO, "x", 1, "test message", (), None)) + handler.close() + assert len(list(tmp_path.iterdir())) == 3 + assert all(stat.S_IMODE(p.stat().st_mode) == 0o600 for p in tmp_path.iterdir()) + + +@pytest.mark.parametrize("exit_code", [0, 9]) +def test_check_wrapper_cleans_only_its_scratch_on_success_and_failure(tmp_path, exit_code): + import check_python + + root = tmp_path / "repo" + executable = root / ".venv/bin/python" + executable.parent.mkdir(parents=True) + executable.write_text( + f"#!{sys.executable}\n" + "import os,pathlib,sys\n" + "p=pathlib.Path(os.environ['MYPY_CACHE_DIR']);p.mkdir(parents=True);(p/'data').write_bytes(b'cache')\n" + "assert os.environ['RUFF_NO_CACHE']=='true'\n" + "assert os.environ['PYTHONDONTWRITEBYTECODE']=='1'\n" + f"sys.exit({exit_code})\n" + ) + executable.chmod(0o700) + protected = root / ".runtime/python-checks/another-job" + protected.mkdir(parents=True) + (protected / "keep").write_text("active") + assert check_python.run("mypy", [], root=root) == exit_code + assert [p for p in protected.parent.iterdir() if p.is_dir()] == [protected] + assert (protected / "keep").read_text() == "active" + + +def test_check_wrapper_refuses_accumulated_crash_directories_without_removing_them(tmp_path): + import check_python + + root = tmp_path / "repo" + parent = root / ".runtime/python-checks" + for i in range(4): + p = parent / str(i) + p.mkdir(parents=True) + (p / "keep").write_bytes(b"preserve") + with pytest.raises(ValueError, match="Four active"): + check_python.run("mypy", [], root=root) + assert len(list(parent.glob("*/keep"))) == 4