Repository navigation
Expand file tree
/
Copy pathspiral_service.py
More file actions
3215 lines (2963 loc) · 148 KB
/
Copy pathspiral_service.py
File metadata and controls
3215 lines (2963 loc) · 148 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""HTTP service for a persistent interactive Spiral fit.
The service binds to loopback by default. Non-loopback binds are explicit and
always carry bearer authentication; every client — including VC3D talking to a
process it launched itself — uses the same authenticated HTTP protocol.
Every service is bound to one dataset at startup: ``--dataset`` (inputs,
resolved once and advertised through ``/dataset``) and ``--output`` (all
generated state) are required; ``--cache`` defaults to the documented user
cache (``$XDG_CACHE_HOME/vc3d/spiral``). Both --output and --cache must
resolve outside the dataset root — the dataset holds inputs only.
The service starts ``Uninitialized``. Dataset and checkpoint discovery remain
available without importing the fitting runtime; ``POST /session/initialize``
creates the first resident session, and ``POST /session/rebuild`` replaces an
existing one.
Generated display data (previews, downloadable
checkpoints) is published as immutable, opaque artifacts and transferred
through ``/artifacts/...`` instead of host filesystem paths. Session inputs
(patches, fibers, PCL documents) can be uploaded into a dataset-scoped
editing workspace and explicitly applied or committed into the dataset.
Host filesystem paths are the service's business. A client never invents
one: a saved checkpoint is a name the service places under the session
output directory, uploads land in service-chosen staging, and everything
read back is an artifact ID. The one path a client does send — the
checkpoint to load into the resident fit — has to be one this service
advertised or wrote itself.
Long operations accept and return. A preview export costs minutes, so
``POST /session/export-preview`` starts one and answers immediately; the
client follows it through ``/session/status``, which it already polls. The
only verbs that hold a request open are the ones that are genuinely quick.
"""
from __future__ import annotations
import argparse
from contextlib import contextmanager
from input_workspace import MutationCoordinator
from workspace_storage import reclaim_workspaces
from service_editing import EditingWorkspace
from collections import OrderedDict, deque
from collections.abc import Mapping
import copy
import dataclasses
import hashlib
import json
import math
import logging
import os
from pathlib import Path
import re
import secrets
import shutil
import signal
import socket
import stat
import sys
import tempfile
import threading
import time
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, unquote, urlparse
from fit_session import (API_VERSION, EDITABLE_PCL_ROLES, FIT_INPUT_CATALOG,
SESSION_BUSY_STATES, SCROLL_SPEC_FILENAME,
SCROLL_SPEC_OWNED_RUN_KEYS, PclRole, ScrollSpecError,
SessionState, SpiralInputPaths, default_user_cache_dir,
input_source_enabled, pcl_input_enabled,
winding_inference_enabled, load_scroll_spec,
parse_session_request, resolve_dataset_root,
validate_session_request)
from checkpoint_migrations import tolerate_config
from config import (CHECKPOINT_MODEL_SHAPE_KEYS, Config, describe_catalog,
filter_known_config_keys, rebuild_stage)
from service_http import (ApiError, TRANSFER_CHUNK_BYTES,
is_safe_relative_name)
from service_artifacts import ArtifactRegistry
from preview_index import PublishedPreviewIndex
from service_files import ExclusiveFileLock, FileLockUnavailable
from service_uploads import (PCL_ROLE_FILES, UPLOADED_CHECKPOINTS_DIRNAME,
UploadEnvironment, UploadManager)
from lasagna_publish import (LasagnaPublisher, PreviewPublication,
stop_process_group)
# Re-exported for the service's own test surface, which addresses the preview
# mapping helpers through this module.
from lasagna_publish import (_load_flatten_correspondence, # noqa: F401
_mapped_winding_ids,
_prepare_cleaned_lasagna_surface,
_raw_run_diff_rgba, _sample_rgba_through_map,
_validate_tifxyz_output_step)
SERVICE_VERSION = "10.0.0"
# Per editable PCL role: the /session/status key carrying its display
# artifact, the artifact registry kind, the artifact directory prefix, and the
# human label used in client-facing messages.
PCL_ARTIFACT_STATUS_KEYS = {
PclRole.SAME_WINDING.value: "same_winding_artifact",
PclRole.RELATIVE.value: "relative_winding_artifact",
}
PCL_ARTIFACT_KINDS = {
PclRole.SAME_WINDING.value: "spiral-same-winding-pcl",
PclRole.RELATIVE.value: "spiral-relative-winding-pcl",
}
PCL_ARTIFACT_DIR_PREFIXES = {
PclRole.SAME_WINDING.value: "same-winding",
PclRole.RELATIVE.value: "relative-winding",
}
PCL_ROLE_LABELS = {
PclRole.SAME_WINDING.value: "same-winding",
PclRole.RELATIVE.value: "relative-winding",
}
MAX_BODY_BYTES = 4 * 1024 * 1024
MAX_DEDUPLICATED_COMMANDS = 256
PREVIEW_ARTIFACTS_KEPT = 3
CHECKPOINT_ARTIFACTS_KEPT = 2
# Upper bound on the checkpoint listing /dataset advertises. A client offers
# this as a choice, so it is a menu, not an inventory.
SESSION_CHECKPOINTS_LISTED = 200
MAX_LOG_ENTRY_CHARS = 8192
# Structured event ring served through /events. This is the whole of what a
# reconnecting client can recover, so it is sized to hold the loading bars
# plus a substantial portion of a long fit.
MAX_EVENT_ENTRIES = 20000
MAX_EVENT_READ_ENTRIES = 1000
# High-frequency event kinds (per-iteration metrics, progress redraws)
# coalesce to at most ~one record per key per interval. The interval matches
# the ProgressReporter publish interval, so the event stream carries the same
# cadence a status poller already observes.
EVENT_COALESCE_SECONDS = 1.0
_SAFE_SESSION_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
# Base input paths are owned by the service (every launch carries --dataset);
# a load request may only choose among service-advertised values for these
# keys.
_DATASET_CLIENT_SELECTABLE = ("checkpoint", "tracks_dbm")
def parse_gpu_ids(value):
"""Parse a comma-separated list of physical CUDA device indices."""
parts = [part.strip() for part in str(value).split(",")]
if not parts or any(not part for part in parts):
raise argparse.ArgumentTypeError(
"--gpus must be a comma-separated list such as 0 or 0,1,2,3")
try:
gpu_ids = tuple(int(part) for part in parts)
except ValueError as exc:
raise argparse.ArgumentTypeError(
"--gpus entries must be non-negative integer device indices") from exc
if any(gpu_id < 0 for gpu_id in gpu_ids):
raise argparse.ArgumentTypeError(
"--gpus entries must be non-negative integer device indices")
if len(set(gpu_ids)) != len(gpu_ids):
raise argparse.ArgumentTypeError("--gpus cannot contain duplicate devices")
return gpu_ids
def _cause(exc):
"""One human-readable line for a failure that has no client to raise to."""
if isinstance(exc, ApiError):
details = "; ".join(
f"{detail.get('field')}: {detail.get('message')}"
for detail in (exc.details or []))
return f"{exc.message}{f' ({details})' if details else ''}"
return f"{type(exc).__name__}: {exc}"
def parse_session_name(value):
"""Validate a host-owned name which is also used as one path component."""
name = str(value).strip()
if not _SAFE_SESSION_NAME.fullmatch(name) or name in {".", ".."}:
raise argparse.ArgumentTypeError(
"--session-name must be 1-64 characters, start with a letter or "
"digit, and contain only letters, digits, '.', '_', or '-'")
return name
def bind_service_paths(resolution, output_directory, cache_directory):
"""Attach the startup-resolved output/cache roots to the advertisement.
Dataset resolution describes inputs only; where generated state lives
(--output) and where derived host caches live (--cache) are service
startup decisions. /dataset advertises the bound result so clients see
one immutable set of paths.
"""
resolution.resolved["output_directory"] = str(output_directory)
resolution.resolved["cache_directory"] = str(cache_directory)
return resolution
def _validate_dt_loss_schedule(value):
"""Validate the required, transient DT schedule on a Run request."""
if not isinstance(value, dict):
raise ApiError(
HTTPStatus.BAD_REQUEST, "dt_loss_schedule must be a JSON object")
expected = {"enabled", "last_fraction"}
if set(value) != expected:
raise ApiError(
HTTPStatus.BAD_REQUEST,
"dt_loss_schedule must contain exactly enabled and last_fraction")
enabled = value["enabled"]
if not isinstance(enabled, bool):
raise ApiError(
HTTPStatus.BAD_REQUEST, "dt_loss_schedule.enabled must be boolean")
fraction = value["last_fraction"]
if (isinstance(fraction, bool)
or not isinstance(fraction, (int, float))):
raise ApiError(
HTTPStatus.BAD_REQUEST,
"dt_loss_schedule.last_fraction must be numeric")
fraction = float(fraction)
if not math.isfinite(fraction) or not 0.0 <= fraction <= 1.0:
raise ApiError(
HTTPStatus.BAD_REQUEST,
"dt_loss_schedule.last_fraction must be finite and between 0 and 1")
return {"enabled": enabled, "last_fraction": fraction}
# Console lines whose information is already published as structured
# /events records: ProgressReporter console snapshots and the fitter's
# periodic step-metric prints. They stay on the terminal, but the event
# stream must not double-report them as log records next to the structured
# progress/metric records.
_STRUCTURED_CONSOLE_LINE = re.compile(r"^(?:PROGRESS |step \d+: loss = )")
class ServiceEventBuffer:
"""Bounded ring of structured service events served through ``/events``.
Every record carries a monotonically increasing ``sequence``;
``GET /events?cursor=N`` returns records with ``sequence > N`` plus
``next_cursor`` for the following read. Cursor semantics:
* A cursor newer than the newest record (a cursor kept across a service
restart) answers ``cursor_reset`` true and the read restarts from the
beginning of the retained ring.
* A cursor older than the ring start answers ``overrun`` true with
``dropped``/``dropped_from`` describing the gap. The event stream is
bounded history, not reconnect state: an overrun client refreshes its
durable view from ``/session/status`` and continues from
``next_cursor``.
Reconnect protocol: read the ``/session/status`` snapshot first, then
subscribe from the cursor position the first ``/events`` read reports.
Records submitted with a ``coalesce_key`` are rate limited: while a
record with the same key was emitted less than ``coalesce_seconds`` ago,
the newest record is parked in a per-key pending slot (replacing any
older pending record) and flushed on the next append or read once the
interval has elapsed. The ring therefore stores at most ~one record per
key per interval while the latest values still reach clients.
"""
def __init__(self, max_entries=MAX_EVENT_ENTRIES,
coalesce_seconds=EVENT_COALESCE_SECONDS,
clock=time.monotonic):
self._lock = threading.Lock()
self._entries = deque(maxlen=max_entries)
self._next_sequence = 1
self._coalesce_seconds = float(coalesce_seconds)
self._clock = clock
self._pending = {}
self._last_emit = {}
# Stamps records that do not carry an explicit session generation.
# Must never take another lock: it is called under this buffer's own.
self.session_generation_provider = None
def append(self, kind, text="", *, severity="info", source="service",
rank=None, session_generation=None, operation=None,
payload=None, coalesce_key=None, force=False):
now = self._clock()
with self._lock:
if session_generation is None \
and self.session_generation_provider is not None:
try:
session_generation = self.session_generation_provider()
except Exception:
session_generation = None
record = {
"timestamp": time.time(),
"severity": str(severity),
"kind": str(kind),
"source": str(source),
"rank": rank,
"session_generation": session_generation,
"operation": operation,
"text": str(text or ""),
"payload": payload,
}
self._flush_due(now)
if coalesce_key is None:
self._append(record)
return
last = self._last_emit.get(coalesce_key)
if force or last is None or now - last >= self._coalesce_seconds:
self._pending.pop(coalesce_key, None)
self._last_emit[coalesce_key] = now
self._append(record)
else:
self._pending[coalesce_key] = record
def _append(self, record):
record["sequence"] = self._next_sequence
self._next_sequence += 1
self._entries.append(record)
def _flush_due(self, now):
for key in list(self._pending):
if now - self._last_emit.get(key, float("-inf")) \
>= self._coalesce_seconds:
self._last_emit[key] = now
self._append(self._pending.pop(key))
def read_after(self, cursor, limit=MAX_EVENT_READ_ENTRIES):
limit = max(1, min(int(limit), MAX_EVENT_READ_ENTRIES))
cursor = int(cursor)
with self._lock:
self._flush_due(self._clock())
latest = self._next_sequence - 1
cursor_reset = cursor > latest
if cursor_reset:
cursor = 0
oldest = (self._entries[0]["sequence"] if self._entries
else self._next_sequence)
dropped = max(0, oldest - max(0, cursor + 1))
events = [dict(record) for record in self._entries
if record["sequence"] > cursor][:limit]
next_cursor = events[-1]["sequence"] if events \
else min(cursor, latest)
return {
"events": events,
"next_cursor": next_cursor,
"latest_sequence": latest,
"dropped": dropped,
"dropped_from": (cursor + 1) if dropped else None,
"overrun": dropped > 0,
"cursor_reset": cursor_reset,
}
class ServiceLogBuffer:
"""Splits the service's stdout and stderr into whole console lines.
Every complete non-structured line is published to the event buffer as a
``log``-kind record; lines already covered by structured
progress/metric events are kept out of the event stream so the same
information is never double-reported.
This used to also retain its own ring for a ``GET /logs`` relay. Nothing
read it: ``/events`` carries these same lines, with a cursor, a
session generation and an overrun signal that the log cursor never had,
and retaining every line twice was the single largest thing this process
held for the benefit of no client.
"""
def __init__(self, events=None):
self._lock = threading.Lock()
self._pending = {"stdout": "", "stderr": ""}
self._events = events
def write(self, stream, text):
if not text or self._events is None:
return
# Carriage-return progress displays should still give remote clients
# useful snapshots even though they overwrite one terminal line.
text = str(text).replace("\r", "\n")
# Splitting and publishing stay under one lock so concurrently
# written streams cannot interleave their lines in the event ring.
with self._lock:
parts = (self._pending.get(stream, "") + text).split("\n")
self._pending[stream] = parts.pop()
for line in parts:
if not line or _STRUCTURED_CONSOLE_LINE.match(line):
continue
if len(line) > MAX_LOG_ENTRY_CHARS:
line = line[:MAX_LOG_ENTRY_CHARS] + " … [truncated]"
self._events.append("log", line, source=stream)
class _TeeStream:
"""Preserve normal terminal output while copying complete lines to logs."""
def __init__(self, stream, logs, name):
self._stream = stream
self._logs = logs
self._name = name
def write(self, text):
written = self._stream.write(text)
self._logs.write(self._name, text)
return written
def flush(self):
return self._stream.flush()
def __getattr__(self, name):
return getattr(self._stream, name)
class ServiceState:
"""HTTP-facing state of the service process.
The service starts uninitialized. Dataset discovery and the HTTP control
surface are available immediately, but constructing the fit runtime is an
explicit client action. While a runtime is being constructed (or after a
construction failure) there is no session *object* to ask, so the service
reports the lifecycle state it is driving itself.
What the service does own is service-scoped bookkeeping — session and
command generations, artifacts, and uploads.
"""
def __init__(self, dataset_root=None, dataset_resolution=None,
service_name=None, session_name="", logs=None, events=None,
gpu_ids=(0,), startup_run=None):
self.lock = threading.RLock()
self._workspace_condition = threading.Condition(self.lock)
self._workspace_closing = False
self._service_closed = False
self._workspace_users = 0
self._background_jobs = set()
self._retiring_sessions = []
self._teardown_lock = threading.Lock()
self._release_receipts = MutationCoordinator()
self._pcl_publication_locks = {
role: threading.Lock() for role in EDITABLE_PCL_ROLES
}
self.session = None
self.editing_workspace = None
self._input_content_artifacts = {}
self._input_content_artifact_lock = threading.Lock()
self.session_id = None
self.session_paths = None
self.session_request = None
self.session_generation = 0
self.status_generation = 0
self.commands = OrderedDict()
self.inflight_commands = set()
self.command_condition = threading.Condition(self.lock)
# Lifecycle the service drives while there is no session object.
# Idle/Running belong to the runtime once one has been initialized.
self._session_state = SessionState.Uninitialized
self._session_phase = "Waiting for fit initialization"
self._session_error = None
self._building = False
self.startup_run = dict(startup_run or {})
self.dataset_root = str(dataset_root) if dataset_root else None
self.dataset_resolution = dataset_resolution
self.service_name = service_name or socket.gethostname()
self.session_name = str(session_name or "")
self.events = events if events is not None else ServiceEventBuffer()
self.logs = logs if logs is not None else ServiceLogBuffer(self.events)
# Log-kind records produced by the console tee carry the current
# session generation. Reading the attribute is lock-free by design;
# the provider runs under the event buffer's own lock.
self.events.session_generation_provider = \
lambda: self.session_generation
# Per-rank change trackers so repeated status snapshots do not
# re-emit identical structured events.
self._event_progress_signatures = {}
self._event_metric_iterations = {}
self._event_errors = {}
self.gpu_ids = tuple(gpu_ids)
self.artifacts = ArtifactRegistry()
self.checkpoint_uploads = UploadManager(self._upload_environment())
# One record for the whole of preview publication (see
# LasagnaPublisher's PreviewPublication), guarded by self.lock.
self._preview = PreviewPublication()
# Display artifacts of the editable PCL roles, keyed by role value.
self.pcl_artifacts = {}
# A preview export runs off the HTTP thread (it costs minutes); this
# is what makes the verb single-flight and what /session/status
# reports so a client reconnecting mid-export can see one is running.
self._preview_export_active = False
self._preview_schedule = None
self._next_preview_iteration = None
self._automatic_previews_disabled = False
self._automatic_preview_generations = set()
# The checkpoint the fitter last reported its resident model equal
# to (see InteractiveFitSession.status()["checkpoint_state"]); a
# change here pins that checkpoint's published preview and re-shows
# it when one exists.
self._checkpoint_state = None
self.config_catalog = Config.catalog()
self.session_revision = 0
if self._output_root() is not None:
reclaim_workspaces(self._output_root())
# ------------------------------------------------------------------
# Status and health
# ------------------------------------------------------------------
@contextmanager
def workspace_use(self):
with self._workspace_condition:
if self._workspace_closing or self._service_closed:
raise ApiError(410, "The editing workspace is closing")
self._workspace_users += 1
try:
yield
finally:
with self._workspace_condition:
self._workspace_users -= 1
self._workspace_condition.notify_all()
def _start_background(self, *, target, args=(), name, daemon=True):
def run():
try:
target(*args)
finally:
with self._workspace_condition:
self._background_jobs.discard(threading.current_thread())
self._workspace_condition.notify_all()
with self._workspace_condition:
if self._workspace_closing or self._service_closed:
raise ApiError(410, "The editing workspace is closing")
thread = threading.Thread(target=run, name=name, daemon=daemon)
self._background_jobs.add(thread)
thread.start()
def release_editing(self, token, command_id):
def release(_):
with self._teardown_lock:
workspace = self.editing_workspace
if workspace is None:
raise ApiError(403, "This client does not own an editing workspace")
workspace.require(token)
self._teardown_workspace()
return {"released": True}
return self._release_receipts.execute(command_id, 'release',
{'token_digest': hashlib.sha256(str(token).encode()).hexdigest()},
release, recoverable=lambda exc: isinstance(exc, (TimeoutError, OSError)))
def _teardown_workspace(self):
try:
self._drain_and_remove_workspace()
except Exception:
root = self.editing_workspace.root if self.editing_workspace else self._output_root()
logging.exception("Spiral teardown failed; retained workspace %s", root)
raise
def _drain_and_remove_workspace(self):
# Do not drop any references or locks until every file user has stopped.
with self._workspace_condition:
self._workspace_closing = True
self._workspace_condition.notify_all()
deadline = time.monotonic() + 15
while self._workspace_users or self._background_jobs:
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError("Workspace users did not stop; files retained")
self._workspace_condition.wait(remaining)
workspace, session = self.editing_workspace, self.session
process = self._preview.process
if workspace is not None:
workspace.coordinator.shutdown(lambda: None)
stop_process_group(process)
if process is not None and process.poll() is None:
raise TimeoutError("Preview process did not stop; workspace retained")
for retiring in tuple(self._retiring_sessions):
retiring.close()
self._retiring_sessions.remove(retiring)
if session is not None:
session.close()
if workspace is not None:
self.artifacts.retire_root(workspace.root)
# Publication recovery lives beside dataset targets, outside root.
for transaction in workspace.transactions.values():
for path in transaction.recovery_paths():
self.logs.write('stderr', f'Retained Commit recovery: {path}\n')
workspace.close()
with self.lock:
self.session = None
self.session_id = None
self.editing_workspace = None
self._input_content_artifacts.clear()
self._session_state = SessionState.Uninitialized
self._session_phase = "Waiting for fit initialization"
self._session_error = None
self._workspace_closing = False
def editing(self, *, create=True):
"""The dataset workspace survives resident generations and disconnects."""
with self.lock:
if self._workspace_closing or self._service_closed:
raise ApiError(410, "The editing workspace is closing")
if self.editing_workspace is None:
if not create:
raise ApiError(409, "Claim an editing workspace first")
if self.dataset_root is None or self._output_root() is None:
raise ApiError(409, "A managed dataset and output are required")
sources = (self.dataset_resolution.to_dict()
if self.dataset_resolution is not None else {})
self.editing_workspace = EditingWorkspace(
self.dataset_root, self._output_root(), sources,
self._editing_resident)
return self.editing_workspace
def input_content_artifact(self, input_id, revision_number):
with self.workspace_use():
return self._input_content_artifact(input_id, revision_number)
def _input_content_artifact(self, input_id, revision_number):
workspace = self.editing(create=False)
revision, = workspace._selection([{'id': input_id, 'revision': int(revision_number)}])
if revision.content is None:
raise ApiError(410, "This input revision is a deletion")
identity = workspace.catalog.entry(input_id).identity
siblings = ()
if identity.kind == 'fiber':
desired = tuple(r for r in workspace.catalog.desired()
if r.content is not None and
workspace.catalog.entry(r.id).identity.kind == 'fiber')
by_name = {Path(workspace.catalog.entry(r.id).identity.source).name: r
for r in desired}
# Resolve the requested revision's links, including transitive and
# pending links, against immutable desired peers. Never substitute
# the current revision for the explicitly requested entry point.
selected = {input_id}
pending = [revision]
while pending:
current = pending.pop()
document = json.loads(Path(current.content.json()['path']).read_text())
for branch in document.get('branches', []):
peer = by_name.get(branch.get('branch_file'))
if peer is not None and peer.id not in selected:
selected.add(peer.id)
pending.append(peer)
siblings = tuple(r for r in desired if r.id in selected and r.id != input_id)
key = (input_id, revision.number, tuple((r.id, r.number) for r in siblings))
with self._input_content_artifact_lock:
if key not in self._input_content_artifacts:
content = revision.content.json()
source = Path(content['path'])
if source.is_dir():
root, entry = source, 'meta.json'
artifact = self.artifacts.register_directory(
'input-content', workspace.id, revision.number, root, entry)
else:
parent = workspace.root / 'artifacts' / input_id
parent.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(dir=parent))
entry = Path(identity.source).name
try:
workspace._copy(source, root / entry)
for sibling in siblings:
name = Path(workspace.catalog.entry(sibling.id).identity.source).name
workspace._copy(sibling.content.json()['path'], root / name)
artifact = self.artifacts.register_directory(
'input-content', workspace.id, revision.number, root, entry)
except BaseException:
shutil.rmtree(root)
raise
self._input_content_artifacts[key] = artifact
return {'workspace_id': workspace.id, 'artifact': self._input_content_artifacts[key]}
def _editing_resident(self):
with self.lock:
if self.session is None or self._building:
raise ApiError(409, "Wait for the resident fit to finish loading")
return self.session
def input_upload_manager(self, upload_id):
if upload_id in self.checkpoint_uploads.uploads:
return self.checkpoint_uploads
return self.editing(create=False).uploads
def editing_lifecycle(self, token, operation, request, callback):
workspace = self.editing()
workspace.require(token)
def perform(captured):
workspace.require(token)
rebuilding = operation in {"session_initialize", "session_rebuild"}
command_id = captured.get("command_id")
if rebuilding and command_id in workspace.lifecycle_started:
response = workspace.lifecycle_started[command_id]
else:
if operation == "session_rebuild":
workspace.refresh_clean(f'{command_id}:refresh')
response = callback(captured)
if rebuilding:
workspace.lifecycle_started[command_id] = response
# Keep the coordinator until background construction and desired
# input replay finish. Read-only status remains responsive.
if operation in {"session_initialize", "session_rebuild"}:
while True:
with self.lock:
building, session = self._building, self.session
state = self._session_state if session is None else session.status()["state"]
if not building and state != SessionState.Loading:
break
time.sleep(0.05)
if state == SessionState.Error:
raise ApiError(409, "Resident construction failed", payload=self.status())
if session is not None:
result = workspace.replay_resident(self.session_generation)
if not result.get("applied"):
raise ApiError(409, "Desired inputs could not be restored", payload=result)
response = {**self.status(), "accepted": True}
return response
return workspace.coordinator.execute(request.get("command_id"), operation,
request, perform, recoverable=lambda exc: isinstance(exc, TimeoutError))
def _base(self):
"""The counters every response carries, and nothing else.
Three survive, because each answers a question no other one can:
``session_generation``
Which resident session this is. It advances on every rebuild,
stamps log and fitter event records, and is what a client uses
to notice that the session it adopted has been replaced.
``session_revision``
Which configuration/input revision the session is at. Mutations
carrying an older revision are refused.
``generation`` (the status revision)
Ordering for status snapshots, so a client can drop a reply that
overtook a newer one.
``service_generation`` and ``command_generation`` used to be here.
The first was the constant 1 and identified nothing (process
identity is ``process_id`` on /health, and clients reset their
cursors per connection); the second counted replayed commands while
the replay cache is keyed by (operation, command ID). Nothing read
either.
"""
return {
"api_version": API_VERSION,
"service_version": SERVICE_VERSION,
"service_name": self.service_name,
"session_name": self.session_name,
"session_id": self.session_id,
"session_generation": self.session_generation,
"session_revision": self.session_revision,
"generation": self.status_generation,
"gpus": list(self.gpu_ids),
}
def status(self):
with self.lock:
response = self._base()
response.update(self.session.status() if self.session else {
# No session object yet (or no longer): the service is
# building one, or building it failed. Both are real
# lifecycle states, so there is nothing like "Empty" to
# report.
"state": self._session_state, "phase": self._session_phase,
"current_iteration": 0,
"target_iteration": 0, "latest_metrics": {}, "warnings": [],
"error": self._session_error, "preview_manifest_path": None,
"preview_generation": 0,
"progress": None,
})
response.setdefault("progress", None)
# The status snapshot carries raw progress facts only. ETA is a
# presentation value clients derive from step/total/elapsed.
if isinstance(response.get("progress"), dict):
response["progress"] = {
key: value
for key, value in response["progress"].items()
if key != "eta_seconds"
}
response["workspace_id"] = self.editing_workspace.id if self.editing_workspace else None
response["session_request"] = self.session_request
response["preview_artifact"] = self._preview.artifact
# Published separately from, and after, the surface: a client that
# never opens an overlay never waits for one.
response["preview_diagnostics_artifact"] = (
self._preview.diagnostics_artifact)
for role_value, status_key in PCL_ARTIFACT_STATUS_KEYS.items():
response[status_key] = self.pcl_artifacts.get(role_value)
response["preview_publish"] = (
dict(self._preview.progress)
if self._preview.progress else None)
response["preview_publish_error"] = self._preview.error
response["preview_active"] = bool(self._preview.generation)
response["preview_pending"] = bool(
self._preview.pending_generation)
response["preview_source_iteration"] = (
self._preview.source_fit_iteration)
response["preview_active_source_iteration"] = (
self._preview.active_source_fit_iteration)
response["preview_pending_source_iteration"] = (
self._preview.pending_source_fit_iteration)
response["preview_schedule"] = copy.deepcopy(
response.get("preview_schedule") or self._preview_schedule)
response["next_preview_iteration"] = response.get(
"next_preview_iteration", self._next_preview_iteration)
response["automatic_previews_disabled"] = (
self._automatic_previews_disabled
or bool(response.get("automatic_previews_disabled")))
publishing = self._preview.status_progress()
if publishing is not None:
response["phase"] = publishing["stage_name"]
response["progress"] = publishing
available = (self.editing_workspace is not None
and any(entry.accepted > entry.persisted
for entry in self.editing_workspace.catalog.entries()))
response["commit_available"] = available
response["commit_unavailable_reason"] = "" if available else "No uncommitted revisions"
response["preview_exporting"] = self._preview_export_active
return response
def session_state(self):
"""The authoritative lifecycle state, session object or not."""
with self.lock:
if self.session is None:
return self._session_state
return self.session.status()["state"]
def health(self):
# Answered from service-owned facts only, so it keeps answering while
# CUDA and the model are being constructed and after a construction
# failure.
state = self.session_state()
response = self._base()
response.update({
"ready": True,
"process_id": os.getpid(),
"dataset_root": self.dataset_root,
"session_state": state,
"cuda_ready": (None if state == SessionState.Loading else
state not in {SessionState.Uninitialized,
SessionState.Error}),
})
return response
def configuration_catalog(self):
# Descriptions are re-read per request, so edited text reaches a
# client when it reconnects, without restarting the service.
return {**self._base(), **describe_catalog(self.config_catalog)}
def dataset(self):
return {**self._base(), **self.dataset_resolution.to_dict(),
"session_checkpoints": self.session_checkpoints()}
@property
def scroll_spec(self):
"""The parsed spiral-scroll.json manifest, or None if it is invalid."""
if self.dataset_resolution is None:
return None
return self.dataset_resolution.scroll_spec
def session_checkpoints(self):
"""Checkpoints under the session output directory, newest first.
Between this and ``detected_checkpoints`` a client has the whole set
of checkpoints it may name: the dataset root holds the ones that came
with the dataset, and the output directory holds everything this
service wrote or received (saves, autosaves, uploads). Advertising
both is what lets a client offer a choice instead of asking the user
to type a path on a host it may never have seen.
"""
root = self._output_root()
if root is None or not root.is_dir():
return []
found = []
for path in root.glob("**/*.ckpt"):
relative = path.relative_to(root)
# Artifact staging is transfer plumbing, and the upload store
# holds digest-named copies a client already has a handle on
# (``uploaded_checkpoint``). Neither is something a user picks
# from, which also keeps the two load sources disjoint.
if any(part.startswith(".") for part in relative.parts) \
or relative.parts[0] == UPLOADED_CHECKPOINTS_DIRNAME:
continue
if path.is_file():
found.append((path.stat().st_mtime, str(path)))
found.sort(key=lambda entry: (-entry[0], entry[1]))
return [path for _, path in found[:SESSION_CHECKPOINTS_LISTED]]
# ------------------------------------------------------------------
# Session lifecycle
# ------------------------------------------------------------------
def _dataset_session_request(self, request, *, include_input_config=False):
"""Build a dataset-owned request and select its active inputs.
A checkpoint-backed request intentionally carries no UI profile
overrides: the checkpoint owns its durable configuration. Input
selection must therefore consult that checkpoint configuration before
clearing mode-specific paths. Otherwise a winding-model checkpoint is
first treated like the default phase mode, ``winding_inference`` is
erased, and only then does the fitter discover that the checkpoint
requires it.
"""
resolution = self.dataset_resolution.to_dict()
requested_paths = request.get("paths") or {}
offending = sorted(
key for key, value in requested_paths.items()
if key not in _DATASET_CLIENT_SELECTABLE
and (value or (isinstance(value, list) and value))
)
if offending:
raise ApiError(
HTTPStatus.BAD_REQUEST,
"This service owns its base inputs; the load request must not "
"carry input paths",
[{"field": key, "message": "Base input paths are owned by the service"}
for key in offending])
paths = {"dataset_root": resolution["root"], "scroll_zarr": ""}
for key in (*(spec.key for spec in FIT_INPUT_CATALOG
if spec.kind != "pcl-set"),
"output_directory", "cache_directory"):
paths[key] = resolution["resolved"].get(key, "")
paths["pcls"] = resolution["pcl_inputs"]
checkpoint = str(requested_paths.get("checkpoint") or "").strip()
if checkpoint:
allowed = set(resolution.get("detected_checkpoints", []))
resolved_checkpoint = str(Path(checkpoint).resolve(strict=False))
output_root = Path(paths["output_directory"]).resolve(strict=False)
if resolved_checkpoint not in allowed and \
not Path(resolved_checkpoint).is_relative_to(output_root):
raise ApiError(HTTPStatus.BAD_REQUEST,
"Checkpoint must be one the service advertises or "
"one under the session output directory",
[{"field": "checkpoint", "message": "Not a service-advertised checkpoint"}])
paths["checkpoint"] = resolved_checkpoint
requested_config = dict(
(request.get("run") or {}).get("config") or {})
config = requested_config
if checkpoint:
checkpoint_config, _, _ = self._checkpoint_durable_cfg(
paths["checkpoint"])
if checkpoint_config is not None:
config = {**checkpoint_config, **requested_config}
# The service owns conventional paths, while the session config owns
# which optional sources participate. Clear disabled paths before
# validating any client-selectable override so the manifest, validator,
# and fitter all describe the same source set.
selected_paths = {
"verified_patches": "verified_patches",
"fibers": "fibers",
"outer_shell": "outer_shell",
"tracks_dbm": "tracks_dbm",
"normal_x": "normals",
"normal_y": "normals",
"gradient_magnitude": "gradient_magnitude",
"winding_inference": "winding_inference",
}
for path_key, source in selected_paths.items():
if not input_source_enabled(config, source):
paths[path_key] = ""
if not winding_inference_enabled(config):
paths["winding_inference"] = ""
paths["pcls"] = [
spec for spec in paths["pcls"]
if pcl_input_enabled(config, spec.get("role"), spec.get("path", ""))
]
tracks = str(requested_paths.get("tracks_dbm") or "").strip()
if not input_source_enabled(config, "tracks_dbm"):
tracks = ""
if tracks:
candidates = set(resolution.get("ambiguities", {}).get("tracks_dbm", []))
if resolution["resolved"].get("tracks_dbm"):
candidates.add(resolution["resolved"]["tracks_dbm"])
if str(Path(tracks).resolve(strict=False)) not in candidates:
raise ApiError(HTTPStatus.BAD_REQUEST,
"tracks_dbm must be one of the service-advertised candidates",
[{"field": "tracks_dbm", "message": "Not a service-advertised candidate"}])
paths["tracks_dbm"] = str(Path(tracks).resolve(strict=False))
resolved_request = {**request, "paths": paths}
if include_input_config:
return resolved_request, config
return resolved_request
def _prepare_session_request(self, request, *, restore_checkpoint_z=False):
"""Validate one session request into the arguments a build needs."""
input_config = None
try:
# The scroll specification in the dataset root owns these. A
# request that names one is refused rather than quietly overruled
# by the file.
scroll_owned = sorted(
key for key in SCROLL_SPEC_OWNED_RUN_KEYS
if key in (request.get("run") or {}))
if scroll_owned:
raise ApiError(
HTTPStatus.BAD_REQUEST,
f"{SCROLL_SPEC_FILENAME} in the dataset root owns these "
"values; the request must not carry them",
[{"field": f"run.{key}",
"message": (f"Owned by {SCROLL_SPEC_FILENAME} as "
f"{SCROLL_SPEC_OWNED_RUN_KEYS[key]!r}")}
for key in scroll_owned])
if self.dataset_resolution is not None:
request, input_config = self._dataset_session_request(
request, include_input_config=True)
paths, run, preview = parse_session_request(request)
except (KeyError, TypeError, ValueError) as exc: