@simplexai/localmodels-linux-arm64 0.1.0-dev.58 → 0.1.0-dev.59
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +57 -56
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/app.py +1 -1
- package/modules/localmodels/bifrost_admin.py +53 -8
- package/modules/localmodels/bifrost_config.py +103 -4
- package/modules/localmodels/bifrost_log.py +166 -0
- package/modules/localmodels/budget.py +1 -1
- package/modules/localmodels/catalog.json +55 -32
- package/modules/localmodels/engines-strata-poly-0.2.20-poly.5.json +94 -0
- package/modules/localmodels/frontend.py +26 -21
- package/modules/localmodels/gateway_bifrost.py +30 -6
- package/modules/localmodels/hosts.py +99 -12
- package/modules/localmodels/library_convert.py +34 -0
- package/modules/localmodels/library_elastic.py +150 -123
- package/modules/localmodels/library_gateway.py +101 -10
- package/modules/localmodels/library_jobs.py +16 -7
- package/modules/localmodels/library_pricing.py +14 -4
- package/modules/localmodels/library_serve.py +84 -16
- package/modules/localmodels/library_state.py +4 -1
- package/modules/localmodels/library_status.py +18 -4
- package/modules/localmodels/metal.py +1 -1
- package/modules/localmodels/metal_probe.py +4 -4
- package/modules/localmodels/plan_envelope.py +4 -1
- package/modules/localmodels/process_identity_linux.py +39 -0
- package/modules/localmodels/remote_ops.py +4 -3
- package/modules/localmodels/remote_ops_download.py +37 -24
- package/modules/localmodels/remote_ops_mirrors.py +43 -2
- package/modules/localmodels/remote_ops_service.py +93 -36
- package/modules/localmodels/runtime_auth.py +4 -1
- package/modules/localmodels/service_wiring.py +238 -12
- package/modules/localmodels/setup_inspection.py +47 -70
- package/modules/localmodels/setup_inspection_harness.py +159 -15
- package/modules/localmodels/setup_text.py +14 -0
- package/modules/localmodels/setup_upgrade.py +1 -1
- package/modules/localmodels/source_byok.py +6 -2
- package/modules/localmodels/source_byok_probe.py +6 -1
- package/modules/localmodels/stack.py +9 -1
- package/modules/localmodels/stack_binding.py +3 -35
- package/modules/localmodels/stack_cleanup.py +4 -0
- package/modules/localmodels/stack_compose.py +18 -2
- package/modules/localmodels/stack_lifecycle.py +24 -1
- package/modules/localmodels/stack_plan.py +6 -2
- package/modules/localmodels/stack_ports.py +2 -0
- package/modules/localmodels/stack_remove.py +10 -1
- package/modules/localmodels/stack_up.py +33 -7
- package/modules/localmodels/stack_update.py +3 -1
- package/modules/localmodels/{strata-poly-serve-0.2.19-poly.1.txt → strata-poly-serve-0.2.20-poly.5.txt} +1 -1
- package/modules/localmodels/suite.py +43 -27
- package/modules/localmodels/transport.py +13 -2
- package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/RECORD +54 -53
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/engines-strata-poly-0.2.19-poly.1.json +0 -79
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev58.dist-info → simplex_localmodels-0.1.0.dev59.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -36,6 +36,7 @@ from localmodels import (
|
|
|
36
36
|
library_status,
|
|
37
37
|
metal,
|
|
38
38
|
plan_envelope,
|
|
39
|
+
source_byok,
|
|
39
40
|
stack_lifecycle,
|
|
40
41
|
stack_ports,
|
|
41
42
|
stack_verify,
|
|
@@ -275,7 +276,7 @@ def _remove_service(plan: Plan, run: Executor) -> None:
|
|
|
275
276
|
raise LibraryError(
|
|
276
277
|
"ENGINE_START_FAILED", f"stopping {plan['name']}: {outcome.get('message')}"
|
|
277
278
|
)
|
|
278
|
-
hosts.delete_record(hosts.LOCAL_ID, plan["name"])
|
|
279
|
+
hosts.delete_record(hosts.LOCAL_ID, plan["name"], deploy_dir=plan["service"]["deploy_dir"])
|
|
279
280
|
|
|
280
281
|
|
|
281
282
|
def _forget_deployment(plan: Plan) -> None:
|
|
@@ -284,7 +285,9 @@ def _forget_deployment(plan: Plan) -> None:
|
|
|
284
285
|
deploy_dir = Path(os.path.expanduser(plan["service"]["deploy_dir"]))
|
|
285
286
|
if deploy_dir.parent.name == "deployments" and deploy_dir.is_dir():
|
|
286
287
|
shutil.rmtree(deploy_dir, ignore_errors=True)
|
|
287
|
-
hosts.delete_record(
|
|
288
|
+
hosts.delete_record(
|
|
289
|
+
hosts.LOCAL_ID, plan["name"], purged=True, deploy_dir=plan["service"]["deploy_dir"]
|
|
290
|
+
)
|
|
288
291
|
|
|
289
292
|
|
|
290
293
|
def stack_member(record: Record) -> str | None:
|
|
@@ -301,21 +304,28 @@ def _fail(record: Record, error: LibraryError) -> LibraryError:
|
|
|
301
304
|
return error
|
|
302
305
|
|
|
303
306
|
|
|
307
|
+
def _restore_baseline_plan(record: Record) -> None:
|
|
308
|
+
"""Restore the pristine capacity plan once the active server is stopped."""
|
|
309
|
+
if (baseline := record.pop("baseline_plan", None)) is not None:
|
|
310
|
+
record["plan"] = baseline
|
|
311
|
+
|
|
312
|
+
|
|
304
313
|
def stop(record: Record, run: Executor) -> None:
|
|
305
|
-
"""
|
|
306
|
-
raises, so the next unload or remove tries again.
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
the
|
|
314
|
+
"""Demote a loaded record, unregister it, then stop and remove the model's server; its
|
|
315
|
+
weights stay. Either failing raises, so the next unload or remove tries again. A loaded
|
|
316
|
+
record is marked failed on disk before unregistering so a failed, interrupted, or killed
|
|
317
|
+
stop never leaves status or load treating an unroutable model as loaded; once unregistered
|
|
318
|
+
the registration receipt is removed before the server stops."""
|
|
310
319
|
if registration := record.get("registration"):
|
|
311
|
-
library_gateway.unregister(registration)
|
|
312
|
-
record.pop("registration")
|
|
313
320
|
if record["state"] == "loaded":
|
|
314
321
|
record["state"] = "failed"
|
|
315
322
|
record["error"] = {
|
|
316
323
|
"code": "ENGINE_START_FAILED",
|
|
317
324
|
"detail": "stopping the model server did not finish; unload or load it again",
|
|
318
325
|
}
|
|
326
|
+
library_state.save(record)
|
|
327
|
+
library_gateway.unregister(registration)
|
|
328
|
+
record.pop("registration")
|
|
319
329
|
library_state.save(record)
|
|
320
330
|
record.pop("load_posture", None)
|
|
321
331
|
if record["state"] != "idle": # loaded, failed, or starting when a load was cut short
|
|
@@ -324,6 +334,9 @@ def stop(record: Record, run: Executor) -> None:
|
|
|
324
334
|
for key in ("registration", "error", "note"):
|
|
325
335
|
record.pop(key, None) # type: ignore[misc]
|
|
326
336
|
library_state.save(record)
|
|
337
|
+
if (baseline := record.pop("baseline_plan", None)) is not None:
|
|
338
|
+
record["plan"] = baseline
|
|
339
|
+
library_state.save(record)
|
|
327
340
|
|
|
328
341
|
|
|
329
342
|
def _serve(
|
|
@@ -379,6 +392,8 @@ def _serve(
|
|
|
379
392
|
ctx_token = _ELASTIC_CTX.set(
|
|
380
393
|
_ElasticLoadContext(elastic=elastic, base=base, pool=record["pool"], port=port, force=force)
|
|
381
394
|
)
|
|
395
|
+
if record.get("baseline_plan") is None:
|
|
396
|
+
record["baseline_plan"] = record["plan"]
|
|
382
397
|
record["plan"], record["state"] = plan, "starting"
|
|
383
398
|
record.pop("error", None)
|
|
384
399
|
library_state.save(record) # the server about to start is recorded before it exists
|
|
@@ -423,6 +438,30 @@ def _next_oom_rung(
|
|
|
423
438
|
return None
|
|
424
439
|
|
|
425
440
|
|
|
441
|
+
def _rollback_registration(
|
|
442
|
+
record: Record, plan: Plan, run: Executor, exc: LibraryError
|
|
443
|
+
) -> LibraryError:
|
|
444
|
+
"""Undo gateway registration and stop the server after a failed ``register()``, surfacing any
|
|
445
|
+
incomplete cleanup in the error detail while keeping uncleaned receipts/plans for ``unload``."""
|
|
446
|
+
notes: list[str] = []
|
|
447
|
+
try: # kept for unload when this fails too
|
|
448
|
+
library_gateway.unregister(record["registration"])
|
|
449
|
+
record.pop("registration")
|
|
450
|
+
except LibraryError as unreg_err:
|
|
451
|
+
notes.append(f"unregister failed ({unreg_err.detail})")
|
|
452
|
+
try:
|
|
453
|
+
_remove_service(plan, run)
|
|
454
|
+
except LibraryError as stop_err:
|
|
455
|
+
notes.append(f"failed to stop server ({stop_err.detail})")
|
|
456
|
+
else:
|
|
457
|
+
record.pop("load_posture", None)
|
|
458
|
+
_restore_baseline_plan(record)
|
|
459
|
+
if notes:
|
|
460
|
+
detail = f"{exc.detail}; rollback incomplete: {'; '.join(notes)}"
|
|
461
|
+
exc = LibraryError(exc.code, detail, failed=exc.failed, **exc.fields)
|
|
462
|
+
return _fail(record, exc)
|
|
463
|
+
|
|
464
|
+
|
|
426
465
|
def _start(
|
|
427
466
|
model: Model,
|
|
428
467
|
record: Record,
|
|
@@ -442,6 +481,8 @@ def _start(
|
|
|
442
481
|
try:
|
|
443
482
|
frontend.install(str(plan["launch"]["frontend_base_dir"]), str(reqs))
|
|
444
483
|
except frontend.FrontendError as exc:
|
|
484
|
+
record.pop("load_posture", None)
|
|
485
|
+
_restore_baseline_plan(record)
|
|
445
486
|
raise _fail(record, LibraryError("ENGINE_START_FAILED", str(exc))) from None
|
|
446
487
|
|
|
447
488
|
ctx = _ELASTIC_CTX.get()
|
|
@@ -452,8 +493,15 @@ def _start(
|
|
|
452
493
|
break
|
|
453
494
|
code = _start_code(finished)
|
|
454
495
|
error = LibraryError(code, str(finished.get("error") or "start failed"))
|
|
455
|
-
|
|
496
|
+
try:
|
|
456
497
|
_remove_service(plan, run)
|
|
498
|
+
except LibraryError as cleanup_err:
|
|
499
|
+
# Keep record["plan"] on the unstopped deployment so unload/remove can stop it;
|
|
500
|
+
# never retry or launch a second server while the failed one may still hold GPU/RAM.
|
|
501
|
+
detail = f"{error.detail}; cleanup failed ({cleanup_err.detail})"
|
|
502
|
+
raise _fail(
|
|
503
|
+
record, LibraryError(code, detail, failed=error.failed, **error.fields)
|
|
504
|
+
) from None
|
|
457
505
|
if code == "OUT_OF_MEMORY" and ctx is not None and oom_retries < MAX_OOM_RETRIES:
|
|
458
506
|
next_elastic = _next_oom_rung(model, facts, ctx, ctx.elastic.rung_index + 1)
|
|
459
507
|
if next_elastic is not None:
|
|
@@ -470,6 +518,8 @@ def _start(
|
|
|
470
518
|
handle.update("load", 0, len(steps), load_step="prepare")
|
|
471
519
|
progress(model.id, "load", 0, len(steps), load_step="prepare")
|
|
472
520
|
continue
|
|
521
|
+
record.pop("load_posture", None)
|
|
522
|
+
_restore_baseline_plan(record)
|
|
473
523
|
raise _fail(record, error)
|
|
474
524
|
handle.update("load", len(steps), len(steps), load_step="load")
|
|
475
525
|
progress(model.id, "load", len(steps), len(steps), load_step="load")
|
|
@@ -494,12 +544,7 @@ def _start(
|
|
|
494
544
|
model.id, model.entry, plan, key, facts, stack_provider=member
|
|
495
545
|
)
|
|
496
546
|
except LibraryError as exc:
|
|
497
|
-
|
|
498
|
-
library_gateway.unregister(record["registration"])
|
|
499
|
-
record.pop("registration")
|
|
500
|
-
with contextlib.suppress(LibraryError):
|
|
501
|
-
_remove_service(plan, run)
|
|
502
|
-
raise _fail(record, exc) from None
|
|
547
|
+
raise _rollback_registration(record, plan, run, exc) from None
|
|
503
548
|
|
|
504
549
|
|
|
505
550
|
def _abandon(record: Record, run: Executor) -> None:
|
|
@@ -626,13 +671,27 @@ def unload(model_id: str, base_dir: str) -> Row:
|
|
|
626
671
|
return _row(model, base_dir)
|
|
627
672
|
|
|
628
673
|
|
|
674
|
+
def _clear_removed_source(pi_model: str | None) -> None:
|
|
675
|
+
"""Clear a stale local ``runtime_model`` in ``model-source.json`` when its model is removed."""
|
|
676
|
+
if not pi_model:
|
|
677
|
+
return
|
|
678
|
+
with contextlib.suppress(OSError, ValueError, source_byok.ByokError):
|
|
679
|
+
state = source_byok.load_source_state()
|
|
680
|
+
if state is not None and state["mode"] == "local" and state["runtime_model"] == pi_model:
|
|
681
|
+
source_byok.save_source_state({**state, "runtime_model": ""})
|
|
682
|
+
|
|
683
|
+
|
|
629
684
|
def remove(model_id: str, base_dir: str) -> Row:
|
|
630
685
|
from localmodels import library_convert
|
|
631
686
|
|
|
632
687
|
library_convert.convert_once()
|
|
633
688
|
model = library_pricing.find(model_id, library_pricing.entries())
|
|
634
689
|
record, job = _claim(model, "remove")
|
|
690
|
+
reg = record.get("registration")
|
|
691
|
+
removed_pi_model = record.get("pi_model") or (reg.get("pi_model") if reg is not None else None)
|
|
692
|
+
still_served = False
|
|
635
693
|
with library_state.held([job]):
|
|
694
|
+
active_plan = record["plan"]
|
|
636
695
|
if record["state"] != "idle":
|
|
637
696
|
stop(record, library_jobs.executor())
|
|
638
697
|
with library_state.locked():
|
|
@@ -640,5 +699,14 @@ def remove(model_id: str, base_dir: str) -> Row:
|
|
|
640
699
|
library_jobs.dests(record["plan"]), library_jobs.in_use(model.id)
|
|
641
700
|
)
|
|
642
701
|
_forget_deployment(record["plan"])
|
|
702
|
+
if active_plan["name"] != record["plan"]["name"]:
|
|
703
|
+
_forget_deployment(active_plan)
|
|
643
704
|
library_state.forget(model.id)
|
|
705
|
+
if removed_pi_model:
|
|
706
|
+
still_served = any(
|
|
707
|
+
r.get("state") == "loaded" and r.get("pi_model") == removed_pi_model
|
|
708
|
+
for r in library_state.records()
|
|
709
|
+
)
|
|
710
|
+
if not still_served:
|
|
711
|
+
_clear_removed_source(removed_pi_model)
|
|
644
712
|
return _row(model, base_dir)
|
|
@@ -98,6 +98,7 @@ class Record(_RecordRequired, total=False):
|
|
|
98
98
|
stack_provider: str # converted: its own stack provider, the main or the fastest LLM
|
|
99
99
|
pi_model: str # what pi offers once it is loaded; fixed when the record is made
|
|
100
100
|
load_posture: LoadPosture # elastic posture & warning metadata recorded on load
|
|
101
|
+
baseline_plan: Plan # pristine capacity plan preserved while a degraded/active load runs
|
|
101
102
|
|
|
102
103
|
|
|
103
104
|
class _JobSince20261113(TypedDict, total=False):
|
|
@@ -256,8 +257,10 @@ def cancelled(job: Job) -> bool:
|
|
|
256
257
|
|
|
257
258
|
|
|
258
259
|
def clear_job(model: str) -> None:
|
|
260
|
+
job = job_path(model)
|
|
259
261
|
for path in (
|
|
260
|
-
|
|
262
|
+
job,
|
|
263
|
+
job.with_name(job.name + ".tmp"),
|
|
261
264
|
cancel_path(model),
|
|
262
265
|
pid_path(model),
|
|
263
266
|
Path(str(pid_path(model)) + ".identity.json"),
|
|
@@ -186,10 +186,24 @@ def _state(lib: Library, model: str, record: Record | None) -> tuple[str, Proble
|
|
|
186
186
|
return "idle", None
|
|
187
187
|
|
|
188
188
|
|
|
189
|
-
def _plan_of(
|
|
190
|
-
|
|
191
|
-
|
|
189
|
+
def _plan_of(
|
|
190
|
+
lib: Library,
|
|
191
|
+
model: Model,
|
|
192
|
+
record: Record | None,
|
|
193
|
+
priced: Priced,
|
|
194
|
+
*,
|
|
195
|
+
state: str | None = None,
|
|
196
|
+
) -> Plan | None:
|
|
197
|
+
"""The plan a row shows: its record's (preferring ``baseline_plan`` whenever not loaded so a
|
|
198
|
+
prior degraded load never pollutes idle/failed specs); for a model a live job is downloading,
|
|
199
|
+
the price on the pool that job recorded (status never moves a running download to another card)."""
|
|
192
200
|
if record is not None:
|
|
201
|
+
if (
|
|
202
|
+
state is not None
|
|
203
|
+
and state != "loaded"
|
|
204
|
+
and (baseline := record.get("baseline_plan")) is not None
|
|
205
|
+
):
|
|
206
|
+
return baseline
|
|
193
207
|
return record["plan"]
|
|
194
208
|
job, alive = lib.jobs.get(model.id, (None, False))
|
|
195
209
|
if job is not None and alive and job["pool"] != priced.pool:
|
|
@@ -428,7 +442,7 @@ def row(lib: Library, model: Model) -> Row:
|
|
|
428
442
|
record = lib.records.get(model.id)
|
|
429
443
|
priced = lib.judge(model)
|
|
430
444
|
state, problem = _state(lib, model.id, record)
|
|
431
|
-
plan = _plan_of(lib, model, record, priced)
|
|
445
|
+
plan = _plan_of(lib, model, record, priced, state=state)
|
|
432
446
|
job, alive = lib.jobs.get(model.id, (None, False))
|
|
433
447
|
fallback_memory, fallback_window, fallback_vision, fallback_download = (
|
|
434
448
|
library_floor.floor_metadata(
|
|
@@ -226,8 +226,8 @@ def inactive_anon_bytes(facts: HostFacts) -> int:
|
|
|
226
226
|
anonymous = max(0, int(ram["anonymous_bytes"]))
|
|
227
227
|
purgeable = max(0, int(ram["purgeable_bytes"]))
|
|
228
228
|
non_purgeable_anon = max(0, anonymous - purgeable)
|
|
229
|
-
lower = max(0, inactive - max(0, file_backed - speculative))
|
|
230
229
|
upper = min(inactive, non_purgeable_anon)
|
|
230
|
+
lower = min(upper, max(0, inactive - max(0, file_backed - speculative) - purgeable))
|
|
231
231
|
if active + inactive > 0:
|
|
232
232
|
est = int(non_purgeable_anon * (inactive / (active + inactive)))
|
|
233
233
|
return max(lower, min(upper, est))
|
|
@@ -87,9 +87,9 @@ def parse_vm_stat_details(vm_stat: str) -> dict[str, int]:
|
|
|
87
87
|
"""Byte breakdown of macOS ``vm_stat`` counters, including estimated inactive anonymous memory.
|
|
88
88
|
|
|
89
89
|
Returns an empty dict when ``vm_stat`` is unreadable. Inactive anonymous pages are bounded
|
|
90
|
-
between ``max(0, inactive - max(0, file_backed - speculative))`` and
|
|
91
|
-
``min(inactive, max(0, anonymous - purgeable))``, estimated proportionally by the
|
|
92
|
-
share of active+inactive paged memory.
|
|
90
|
+
between ``min(upper, max(0, inactive - max(0, file_backed - speculative) - purgeable))`` and
|
|
91
|
+
``upper = min(inactive, max(0, anonymous - purgeable))``, estimated proportionally by the
|
|
92
|
+
inactive share of active+inactive paged memory without double-counting purgeable pages.
|
|
93
93
|
"""
|
|
94
94
|
parsed = _vm_stat_counts(vm_stat)
|
|
95
95
|
if parsed is None:
|
|
@@ -122,8 +122,8 @@ def parse_vm_stat_details(vm_stat: str) -> dict[str, int]:
|
|
|
122
122
|
anonymous = counts["Anonymous pages"]
|
|
123
123
|
purgeable = counts["Pages purgeable"]
|
|
124
124
|
non_purgeable_anon = max(0, anonymous - purgeable)
|
|
125
|
-
lower = max(0, inactive - max(0, file_backed - speculative))
|
|
126
125
|
upper = min(inactive, non_purgeable_anon)
|
|
126
|
+
lower = min(upper, max(0, inactive - max(0, file_backed - speculative) - purgeable))
|
|
127
127
|
if active + inactive > 0:
|
|
128
128
|
est = int(non_purgeable_anon * (inactive / (active + inactive)))
|
|
129
129
|
inactive_anon = max(lower, min(upper, est))
|
|
@@ -325,7 +325,10 @@ def service_name(base_dir: str, name: str) -> str:
|
|
|
325
325
|
|
|
326
326
|
|
|
327
327
|
def _same_dir(a: str, b: str) -> bool:
|
|
328
|
-
|
|
328
|
+
def norm(path: str) -> str:
|
|
329
|
+
return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
|
|
330
|
+
|
|
331
|
+
return norm(a) == norm(b)
|
|
329
332
|
|
|
330
333
|
|
|
331
334
|
def resolved_name(model_id: str, port: int, base_dir: str, taken: Mapping[str, str]) -> str:
|
|
@@ -6,6 +6,7 @@ import os
|
|
|
6
6
|
import shlex
|
|
7
7
|
import shutil
|
|
8
8
|
import subprocess
|
|
9
|
+
import sys
|
|
9
10
|
import time
|
|
10
11
|
from pathlib import Path
|
|
11
12
|
|
|
@@ -165,3 +166,41 @@ def command_matches(pid: int, expected: list[str], root: str = "/") -> bool:
|
|
|
165
166
|
return argv_matches(actual, process.joinpath("exe"), expected, root)
|
|
166
167
|
except (OSError, ValueError, UnicodeError):
|
|
167
168
|
return False
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def bind_to_parent(parent: object) -> None:
|
|
172
|
+
"""End this local POSIX streaming helper when its controller dies (e.g. SIGKILL), matching
|
|
173
|
+
Windows's kill-on-close job object so an orphan never keeps writing ``.part`` files after
|
|
174
|
+
``cancel`` or a resumed download took over."""
|
|
175
|
+
if not isinstance(parent, int) or isinstance(parent, bool) or parent <= 1 or os.name == "nt":
|
|
176
|
+
return
|
|
177
|
+
armed = False
|
|
178
|
+
if sys.platform.startswith("linux"):
|
|
179
|
+
try:
|
|
180
|
+
import ctypes
|
|
181
|
+
import signal
|
|
182
|
+
|
|
183
|
+
libc = ctypes.CDLL(None)
|
|
184
|
+
libc.prctl.argtypes = (
|
|
185
|
+
ctypes.c_int,
|
|
186
|
+
ctypes.c_ulong,
|
|
187
|
+
ctypes.c_ulong,
|
|
188
|
+
ctypes.c_ulong,
|
|
189
|
+
ctypes.c_ulong,
|
|
190
|
+
)
|
|
191
|
+
libc.prctl.restype = ctypes.c_int
|
|
192
|
+
armed = libc.prctl(1, signal.SIGKILL, 0, 0, 0) == 0 # PR_SET_PDEATHSIG = 1
|
|
193
|
+
except (OSError, AttributeError):
|
|
194
|
+
armed = False
|
|
195
|
+
if os.getppid() != parent:
|
|
196
|
+
os._exit(1)
|
|
197
|
+
if not armed:
|
|
198
|
+
import threading
|
|
199
|
+
|
|
200
|
+
def _watch() -> None:
|
|
201
|
+
while True:
|
|
202
|
+
time.sleep(0.2)
|
|
203
|
+
if os.getppid() != parent:
|
|
204
|
+
os._exit(1)
|
|
205
|
+
|
|
206
|
+
threading.Thread(target=_watch, name="parent-watch", daemon=True).start()
|
|
@@ -619,6 +619,8 @@ def unpack(archive: str, directory: str, keep: tuple[str, ...] = ()) -> None:
|
|
|
619
619
|
member.mode |= 0o700
|
|
620
620
|
elif member.isfile():
|
|
621
621
|
member.mode |= 0o200
|
|
622
|
+
if member.issym() or member.islnk():
|
|
623
|
+
remote_ops_download.clear_link(os.path.join(directory, name))
|
|
622
624
|
tar.extract(member, directory)
|
|
623
625
|
|
|
624
626
|
|
|
@@ -729,9 +731,8 @@ ACTIONS: Actions = {
|
|
|
729
731
|
|
|
730
732
|
|
|
731
733
|
def main(argv: list[str]) -> int:
|
|
732
|
-
|
|
733
|
-
#
|
|
734
|
-
os.umask(os.umask(0o022) | 0o022)
|
|
734
|
+
remote_ops_download.bind_to_parent(globals().get("_PARENT_PID"))
|
|
735
|
+
os.umask(os.umask(0o022) | 0o022) # never leave group/world-writable files under umask 0002
|
|
735
736
|
encoded = globals().get("_PARAMS_B64") or (argv[2] if len(argv) == 3 else None)
|
|
736
737
|
if len(argv) not in (2, 3) or argv[1] not in ACTIONS or encoded is None:
|
|
737
738
|
sys.stderr.write("usage: remote_ops.py {{{}}} [PARAMS_B64]\n".format("|".join(ACTIONS)))
|
|
@@ -21,8 +21,15 @@ import urllib.request
|
|
|
21
21
|
from typing import Iterator, Tuple
|
|
22
22
|
|
|
23
23
|
try:
|
|
24
|
-
from localmodels import
|
|
24
|
+
from localmodels import (
|
|
25
|
+
process_identity_linux,
|
|
26
|
+
remote_ops,
|
|
27
|
+
remote_ops_mirrors,
|
|
28
|
+
remote_ops_prepare,
|
|
29
|
+
remote_ops_ranges,
|
|
30
|
+
)
|
|
25
31
|
except ImportError: # run as a bare file from this directory
|
|
32
|
+
import process_identity_linux # type: ignore[import-not-found,no-redef]
|
|
26
33
|
import remote_ops # type: ignore[import-not-found,no-redef]
|
|
27
34
|
import remote_ops_mirrors # type: ignore[import-not-found,no-redef]
|
|
28
35
|
import remote_ops_prepare # type: ignore[import-not-found,no-redef]
|
|
@@ -40,29 +47,33 @@ def act_engine(p: remote_ops.EngineParams) -> None:
|
|
|
40
47
|
if os.path.exists(done_marker) and remote_ops._read(done_marker).strip() == expected:
|
|
41
48
|
remote_ops.emit("result", binary=binary, reused=True)
|
|
42
49
|
return
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
a["
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
50
|
+
with remote_ops_mirrors.engine_lock(directory):
|
|
51
|
+
if os.path.exists(done_marker) and remote_ops._read(done_marker).strip() == expected:
|
|
52
|
+
remote_ops.emit("result", binary=binary, reused=True)
|
|
53
|
+
return
|
|
54
|
+
os.makedirs(directory, exist_ok=True)
|
|
55
|
+
cache = os.path.join(os.path.dirname(directory), ".archives")
|
|
56
|
+
active_region = p.get("region")
|
|
57
|
+
for i in remote_ops.each_file(
|
|
58
|
+
[(os.path.join(cache, a["name"]), a["size_bytes"]) for a in p["assets"]]
|
|
59
|
+
):
|
|
60
|
+
a = p["assets"][i]
|
|
61
|
+
archive = os.path.join(cache, a["name"])
|
|
62
|
+
switched = remote_ops.fetch(
|
|
63
|
+
a["url"],
|
|
64
|
+
archive,
|
|
65
|
+
a["sha256"],
|
|
66
|
+
a["size_bytes"],
|
|
67
|
+
a["name"],
|
|
68
|
+
npm_copies(a),
|
|
69
|
+
active_region,
|
|
70
|
+
)
|
|
71
|
+
if switched in ("cn", "global"):
|
|
72
|
+
active_region = switched
|
|
73
|
+
remote_ops.unpack(archive, directory, tuple(a.get("members") or ()))
|
|
74
|
+
if not os.access(binary, os.X_OK):
|
|
75
|
+
raise RuntimeError(f"the engine has no executable {os.path.relpath(binary, directory)}")
|
|
76
|
+
remote_ops._write(done_marker, expected)
|
|
66
77
|
remote_ops.emit("result", binary=binary, reused=False)
|
|
67
78
|
|
|
68
79
|
|
|
@@ -234,6 +245,8 @@ _load_ranges = remote_ops_mirrors.load_ranges
|
|
|
234
245
|
_save_ranges = remote_ops_mirrors.save_ranges
|
|
235
246
|
kept_bytes = remote_ops_mirrors.kept_bytes
|
|
236
247
|
discard = remote_ops_mirrors.discard
|
|
248
|
+
clear_link = remote_ops_mirrors.clear_link
|
|
249
|
+
bind_to_parent = process_identity_linux.bind_to_parent
|
|
237
250
|
|
|
238
251
|
|
|
239
252
|
def npm_transfer(source: remote_ops.Source, part: str, size: int, label: str) -> None:
|
|
@@ -7,6 +7,7 @@ Part of the remote_ops bundle (transport.BUNDLES): standard library only, Python
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
9
|
import collections
|
|
10
|
+
import contextlib
|
|
10
11
|
import json
|
|
11
12
|
import os
|
|
12
13
|
import shutil
|
|
@@ -14,6 +15,7 @@ import tarfile
|
|
|
14
15
|
import time
|
|
15
16
|
import urllib.parse
|
|
16
17
|
import urllib.request
|
|
18
|
+
from typing import Iterator
|
|
17
19
|
|
|
18
20
|
try:
|
|
19
21
|
from localmodels import remote_ops
|
|
@@ -232,9 +234,48 @@ def kept_bytes(part: str, size: int) -> int:
|
|
|
232
234
|
|
|
233
235
|
|
|
234
236
|
def discard(part: str) -> None:
|
|
235
|
-
for path in (part, state_path(part)):
|
|
236
|
-
|
|
237
|
+
for path in (part, state_path(part), state_path(part) + ".tmp", part + ".tmp", part + ".npm"):
|
|
238
|
+
try:
|
|
237
239
|
os.remove(path)
|
|
240
|
+
except FileNotFoundError:
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def clear_link(target: str) -> None:
|
|
245
|
+
"""Remove an existing file or symlink before tar.extract recreates a link member."""
|
|
246
|
+
if os.path.islink(target) or os.path.isfile(target):
|
|
247
|
+
os.unlink(target)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@contextlib.contextmanager
|
|
251
|
+
def engine_lock(directory: str) -> Iterator[None]:
|
|
252
|
+
"""Serialize concurrent engine fetches and unpacks under the same engines root so parallel
|
|
253
|
+
model downloads never race on ``.archives/*.part`` or ``unpack()``."""
|
|
254
|
+
parent = os.path.dirname(directory) or "."
|
|
255
|
+
os.makedirs(parent, exist_ok=True)
|
|
256
|
+
lock_path = os.path.join(parent, ".engine.lock")
|
|
257
|
+
with open(lock_path, "a+") as lock:
|
|
258
|
+
if os.name == "nt":
|
|
259
|
+
import msvcrt
|
|
260
|
+
|
|
261
|
+
lock.seek(0)
|
|
262
|
+
while True:
|
|
263
|
+
try:
|
|
264
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_NBLCK, 1) # type: ignore[attr-defined]
|
|
265
|
+
break
|
|
266
|
+
except OSError:
|
|
267
|
+
time.sleep(0.1)
|
|
268
|
+
try:
|
|
269
|
+
yield
|
|
270
|
+
finally:
|
|
271
|
+
with contextlib.suppress(OSError):
|
|
272
|
+
lock.seek(0)
|
|
273
|
+
msvcrt.locking(lock.fileno(), msvcrt.LK_UNLCK, 1) # type: ignore[attr-defined]
|
|
274
|
+
else:
|
|
275
|
+
import fcntl
|
|
276
|
+
|
|
277
|
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
|
278
|
+
yield
|
|
238
279
|
|
|
239
280
|
|
|
240
281
|
def npm_transfer(
|