Merge pull request #2797 from infinito-nexus/fix/svc-ai-lmstudio/pull-resume-on-reset

fix(svc-ai-lmstudio): fetch the preload models from their declared url
This commit is contained in:
kevinveenbirkenbach authored and GitHub committed 2026-11-24 01:23:06 +01:00
commit 9223522c43
17 files changed
+472 -518

No files matched your search

+2 -2
View File
@@ -13,8 +13,8 @@ This role deploys LM Studio as a headless model server in a single container, in
- **OpenAI-compatible endpoint:** The headless server answers `/v1` requests on port 1234 inside the container network.
- **CPU inference:** The role builds its own image from the pinned llmster release for the host's architecture, amd64 or arm64, keeps only the CPU llama.cpp engine and passes no GPU device into the container.
- **Persistent model store:** A named volume mounted at `/root/.lmstudio` keeps downloaded models and server settings across redeploys.
- **Preloaded models:** Every entry of `services.lmstudio.preload_models` is downloaded on the hosting node with `lms get --gguf`, overlapped and reaped like the Ollama pre-pull. A download that outlives its budget is cancelled inside the container through the interrupt prompt of `lms get`, so LM Studio drops the transfer and the retry downloads afresh instead of following the stalled one. Each entry carries the `source` repository to download, the `quant` variant to take from it, the `name` LM Studio indexes that repository under and the gateway addresses it by, and the `alias` the gateway publishes it as. `source` is a full Hugging Face URL, never a search term: a search term resolves to whichever model the catalogue lists first. `quant` is appended as `@<variant>` and is required: without it LM Studio picks the variant itself, and the `file`, `sha256` and `bytes` the entry declares then describe a guess that the store check and the download budget are both measured against.
- **Loading:** The pre-pull downloads without loading. LM Studio serves with just-in-time loading, so the first `/v1/chat/completions` naming a `name` loads that model; the gateway's warm task issues that first request at deploy time.
- **Preloaded models:** Every entry of `services.lmstudio.preload_models` is fetched from its declared `url` straight into the model store, never through `lms get` and LM Studio's Hugging Face proxy. One task file serves both paths: Swarm with a shared NFS store seeds it once before the daemons start, and every other deployment fetches into the model volume on each hosting node. The fetch retries a failed or reset transfer inside a budget derived from the declared `bytes`, `preload_floor_seconds` and `preload_min_bytes_per_second`, and the deploy fails when no source delivered a model or the stored file does not match its declared `sha256` and `bytes`. Each entry also carries the `source` repository and the `quant` variant the `file` belongs to, the `name` LM Studio indexes that repository under and the gateway addresses it by, and the `alias` the gateway publishes it as.
- **Loading:** The preload downloads without loading. LM Studio serves with just-in-time loading, so the first `/v1/chat/completions` naming a `name` loads that model; the gateway's warm task issues that first request at deploy time.
- **Gateway backend:** The LiteLLM Gateway publishes those aliases, which are the names Ollama serves too, so the same model name routes to whichever local backend a deployment runs.
- **Bounded resources:** The container is capped at 4 CPUs, 8 GB of memory and 2048 processes, and the role declares a minimum of 4 GB free storage for building the image; downloaded models grow the volume beyond that.
- **Backup integration:** Backup Docker Volumes snapshots the model volume when that role is present, without stopping the container.
-1
View File
@@ -33,7 +33,6 @@ lmstudio:
internal:
http: 1234
preload_models: "{{ AI_LOCAL_MODELS }}"
preload_async_time: 3600
preload_floor_seconds: 600
preload_min_bytes_per_second: 1000000
lifecycle: beta
+5 -1
View File
@@ -3,10 +3,14 @@
- name: "⬇️ Seed the shared model store before the daemons index it"
ansible.builtin.include_tasks:
file: utils/preseed.yml
file: utils/fetch.yml
apply:
delegate_to: "{{ LMSTUDIO_NFS_SERVER }}"
run_once: true
vars:
lmstudio_fetch_store: "{{ LMSTUDIO_SHARED_MODELS_PATH }}"
lmstudio_fetch_staging: "{{ LMSTUDIO_SHARED_STAGING_PATH }}"
lmstudio_fetch_node: "{{ LMSTUDIO_NFS_SERVER }}"
when: LMSTUDIO_PRESEED_ENABLED | bool
- name: "🥾 Bootstrap the compose host once before staging the build context"
+150
View File
@@ -0,0 +1,150 @@
---
# Param: lmstudio_fetch_store directory on the target that holds <repo>/<file> of every model
# Param: lmstudio_fetch_staging directory on the store's filesystem where a download lands until it verifies
# Param: lmstudio_fetch_node the host that owns the store, named in the failure messages
- name: "📁 Create the model store directories on '{{ lmstudio_fetch_node }}'"
ansible.builtin.file:
path: "{{ lmstudio_fetch_store }}/{{ model.repo }}"
state: directory
mode: "0755"
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.file }}"
- name: "📁 Create the staging dir beside the model store on '{{ lmstudio_fetch_node }}'"
ansible.builtin.file:
path: "{{ lmstudio_fetch_staging }}"
state: directory
mode: "0755"
- name: "🔍 Find partial downloads a broken fetch left on '{{ lmstudio_fetch_node }}'"
ansible.builtin.find:
paths: "{{ lmstudio_fetch_staging }}"
file_type: any
hidden: true
register: lmstudio_staging_leftovers
- name: "🧹 Remove partial downloads a broken fetch left on '{{ lmstudio_fetch_node }}'"
ansible.builtin.file:
path: "{{ leftover.path }}"
state: absent
loop: "{{ lmstudio_staging_leftovers.files }}"
loop_control:
loop_var: leftover
label: "{{ leftover.path | basename }}"
- name: "🔍 Read what the model store on '{{ lmstudio_fetch_node }}' already holds"
ansible.builtin.stat:
path: "{{ lmstudio_fetch_store }}/{{ model.repo }}/{{ model.file }}"
checksum_algorithm: sha256
register: lmstudio_present
changed_when: false
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.file }}"
- name: "🗄️ Measure the free space the model store on '{{ lmstudio_fetch_node }}' offers"
ansible.builtin.command: "df -P -B1 {{ lmstudio_fetch_store | quote }}"
register: lmstudio_store_space
changed_when: false
- name: "🛑 Refuse to fetch models the store on '{{ lmstudio_fetch_node }}' cannot hold"
vars:
_free: "{{ lmstudio_store_space.stdout_lines[1].split()[3] | int }}"
_pending: >-
{%- set tally = namespace(bytes=0) -%}
{%- for present in lmstudio_present.results
if not (present.stat.exists and present.stat.checksum == present.model.sha256) -%}
{%- set tally.bytes = tally.bytes + (present.model.bytes | int) -%}
{%- endfor -%}
{{ tally.bytes }}
ansible.builtin.fail:
msg: >-
The model store {{ lmstudio_fetch_store }} on {{ lmstudio_fetch_node }} has
{{ (_free | int / 1024 / 1024 / 1024) | round(1) }} GiB free but needs
{{ (_pending | int / 1024 / 1024 / 1024) | round(1) }} GiB for the declared
models it does not hold at their digest yet. Shrink AI_LOCAL_MODELS in
group_vars/all/16_ai.yml or give {{ lmstudio_fetch_node }} more space.
when: _free | int < _pending | int
- name: "⬇️ Fetch the models into the store on '{{ lmstudio_fetch_node }}'"
get_url_retry:
url: "{{ model.url }}"
dest: "{{ lmstudio_fetch_store }}/{{ model.repo }}/{{ model.file }}"
tmp_dest: "{{ lmstudio_fetch_staging }}"
checksum: "sha256:{{ model.sha256 }}"
mode: "0644"
vars:
_bytes: "{{ model.bytes }}"
_budget: &lmstudio_fetch_budget >-
{{ [ LMSTUDIO_PRELOAD_FLOOR_SECONDS | int,
((_bytes | int) / (LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND | int))
| round(0, 'ceil') | int ] | max }}
timeout: "{{ lookup('timeout', _budget) | int }}"
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.file }}"
register: lmstudio_fetch
changed_when: false
ignore_errors: true
- name: "🪞 Fetch from a mirror when the source failed on '{{ lmstudio_fetch_node }}'"
get_url_retry:
url: "{{ item.1 }}"
dest: "{{ lmstudio_fetch_store }}/{{ item.0.repo }}/{{ item.0.file }}"
tmp_dest: "{{ lmstudio_fetch_staging }}"
checksum: "sha256:{{ item.0.sha256 }}"
mode: "0644"
vars:
_bytes: "{{ item.0.bytes }}"
_budget: *lmstudio_fetch_budget
timeout: "{{ lookup('timeout', _budget) | int }}"
loop: "{{ LMSTUDIO_PRELOAD_MODELS | subelements('mirrors', skip_missing=True) }}"
loop_control:
label: "{{ item.0.file }} from {{ item.1 }}"
register: lmstudio_fetch_mirror
changed_when: false
ignore_errors: true
- name: "🔍 Read back what the model store on '{{ lmstudio_fetch_node }}' now holds"
ansible.builtin.stat:
path: "{{ lmstudio_fetch_store }}/{{ model.repo }}/{{ model.file }}"
checksum_algorithm: sha256
register: lmstudio_seeded
changed_when: false
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.file }}"
- name: "🛑 Fail when no source delivered a declared model to '{{ lmstudio_fetch_node }}'"
vars:
_missing: >-
{{ lmstudio_seeded.results
| rejectattr('stat.exists')
| map(attribute='model.file') | list }}
_said: >-
{{ (lmstudio_fetch.results | map(attribute='msg') | select | list)
+ (lmstudio_fetch_mirror.results | default([]) | map(attribute='msg') | select | list) }}
ansible.builtin.fail:
msg: >-
The model store {{ lmstudio_fetch_store }} on {{ lmstudio_fetch_node }} is missing
{{ _missing | join(', ') }}. What the sources answered:
{{ _said | join(' | ') }}
when: _missing | length > 0
- name: "🛑 Fail when a stored model does not match its declared digest and size"
ansible.builtin.fail:
msg: >-
{{ item.model.file }} in the model store {{ lmstudio_fetch_store }} on
{{ lmstudio_fetch_node }} hashes to {{ item.stat.checksum }} at {{ item.stat.size }} bytes,
but AI_LOCAL_MODELS declares {{ item.model.sha256 }} at {{ item.model.bytes }} bytes.
loop: "{{ lmstudio_seeded.results | selectattr('stat.exists') | list }}"
loop_control:
label: "{{ item.model.file }}"
when: >-
item.stat.checksum != item.model.sha256
or (item.stat.size | int) != (item.model.bytes | int)
@@ -12,41 +12,23 @@
until: lmstudio_daemon_ready.rc == 0
delegate_to: "{{ lmstudio_node }}"
- name: "🗄️ Check the model store on '{{ lmstudio_node }}' before preloading"
- name: "⬇️ Preload the LM Studio models into the volume on '{{ lmstudio_node }}'"
when: not (LMSTUDIO_PRESEED_ENABLED | bool)
block:
- name: "🗄️ Measure the space the model store offers on '{{ lmstudio_node }}'"
ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node
container exec {{ LMSTUDIO_LOCAL_CID | quote }} df -P -B1 {{ LMSTUDIO_MODELS_TARGET | quote }}
register: lmstudio_store_space
- name: "🧭 Resolve the model volume's mountpoint on '{{ lmstudio_node }}'"
ansible.builtin.command: >-
container volume inspect --format '{{ "{{" }}.Mountpoint{{ "}}" }}'
{{ lookup('volume', application_id, 'lmstudio_models').name | quote }}
register: lmstudio_models_mountpoint
changed_when: false
retries: 30
delay: 2
until: lmstudio_store_space.rc == 0
delegate_to: "{{ lmstudio_node }}"
- name: "🛑 Refuse to preload models the store on '{{ lmstudio_node }}' cannot hold"
- name: "⬇️ Fetch the LM Studio models from their sources on '{{ lmstudio_node }}'"
ansible.builtin.include_tasks:
file: utils/fetch.yml
apply:
delegate_to: "{{ lmstudio_node }}"
vars:
_free: "{{ lmstudio_store_space.stdout_lines[1].split()[3] | int }}"
_required: "{{ LMSTUDIO_PRELOAD_LARGEST_BYTES | int }}"
ansible.builtin.fail:
msg: >-
The model store on {{ lmstudio_node }} has
{{ (_free | int / 1024 / 1024 / 1024) | round(1) }} GiB free, less than the
{{ (_required | int / 1024 / 1024 / 1024) | round(1) }} GiB the largest
declared model needs. Shrink AI_LOCAL_MODELS in group_vars/all/16_ai.yml or
give the node more disk.
when: _free | int < _required | int
- name: "⬇️ Preload the LM Studio models on '{{ lmstudio_node }}'"
block:
- name: "⬇️ Preload the LM Studio models (first pass)"
ansible.builtin.include_tasks: utils/preload/pull.yml
rescue:
- name: "🐝 Re-raise the preload failure unchanged in swarm" # nocheck: rescue-recovery a timed-out transfer leaves the daemon reporting 0.00% for every further pull, and restarting the container it owns is the only lever the role has, though CI job 105558224377 shows a restart returning rc 0 without clearing it; the generic capture cannot even try, so swarm re-raises here instead, because under any_errors_fatal a rescued host keeps running while every other host is already marked failed, and compose ends the block by preloading again so an unrecovered failure still re-raises
ansible.builtin.fail:
msg: "{{ ansible_failed_result.msg | default('LM Studio preload failed') }}"
when: IS_SWARM_MODE
- name: "♻️ Recover the wedged transfer and preload again"
ansible.builtin.include_tasks: utils/preload/recover.yml
lmstudio_fetch_store: "{{ lmstudio_models_mountpoint.stdout | trim }}"
lmstudio_fetch_staging: "{{ [lmstudio_models_mountpoint.stdout | trim, '.staging'] | path_join }}"
lmstudio_fetch_node: "{{ lmstudio_node }}"
@@ -1,61 +0,0 @@
---
- name: 🛑 Fail if a model's download budget outlasts the pre-pull async lifetime
ansible.builtin.assert:
that: (_budget | int) + 2 * (_grace | int) < (LMSTUDIO_PRELOAD_ASYNC_TIME | int)
fail_msg: >-
{{ model.alias }} needs {{ (_budget | int) + 2 * (_grace | int) }} s for its download budget and cancel,
but services.lmstudio.preload_async_time of svc-ai-lmstudio allows {{ LMSTUDIO_PRELOAD_ASYNC_TIME }} s;
raise it in the inventory.
quiet: true
vars:
_grace: &lmstudio_pull_grace 15
_budget: &lmstudio_pull_budget >-
{{ [ LMSTUDIO_PRELOAD_FLOOR_SECONDS | int,
((model.bytes | int) / (LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND | int))
| round(0, 'ceil') | int ] | max }}
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.alias }}"
when: ASYNC_ENABLED | bool
- name: ⬇️ Pre-pull LM Studio models
ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node
container exec {{ LMSTUDIO_LOCAL_CID | quote }}
sh -c 'echo N | timeout --foreground -s INT -k "$1" "$2" lms get --yes --gguf "$3"'
sh {{ _grace }} {{ _budget }} {{ (model.source ~ '@' ~ model.quant) | quote }}
vars:
_grace: *lmstudio_pull_grace
_budget: *lmstudio_pull_budget
environment:
CONTAINER_EXEC_TIMEOUT: "{{ (_budget | int) + 2 * (_grace | int) }}"
register: lmstudio_pull_result
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.alias }}"
# rationale: async; the reap below reads every job back before the play continues, so no model is still downloading when playwright starts
async: "{{ LMSTUDIO_PRELOAD_ASYNC_TIME if ASYNC_ENABLED | bool else omit }}"
poll: "{{ ASYNC_POLL if ASYNC_ENABLED | bool else omit }}"
retries: "{{ 0 if ASYNC_ENABLED | bool else 1 }}"
delay: 15
until: >
(lmstudio_pull_result.rc | default(0)) == 0 or
('You already have this model' in (lmstudio_pull_result.stderr | default('')))
changed_when: false
failed_when: >-
(lmstudio_pull_result.failed | default(false))
and 'You already have this model' not in ((lmstudio_pull_result.stdout | default('')) ~ (lmstudio_pull_result.stderr | default('')))
delegate_to: "{{ LMSTUDIO_HOST_NODE }}"
- name: "⏳ Reap the LM Studio model pre-pulls"
ansible.builtin.include_tasks:
file: utils/async/reap.yml
apply:
delegate_to: "{{ LMSTUDIO_HOST_NODE }}"
vars:
async_reap_jobs: "{{ lmstudio_pull_result.results | default([]) }}"
async_reap_label: "LM Studio model pre-pull"
async_reap_tolerate:
- "You already have this model"
ASYNC_TIME: "{{ LMSTUDIO_PRELOAD_ASYNC_TIME }}"
@@ -1,28 +0,0 @@
---
- name: "🩺 Dump the LM Studio transfer record"
ansible.builtin.shell: > # nocheck: container-exec-resolver runtime-resolved CID, delegated to the hosting node
container exec -i {{ LMSTUDIO_LOCAL_CID | quote }}
cat /root/.lmstudio/.internal/single-downloads-info.json
register: lmstudio_transfer_record
changed_when: false
failed_when: false
delegate_to: "{{ LMSTUDIO_HOST_NODE }}"
- name: "🩺 Report the LM Studio transfer record"
ansible.builtin.debug:
var: lmstudio_transfer_record.stdout
- name: "♻️ Restart LM Studio to release the wedged transfer"
ansible.builtin.command: container restart {{ LMSTUDIO_LOCAL_CID }}
changed_when: true
delegate_to: "{{ LMSTUDIO_HOST_NODE }}"
- name: "🔍 Re-resolve the {{ application_id }} hosting node + container id"
ansible.builtin.include_tasks: "{{ lookup('path_absolute', 'roles/sys-svc-compose/tasks/utils/swarm/resolve_host_cid.yml') }}"
vars:
resolve_service_key: "{{ entity_name }}"
resolve_output_prefix: LMSTUDIO
resolve_compose_cid: "{{ LMSTUDIO_CONTAINER }}"
- name: "⬇️ Preload the LM Studio models (after the restart)"
ansible.builtin.include_tasks: utils/preload/pull.yml
@@ -1,118 +0,0 @@
---
- name: "📁 Create the shared model store before the daemons start"
ansible.builtin.file:
path: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ model.repo }}"
state: directory
mode: "0755"
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.file }}"
- name: "📁 Create the staging directory beside the model store"
ansible.builtin.file:
path: "{{ LMSTUDIO_SHARED_STAGING_PATH }}"
state: directory
mode: "0755"
- name: "🔍 Read what the shared model store already holds"
ansible.builtin.stat:
path: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ model.repo }}/{{ model.file }}"
checksum_algorithm: sha256
register: lmstudio_present
changed_when: false
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.file }}"
- name: "🗄️ Measure the free space the shared model store offers"
ansible.builtin.command: "df -P -B1 {{ LMSTUDIO_SHARED_MODELS_PATH | quote }}"
register: lmstudio_export_space
changed_when: false
- name: "🛑 Refuse to fetch models the shared store cannot hold"
vars:
_free: "{{ lmstudio_export_space.stdout_lines[1].split()[3] | int }}"
_absent: >-
{{ lmstudio_present.results
| rejectattr('stat.exists')
| map(attribute='model.bytes') | map('int') | sum }}
_required: "{{ (_absent | int) + (LMSTUDIO_PRELOAD_LARGEST_BYTES | int) }}"
ansible.builtin.fail:
msg: >-
The shared model store on {{ LMSTUDIO_NFS_SERVER }} has
{{ (_free | int / 1024 / 1024 / 1024) | round(1) }} GiB free but needs
{{ (_required | int / 1024 / 1024 / 1024) | round(1) }} GiB: it is missing
{{ (_absent | int / 1024 / 1024 / 1024) | round(1) }} GiB of declared models,
plus {{ (LMSTUDIO_PRELOAD_LARGEST_BYTES | int / 1024 / 1024 / 1024) | round(1) }}
GiB for the largest one while it stages. Shrink AI_LOCAL_MODELS in
group_vars/all/16_ai.yml or grow the export.
when: _free | int < _required | int
- name: "⬇️ Fetch the models into the shared store"
get_url_retry:
url: "{{ model.url }}"
dest: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ model.repo }}/{{ model.file }}"
tmp_dest: "{{ LMSTUDIO_SHARED_STAGING_PATH }}"
checksum: "sha256:{{ model.sha256 }}"
mode: "0644"
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.file }}"
register: lmstudio_fetch
changed_when: false
failed_when: false
- name: "🪞 Fetch from a mirror when the source did not deliver"
get_url_retry:
url: "{{ item.1 }}"
dest: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ item.0.repo }}/{{ item.0.file }}"
tmp_dest: "{{ LMSTUDIO_SHARED_STAGING_PATH }}"
checksum: "sha256:{{ item.0.sha256 }}"
mode: "0644"
loop: "{{ LMSTUDIO_PRELOAD_MODELS | subelements('mirrors', skip_missing=True) }}"
loop_control:
label: "{{ item.0.file }} from {{ item.1 }}"
register: lmstudio_fetch_mirror
changed_when: false
failed_when: false
- name: "🔍 Read back what the shared model store now holds"
ansible.builtin.stat:
path: "{{ LMSTUDIO_SHARED_MODELS_PATH }}/{{ model.repo }}/{{ model.file }}"
checksum_algorithm: sha256
register: lmstudio_seeded
changed_when: false
loop: "{{ LMSTUDIO_PRELOAD_MODELS }}"
loop_control:
loop_var: model
label: "{{ model.file }}"
- name: "🛑 Fail when no source delivered a declared model"
vars:
_missing: >-
{{ lmstudio_seeded.results
| rejectattr('stat.exists')
| map(attribute='model.file') | list }}
_said: >-
{{ (lmstudio_fetch.results | map(attribute='msg') | select | list)
+ (lmstudio_fetch_mirror.results | default([]) | map(attribute='msg') | select | list) }}
ansible.builtin.fail:
msg: >-
The shared model store on {{ LMSTUDIO_NFS_SERVER }} is missing
{{ _missing | join(', ') }}. What the sources answered:
{{ _said | join(' | ') }}
when: _missing | length > 0
- name: "🛑 Fail when a seeded model does not match its checksum"
ansible.builtin.fail:
msg: >-
{{ item.model.file }} in the shared model store on {{ LMSTUDIO_NFS_SERVER }}
hashes to {{ item.stat.checksum }}, but AI_LOCAL_MODELS declares
{{ item.model.sha256 }}.
loop: "{{ lmstudio_seeded.results | selectattr('stat.exists') | list }}"
loop_control:
label: "{{ item.model.file }}"
when: item.stat.checksum != item.model.sha256
-3
View File
@@ -9,11 +9,8 @@ LMSTUDIO_APP_VERSION: "{{ lookup('config', application_id, 'services.lmstudio.ap
LMSTUDIO_BUILD_DIR: "{{ lookup('container', application_id, 'directories.instance') }}"
LMSTUDIO_PORT: "{{ lookup('config', application_id, 'services.lmstudio.ports.internal.http') }}"
LMSTUDIO_PRELOAD_MODELS: "{{ lookup('config', application_id, 'services.lmstudio.preload_models') }}"
LMSTUDIO_PRELOAD_ASYNC_TIME: "{{ lookup('config', application_id, 'services.lmstudio.preload_async_time') }}"
LMSTUDIO_PRELOAD_FLOOR_SECONDS: "{{ lookup('config', application_id, 'services.lmstudio.preload_floor_seconds') }}"
LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND: "{{ lookup('config', application_id, 'services.lmstudio.preload_min_bytes_per_second') }}"
LMSTUDIO_PRELOAD_LARGEST_BYTES: >-
{{ LMSTUDIO_PRELOAD_MODELS | map(attribute='bytes') | map('int') | max }}
LMSTUDIO_MODELS_TARGET: "{{ lookup('volume', application_id, 'lmstudio_models').target }}"
LMSTUDIO_NFS_SERVER: "{{ (groups['svc-storage-nfs-server'] | default([]))[0] | default(inventory_hostname) }}"
LMSTUDIO_SHARED_MODELS_PATH: "{{ [ STORAGE_NFS_STATE_PATH, lookup('volume', application_id, 'lmstudio_models').name ] | path_join }}"
@@ -0,0 +1,3 @@
from tests.integration.roles import PROJECT_ROOT
__all__ = ["PROJECT_ROOT"]
@@ -0,0 +1,290 @@
from __future__ import annotations
import hashlib
import json
import os
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import time
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from tests.integration.roles import PROJECT_ROOT
from utils.cache.yaml import load_yaml_any
TASKS = PROJECT_ROOT / "roles/svc-ai-lmstudio/tasks"
FETCH = TASKS / "utils/fetch.yml"
BLOB = bytes(range(256)) * 1024
REPO = "lmstudio-community/Probe-GGUF"
FILE = "Probe-Q4_K_M.gguf"
PLAYBOOK = """
- hosts: localhost
gather_facts: false
tasks:
- ansible.builtin.include_tasks: "{{ fetch }}"
"""
def _serve(resets: int, corrupt: bool) -> tuple[ThreadingHTTPServer, dict]:
"""
Args:
resets: how many transfers the source cuts off halfway with a TCP reset.
corrupt: whether every body the source sends differs from BLOB.
Returns:
The running source and its request counter.
"""
state = {"requests": 0}
class Source(BaseHTTPRequestHandler):
def do_GET(self) -> None:
state["requests"] += 1
body = bytes(reversed(BLOB)) if corrupt else BLOB
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
if state["requests"] <= resets:
self.wfile.write(body[: len(body) // 2])
self.wfile.flush()
self.connection.setsockopt(
socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)
)
self.connection.close()
self.close_connection = True
return
self.wfile.write(body)
def log_message(self, *args) -> None:
return
server = ThreadingHTTPServer(("127.0.0.1", 0), Source)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, state
def _fetch(
resets: int,
corrupt: bool,
floor: int,
stale: bool,
mirrors: list[bool],
free: int | None,
held: bytes | None,
) -> tuple[int, str, bytes, int, float, list[str]]:
"""
Args:
resets: how many transfers the source cuts off halfway.
corrupt: whether the source only ever sends other bytes than BLOB.
floor: the download budget floor in seconds.
stale: whether an interrupted earlier fetch left a partial in staging.
mirrors: per mirror, whether it only ever sends other bytes than BLOB.
free: the free bytes df reports for the store, None for the real figure.
held: what the store already holds at the model's path, None for nothing.
Returns:
The play's exit code, its output, the stored model (b"" when absent),
the requests the source answered, the play's wall time and what
staging holds afterwards.
"""
server, state = _serve(resets, corrupt)
sources = [server] + [_serve(0, bad)[0] for bad in mirrors]
try:
with tempfile.TemporaryDirectory() as scratch:
root = Path(scratch)
store = root / "store"
staging = store / ".staging"
stored = store / REPO / FILE
if stale:
staging.mkdir(parents=True)
(staging / "tmpinterrupted").write_bytes(BLOB[:1024])
if held is not None:
stored.parent.mkdir(parents=True)
stored.write_bytes(held)
host, port = server.server_address[:2]
variables = root / "vars.json"
variables.write_text(
json.dumps(
{
"fetch": str(FETCH),
"ansible_python_interpreter": sys.executable,
"lmstudio_fetch_store": str(store),
"lmstudio_fetch_staging": str(staging),
"lmstudio_fetch_node": "localhost",
"LMSTUDIO_PRELOAD_FLOOR_SECONDS": floor,
"LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND": 1_000_000,
"LMSTUDIO_PRELOAD_MODELS": [
{
"repo": REPO,
"file": FILE,
"url": f"http://{host}:{port}/{FILE}",
"mirrors": [
"http://{}:{}/{}".format(
*mirror.server_address[:2], FILE
)
for mirror in sources[1:]
],
"sha256": hashlib.sha256(BLOB).hexdigest(),
"bytes": len(BLOB),
}
],
}
),
encoding="utf-8",
)
playbook = root / "playbook.yml"
playbook.write_text(PLAYBOOK, encoding="utf-8")
env = {
**os.environ,
"ANSIBLE_CONFIG": str(PROJECT_ROOT / "ansible.cfg"),
"ANSIBLE_HOME": str(root / "ansible-home"),
"ANSIBLE_LOCAL_TEMP": str(root / "ansible-local"),
"ANSIBLE_REMOTE_TEMP": str(root / "ansible-remote"),
}
if free is not None:
bin_dir = root / "bin"
bin_dir.mkdir()
df = bin_dir / "df"
df.write_text(
"#!/bin/sh\n"
"echo 'Filesystem 1-blocks Used Available Capacity Mounted on'\n"
f"echo 'probe 0 0 {free} 0% /'\n",
encoding="utf-8",
)
df.chmod(0o755)
env["PATH"] = f"{bin_dir}{os.pathsep}{env['PATH']}"
began = time.monotonic()
result = subprocess.run(
[
sys.executable,
"-m",
"ansible.cli.playbook",
"-i",
"localhost,",
"-c",
"local",
str(playbook),
"-e",
f"@{variables}",
],
cwd=str(PROJECT_ROOT),
env=env,
capture_output=True,
text=True,
check=False,
timeout=600,
)
elapsed = time.monotonic() - began
body = b""
if stored.exists():
body = stored.read_bytes() # nocheck: cache-read the play wrote it
return (
result.returncode,
result.stdout + result.stderr,
body,
state["requests"],
elapsed,
sorted(os.listdir(staging)) if staging.exists() else [],
)
finally:
for source in sources:
source.shutdown()
source.server_close()
def _includes_fetch(tasks: list) -> bool:
"""
Args:
tasks: a parsed task list.
Returns:
Whether any task in it, nested blocks included, includes utils/fetch.yml.
"""
for task in tasks or []:
include = task.get("ansible.builtin.include_tasks")
target = include.get("file") if isinstance(include, dict) else include
if target == "utils/fetch.yml":
return True
if any(_includes_fetch(task.get(key)) for key in ("block", "rescue")):
return True
return False
class TestFetch(unittest.TestCase):
def test_a_reset_transfer_costs_a_retry_not_the_deploy(self) -> None:
rc, output, body, requests, _elapsed, _staged = _fetch(
1, False, 60, False, [], None, None
)
self.assertEqual(rc, 0, output[-3000:])
self.assertEqual(body, BLOB)
self.assertEqual(requests, 2)
def test_an_interrupted_fetch_leaves_no_partial_behind(self) -> None:
rc, output, body, _requests, _elapsed, staged = _fetch(
0, False, 60, True, [], None, None
)
self.assertEqual(rc, 0, output[-3000:])
self.assertEqual(body, BLOB)
self.assertEqual(staged, [])
def test_a_source_that_never_verifies_fails_closed_inside_the_budget(self) -> None:
rc, output, body, requests, elapsed, _staged = _fetch(
0, True, 4, False, [], None, None
)
self.assertNotEqual(rc, 0, output[-3000:])
self.assertIn("Timed out after 4 second(s)", output, output[-3000:])
self.assertEqual(body, b"")
self.assertGreater(requests, 0)
self.assertLess(elapsed, 4 + 30)
def test_a_timed_out_source_hands_over_to_the_next_mirror(self) -> None:
rc, output, body, requests, _elapsed, _staged = _fetch(
0, True, 4, False, [True, False], None, None
)
self.assertEqual(rc, 0, output[-3000:])
self.assertIn("Timed out after 4 second(s)", output, output[-3000:])
self.assertEqual(body, BLOB)
self.assertGreater(requests, 0)
def test_a_timed_out_mirror_still_reaches_the_final_check(self) -> None:
rc, output, body, _requests, _elapsed, _staged = _fetch(
0, True, 4, False, [True], None, None
)
self.assertNotEqual(rc, 0, output[-3000:])
self.assertIn("What the sources answered", output, output[-3000:])
self.assertEqual(body, b"")
def test_an_absent_model_counts_once_against_the_free_space(self) -> None:
rc, output, body, _requests, _elapsed, _staged = _fetch(
0, False, 60, False, [], len(BLOB) * 3 // 2, None
)
self.assertEqual(rc, 0, output[-3000:])
self.assertEqual(body, BLOB)
def test_a_held_model_with_another_digest_counts_as_pending(self) -> None:
held = bytes(reversed(BLOB))
rc, output, body, requests, _elapsed, _staged = _fetch(
0, False, 60, False, [], len(BLOB) // 2, held
)
self.assertNotEqual(rc, 0, output[-3000:])
self.assertIn("GiB free but needs", output, output[-3000:])
self.assertEqual(body, held)
self.assertEqual(requests, 0)
def test_the_swarm_seed_and_the_node_preload_share_one_fetch(self) -> None:
for caller in ("00_core.yml", "utils/preload/node.yml"):
with self.subTest(caller=caller):
self.assertTrue(
_includes_fetch(
load_yaml_any(str(TASKS / caller), default_if_missing=[])
)
)
if __name__ == "__main__":
unittest.main()
@@ -2,15 +2,15 @@
Rationale
=========
``roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml`` downloads with
``lms get --yes --gguf <source>@<quant>``. Without the ``@<quant>`` suffix LM
Studio picks the variant itself, and the ``file``, ``sha256`` and ``bytes`` the
entry declares become a guess about that pick rather than a description of it.
``roles/svc-ai-lmstudio/tasks/utils/fetch.yml`` downloads the entry's ``url``
into ``<models>/<repo>/<file>`` and verifies it against ``sha256`` and
``bytes``. ``quant`` names the variant those four fields describe, so an entry
whose ``file`` carries another variant pins a digest to the wrong blob.
Two shipped checks measure against those fields, so the guess is not harmless.
Two shipped checks measure against those fields, so the drift is not harmless.
``roles/svc-ai-lmstudio/files/test/test.sh`` looks for
``<models>/<repo>/<file>`` and reports ``is not in the model store`` when the
store holds a different variant. ``pull.yml`` derives the download budget from
store holds a different variant. ``fetch.yml`` derives the download budget from
``bytes``, so a declaration smaller than the real file cuts the transfer off.
Run 36107421422 hit both at once: the entry declared ``Q4_K_M`` at 808 MB while
@@ -72,8 +72,8 @@ class TestLocalModelQuantPinned(unittest.TestCase):
]
self.assertFalse(
missing,
f"{self.rel}: {missing} declare no 'quant', so lms get picks the "
"variant and the declared file, sha256 and bytes describe a guess",
f"{self.rel}: {missing} declare no 'quant', so nothing names the "
"variant the declared file, sha256 and bytes describe",
)
def test_the_declared_file_carries_the_pinned_quantization(self) -> None:
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
Whitespace-only changes.
@@ -1,264 +0,0 @@
from __future__ import annotations
import os
import signal
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
from utils.cache.files import PROJECT_ROOT
from utils.cache.yaml import load_yaml_any
from utils.templating.ansible import _trust_as_template
PULL = PROJECT_ROOT / "roles/svc-ai-lmstudio/tasks/utils/preload/pull.yml"
WRAPPER = PROJECT_ROOT / "roles/sys-svc-container/files/python/container.py"
TASK = "⬇️ Pre-pull LM Studio models"
BUDGET_SECONDS = 2
FAKE_DOCKER = """
import shutil
import subprocess
import sys
args = sys.argv[2:]
flags = []
while args[0].startswith("-"):
flags.append(args.pop(0))
child = subprocess.Popen(
args[1:],
stdin=None if "-i" in flags else subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
start_new_session=True,
)
shutil.copyfileobj(child.stdout, sys.stdout.buffer)
sys.exit(child.wait())
"""
FAKE_LMS = """
import os
import signal
import sys
import time
from pathlib import Path
state = Path(os.environ["FAKE_LMS_STATE"])
job = state / "job"
def record(name, line):
with (state / name).open("a") as handle:
handle.write(line + "\\n")
def interrupted(signum, frame):
if sys.stdin.readline().strip().upper() == "N":
job.unlink()
record("events", "cancel")
else:
record("events", "background")
sys.exit(1)
signal.signal(signal.SIGINT, interrupted)
record("pids", str(os.getpid()))
if job.exists():
record("events", "attach")
else:
job.touch()
record("events", "start")
time.sleep(30)
"""
def _install(path: Path, content: str) -> None:
"""
Args:
path: where the executable lands.
content: its full text, shebang included.
"""
path.write_text(content, encoding="utf-8")
path.chmod(0o755)
def _lines(path: Path) -> list[str]:
"""
Args:
path: a record the fake lms appends to.
Returns:
Its lines, or [] while it does not exist.
"""
if not path.exists():
return []
return path.read_text().split() # nocheck: cache-read rewritten between reads
def _running(pid: int) -> bool:
"""
Args:
pid: a fake lms process.
Returns:
Whether it still runs.
"""
try:
os.kill(pid, 0)
except ProcessLookupError:
return False
return True
def _templar() -> tuple[dict, Templar]:
"""
Returns:
The pre-pull task and a templar holding one model whose budget is BUDGET_SECONDS.
"""
task = next(
task
for task in load_yaml_any(str(PULL), default_if_missing=[])
if task.get("name") == TASK
)
variables = {
"LMSTUDIO_LOCAL_CID": "lmstudio",
"LMSTUDIO_PRELOAD_FLOOR_SECONDS": BUDGET_SECONDS,
"LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND": 1_000_000,
"model": {
"alias": "llama3.2:1b",
"source": "https://huggingface.co/lmstudio-community/Llama-3.2-1B-Instruct-GGUF",
"quant": "Q4_K_M",
"bytes": 1,
},
}
for key, value in (task.get("vars") or {}).items():
variables[key] = _trust_as_template(value)
return task, Templar(loader=DataLoader(), variables=variables)
def _render(templar: Templar, value: str) -> str:
"""
Args:
templar: from _templar.
value: a task field.
Returns:
The field rendered.
"""
return str(templar.template(_trust_as_template(value)))
class TestTimedOutPull(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.scratch = tempfile.TemporaryDirectory()
root = Path(cls.scratch.name)
bin_dir = root / "bin"
cls.state = root / "state"
bin_dir.mkdir()
cls.state.mkdir()
_install(bin_dir / "docker", f"#!{sys.executable} -I\n{FAKE_DOCKER}")
_install(bin_dir / "lms", f"#!{sys.executable} -I\n{FAKE_LMS}")
_install(
bin_dir / "container",
f'#!/bin/sh\nexec "{sys.executable}" -I "{WRAPPER}" "$@"\n',
)
task, cls.templar = _templar()
command = _render(cls.templar, task["ansible.builtin.shell"])
cls.environment = {
key: _render(cls.templar, value)
for key, value in task["environment"].items()
}
env = {
**os.environ,
**cls.environment,
"PATH": f"{bin_dir}{os.pathsep}{os.environ['PATH']}",
"FAKE_LMS_STATE": str(cls.state),
}
cls.attempts = []
for _attempt in range(2):
result = subprocess.run(
["/bin/sh", "-c", command],
env=env,
stdin=subprocess.DEVNULL,
capture_output=True,
check=False,
timeout=120,
)
pid = int(_lines(cls.state / "pids")[-1])
cls.attempts.append((result.returncode, _running(pid)))
cls.events = _lines(cls.state / "events")
@classmethod
def tearDownClass(cls) -> None:
for pid in map(int, _lines(cls.state / "pids")):
if _running(pid):
os.kill(pid, signal.SIGKILL)
cls.scratch.cleanup()
def test_the_timeout_still_fails_the_attempt(self) -> None:
self.assertEqual([rc for rc, _alive in self.attempts], [124, 124])
def test_no_lms_outlives_its_attempt(self) -> None:
self.assertEqual([alive for _rc, alive in self.attempts], [False, False])
def test_the_timeout_cancels_the_transfer(self) -> None:
self.assertEqual(self.events[:2], ["start", "cancel"])
def test_the_retry_downloads_afresh(self) -> None:
self.assertEqual(self.events, ["start", "cancel", "start", "cancel"])
def test_the_host_guard_outlasts_the_in_container_cancel(self) -> None:
self.assertGreater(
int(self.environment["CONTAINER_EXEC_TIMEOUT"]),
int(_render(self.templar, "{{ (_budget | int) + (_grace | int) }}")),
)
class TestBudgetGuard(unittest.TestCase):
def _holds(self, model_bytes: int) -> bool:
"""
Args:
model_bytes: the declared size of the one model to pre-pull.
Returns:
Whether the guard lets the pre-pull start under the shipped async lifetime.
"""
guard = next(
task
for task in load_yaml_any(str(PULL), default_if_missing=[])
if "ansible.builtin.assert" in task
)
variables = {
"LMSTUDIO_PRELOAD_ASYNC_TIME": 3600,
"LMSTUDIO_PRELOAD_FLOOR_SECONDS": 600,
"LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND": 1_000_000,
"model": {"alias": "probe", "bytes": model_bytes},
}
for key, value in guard["vars"].items():
variables[key] = _trust_as_template(value)
templar = Templar(loader=DataLoader(), variables=variables)
return (
_render(templar, f"{{{{ {guard['ansible.builtin.assert']['that']} }}}}")
== "True"
)
def test_the_guard_shares_the_pull_budget(self) -> None:
tasks = load_yaml_any(str(PULL), default_if_missing=[])
guard = next(task for task in tasks if "ansible.builtin.assert" in task)
pull = next(task for task in tasks if task.get("name") == TASK)
self.assertEqual(guard["vars"], pull["vars"])
def test_the_largest_budget_that_fits_passes(self) -> None:
self.assertTrue(self._holds(3_569_000_000))
def test_a_budget_reaching_the_async_lifetime_fails(self) -> None:
self.assertFalse(self._holds(3_570_000_000))
if __name__ == "__main__":
unittest.main()