From ff229ff51cd6922fd79ccfb6fc9bd961f99bfab7 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Tue, 24 Nov 2026 10:49:25 +0000 Subject: [PATCH] feat(svc-ai-lmstudio): fetch every lacking model at once as async jobs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The model preload fetched one model after the other, so a node with several models waited for the sum of all downloads. When async is enabled, every model the store lacks now starts as its own async get_url job per source slot: the declared url first, then each mirror, a mirror only after the whole source round ended and only for the models still missing. Each slot round gets a budget of max(floor, bytes / minimum rate) with async retries inside it. A jobs file records the running jobs, so a later run waits out or drops the downloads of a killed run, and a download that still runs or reports no state past its lifetime stops the play. Partial downloads in staging are removed before every store read, and the final check fails closed with what each source answered. Debug runs keep fetching one model at a time through get_url_retry, which now takes its own retries argument. ๐ŸŽฏ Fix: 92 % ๐Ÿ’ฅ Break: 4 % ๐Ÿ’ธ Tokens: 100 % โฑ๏ธ Velocity: 100 % ๐Ÿ›ก๏ธ Security: 100 % ๐Ÿ† Score: 88 ๐Ÿšฆ Gate: โœ… 90/5, tokens and velocity <= 100, security 100 % Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 --- plugins/action/get_url_retry.py | 21 +- roles/svc-ai-lmstudio/README.md | 2 +- roles/svc-ai-lmstudio/meta/services.yml | 2 + roles/svc-ai-lmstudio/tasks/utils/fetch.yml | 219 ++-- .../tasks/utils/fetch/attempt.yml | 67 ++ .../tasks/utils/fetch/collect.yml | 36 + .../tasks/utils/fetch/round.yml | 26 + .../tasks/utils/fetch/settle.yml | 45 + .../tasks/utils/fetch/start.yml | 37 + roles/svc-ai-lmstudio/vars/main.yml | 2 + .../roles/svc-ai-lmstudio/test_fetch.py | 938 ++++++++++++++---- tests/lint/ansible/modules/README.md | 2 +- .../test_no_legacy_get_url_module_usage.py | 165 ++- .../plugins/action/test_get_url_retry.py | 47 + 14 files changed, 1335 insertions(+), 274 deletions(-) create mode 100644 roles/svc-ai-lmstudio/tasks/utils/fetch/attempt.yml create mode 100644 roles/svc-ai-lmstudio/tasks/utils/fetch/collect.yml create mode 100644 roles/svc-ai-lmstudio/tasks/utils/fetch/round.yml create mode 100644 roles/svc-ai-lmstudio/tasks/utils/fetch/settle.yml create mode 100644 roles/svc-ai-lmstudio/tasks/utils/fetch/start.yml diff --git a/plugins/action/get_url_retry.py b/plugins/action/get_url_retry.py index 81fd62c7aa..e00d053f32 100755 --- a/plugins/action/get_url_retry.py +++ b/plugins/action/get_url_retry.py @@ -11,8 +11,18 @@ from ansible.plugins.action import ActionBase class ActionModule(ActionBase): + """get_url with retries on the controller. + + Args: + retries: own argument, never passed on to get_url: how often a failed + download is retried. Use it instead of the ``retries`` task keyword, + which also makes Ansible retry the whole task, every retry of this + plugin included. Defaults to the keyword, else DEFAULT_RETRIES. + """ + DEFAULT_RETRIES = 12 DEFAULT_DELAY = 5 + OWN_ARGS = frozenset({"retries"}) def run(self, tmp=None, task_vars=None): if task_vars is None: @@ -24,7 +34,10 @@ class ActionModule(ActionBase): if self._task.async_val: return self._execute_get_url(tmp=tmp, task_vars=task_vars) - retries = self._task_keyword_int("retries", self.DEFAULT_RETRIES) + if "retries" in self._task.args: + retries = self._as_int(self._task.args["retries"], self.DEFAULT_RETRIES) + else: + retries = self._task_keyword_int("retries", self.DEFAULT_RETRIES) delay = self._task_keyword_int("delay", self.DEFAULT_DELAY) attempts_total = max(1, retries + 1) @@ -44,7 +57,11 @@ class ActionModule(ActionBase): def _execute_get_url(self, tmp, task_vars): return self._execute_module( module_name="ansible.builtin.get_url", - module_args=dict(self._task.args), + module_args={ + key: value + for key, value in self._task.args.items() + if key not in self.OWN_ARGS + }, task_vars=task_vars, tmp=tmp, ) diff --git a/roles/svc-ai-lmstudio/README.md b/roles/svc-ai-lmstudio/README.md index 0948baba5b..b3f281d2b8 100644 --- a/roles/svc-ai-lmstudio/README.md +++ b/roles/svc-ai-lmstudio/README.md @@ -13,7 +13,7 @@ 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 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. +- **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. Models the store already holds at their `sha256` are left alone. The others download at once from their declared `url`, then from each of the optional `mirrors` in turn, every source only for the models the sources before it did not deliver. A source's downloads run as async jobs within a budget derived from their summed `bytes`, `preload_floor_seconds` and `preload_min_bytes_per_second`, and a failed download is retried up to `preload_retries` times `preload_retry_delay` seconds apart while that budget lasts. With `ASYNC_ENABLED` off, as in debug runs, the models download one after the other through `get_url_retry`, each retried up to `preload_retries` times `preload_retry_delay` seconds apart, every retry inside that model's own budget. Downloads an interrupted deploy left running are waited for, each up to the deadline its lifetime sets, before the next deploy touches the store, 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. diff --git a/roles/svc-ai-lmstudio/meta/services.yml b/roles/svc-ai-lmstudio/meta/services.yml index f5347e7c74..5dea326c2c 100644 --- a/roles/svc-ai-lmstudio/meta/services.yml +++ b/roles/svc-ai-lmstudio/meta/services.yml @@ -35,6 +35,8 @@ lmstudio: preload_models: "{{ AI_LOCAL_MODELS }}" preload_floor_seconds: 600 preload_min_bytes_per_second: 1000000 + preload_retries: 12 + preload_retry_delay: 5 lifecycle: beta # nocheck: playwright-service-flag, dynamic-flag diff --git a/roles/svc-ai-lmstudio/tasks/utils/fetch.yml b/roles/svc-ai-lmstudio/tasks/utils/fetch.yml index 059d516b67..50585402b4 100644 --- a/roles/svc-ai-lmstudio/tasks/utils/fetch.yml +++ b/roles/svc-ai-lmstudio/tasks/utils/fetch.yml @@ -1,13 +1,58 @@ --- # Param: lmstudio_fetch_store directory on the target that holds / 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 +# Param: lmstudio_fetch_node the host that owns the store: the fetch is delegated to it, its jobs are collected there and the failure messages name it +- name: "๐Ÿ›‘ Refuse declared models that share a store path but not a digest and size" + vars: + _repos: "{{ LMSTUDIO_PRELOAD_MODELS | map(attribute='repo') | list }}" + _files: "{{ LMSTUDIO_PRELOAD_MODELS | map(attribute='file') | list }}" + _paths: "{{ _repos | zip(_files) | map('join', '/') | unique | list }}" + _identities: >- + {{ _repos | zip(_files, LMSTUDIO_PRELOAD_MODELS | map(attribute='sha256'), + LMSTUDIO_PRELOAD_MODELS | map(attribute='bytes') | map('string')) + | map('join', '/') | unique | list }} + ansible.builtin.assert: + that: _identities | length == _paths | length + fail_msg: >- + AI_LOCAL_MODELS declares the same repo and file more than once with + different sha256 or bytes, so the model store on {{ lmstudio_fetch_node }} + could satisfy only one of them: {{ _identities | join(', ') }}. + quiet: true + +- name: "๐Ÿ›‘ Refuse a negative fetch retry count or delay on '{{ lmstudio_fetch_node }}'" + ansible.builtin.assert: + that: + - LMSTUDIO_PRELOAD_RETRIES | int >= 0 + - LMSTUDIO_PRELOAD_RETRY_DELAY | int >= 0 + fail_msg: >- + services.lmstudio.preload_retries ({{ LMSTUDIO_PRELOAD_RETRIES }}) and + preload_retry_delay ({{ LMSTUDIO_PRELOAD_RETRY_DELAY }}) of svc-ai-lmstudio + must not be negative. + quiet: true + +- name: "๐Ÿงพ Start the fetch on '{{ lmstudio_fetch_node }}' with nothing read yet" + vars: + _declared: >- + {%- set seen = namespace(paths=[], models=[]) -%} + {%- for model in LMSTUDIO_PRELOAD_MODELS + if (model.repo ~ '/' ~ model.file) not in seen.paths -%} + {%- set seen.paths = seen.paths + [model.repo ~ '/' ~ model.file] -%} + {%- set seen.models = seen.models + [model] -%} + {%- endfor -%} + {{ seen.models }} + ansible.builtin.set_fact: + lmstudio_fetch_declared: "{{ _declared }}" + lmstudio_fetch_jobs_file: "{{ lmstudio_fetch_staging }}.jobs.json" + lmstudio_fetch_pending: [] + lmstudio_fetch_settled: [] + lmstudio_fetch_said: [] + - 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: "{{ lmstudio_fetch_declared }}" loop_control: loop_var: model label: "{{ model.file }}" @@ -18,32 +63,49 @@ 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: "๐Ÿ”Ž Look for downloads a past fetch on '{{ lmstudio_fetch_node }}' left running" + ansible.builtin.slurp: + src: "{{ lmstudio_fetch_jobs_file }}" + register: lmstudio_fetch_leftovers + failed_when: >- + lmstudio_fetch_leftovers is failed + and 'not found' not in lmstudio_fetch_leftovers.msg -- 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 }}" +- name: "โณ Wait until downloads a past fetch left on '{{ lmstudio_fetch_node }}' end" + vars: + _leftovers: "{{ lmstudio_fetch_leftovers.content | b64decode | from_json }}" + _now: "{{ '%s' | strftime | int }}" + ansible.builtin.async_status: + jid: "{{ jid }}" + loop: "{{ (lmstudio_fetch_leftovers.content | b64decode | from_json).jobs if lmstudio_fetch_leftovers.content is defined else [] }}" 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 + loop_var: jid + register: lmstudio_fetch_leftover_jobs + until: lmstudio_fetch_leftover_jobs.finished or (_now | int) > (_leftovers.deadline | int) + retries: "{{ [((_leftovers.deadline | int) - (_now | int)) // 5 + 1, 0] | max }}" + delay: 5 changed_when: false - loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" - loop_control: - loop_var: model - label: "{{ model.file }}" + failed_when: false + ignore_errors: true + +- name: "โธ๏ธ Wait out unnoted downloads of a past fetch on '{{ lmstudio_fetch_node }}'" + ansible.builtin.wait_for: + timeout: >- + {{ [((lmstudio_fetch_leftovers.content | b64decode | from_json).deadline | int) + - ('%s' | strftime | int), 0] | max }} + when: >- + lmstudio_fetch_leftovers.content is defined + and (lmstudio_fetch_leftovers.content | b64decode | from_json).jobs | length == 0 + +- name: "๐Ÿงพ Clear the jobs file an earlier fetch on '{{ lmstudio_fetch_node }}' left" + ansible.builtin.file: + path: "{{ lmstudio_fetch_jobs_file }}" + state: absent + +- name: "๐Ÿ“ฅ Take stock of the model store on '{{ lmstudio_fetch_node }}'" + ansible.builtin.include_tasks: utils/fetch/settle.yml + vars: + lmstudio_fetch_models: "{{ lmstudio_fetch_declared }}" - name: "๐Ÿ—„๏ธ Measure the free space the model store on '{{ lmstudio_fetch_node }}' offers" ansible.builtin.command: "df -P -B1 {{ lmstudio_fetch_store | quote }}" @@ -53,13 +115,7 @@ - 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 }} + _pending: "{{ lmstudio_fetch_pending | map(attribute='model.bytes') | map('int') | sum }}" ansible.builtin.fail: msg: >- The model store {{ lmstudio_fetch_store }} on {{ lmstudio_fetch_node }} has @@ -69,71 +125,68 @@ 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" +- name: "๐Ÿ—บ๏ธ Plan the sources of each model missing on '{{ lmstudio_fetch_node }}'" 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 + _plan: >- + {%- set plan = namespace(jobs=[]) -%} + {%- for pending in lmstudio_fetch_pending -%} + {%- for url in [pending.model.url] + (pending.model.mirrors | default([])) -%} + {%- set plan.jobs = plan.jobs + [{'model': pending.model, 'url': url, 'slot': loop.index0}] -%} + {%- endfor -%} + {%- endfor -%} + {{ plan.jobs }} + ansible.builtin.set_fact: + lmstudio_fetch_plan: "{{ _plan }}" + lmstudio_fetch_rounds: >- + {{ _plan | map(attribute='slot') | unique | sort + | product(range((LMSTUDIO_PRELOAD_RETRIES | int) + 1 if ASYNC_ENABLED | bool else 1)) + | list }} -- 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" +- name: "โฌ‡๏ธ Fetch the missing models on '{{ lmstudio_fetch_node }}' round by round" + ansible.builtin.include_tasks: utils/fetch/round.yml vars: - _bytes: "{{ item.0.bytes }}" - _budget: *lmstudio_fetch_budget - timeout: "{{ lookup('timeout', _budget) | int }}" - loop: "{{ LMSTUDIO_PRELOAD_MODELS | subelements('mirrors', skip_missing=True) }}" + lmstudio_fetch_slot: "{{ lmstudio_fetch_round[0] }}" + lmstudio_fetch_attempt: "{{ lmstudio_fetch_round[1] }}" + loop: "{{ lmstudio_fetch_rounds }}" loop_control: - label: "{{ item.0.file }} from {{ item.1 }}" - register: lmstudio_fetch_mirror - changed_when: false - ignore_errors: true + loop_var: lmstudio_fetch_round -- name: "๐Ÿ” Read back what the model store on '{{ lmstudio_fetch_node }}' now holds" +- name: "๐Ÿ” Check nothing else rewrote the store on '{{ lmstudio_fetch_node }}'" ansible.builtin.stat: - path: "{{ lmstudio_fetch_store }}/{{ model.repo }}/{{ model.file }}" - checksum_algorithm: sha256 - register: lmstudio_seeded + path: "{{ lmstudio_fetch_store }}/{{ last.model.repo }}/{{ last.model.file }}" + get_checksum: false + get_mime: false + get_attributes: false + register: lmstudio_fetch_final changed_when: false - loop: "{{ LMSTUDIO_PRELOAD_MODELS }}" + loop: "{{ lmstudio_fetch_settled + lmstudio_fetch_pending }}" loop_control: - loop_var: model - label: "{{ model.file }}" + loop_var: last + label: "{{ last.model.file }}" + +- name: "๐Ÿ“ฅ Re-read the models something else rewrote on '{{ lmstudio_fetch_node }}'" + ansible.builtin.include_tasks: utils/fetch/settle.yml + vars: + lmstudio_fetch_models: >- + {%- set rewritten = namespace(models=[]) -%} + {%- for seen in lmstudio_fetch_final.results + if seen.stat.exists != seen.last.stat.exists + or (seen.stat.exists + and [seen.stat.inode, seen.stat.mtime, seen.stat.size] + != [seen.last.stat.inode, seen.last.stat.mtime, seen.last.stat.size]) -%} + {%- set rewritten.models = rewritten.models + [seen.last.model] -%} + {%- endfor -%} + {{ rewritten.models }} + when: lmstudio_fetch_models | length > 0 - 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) }} + _missing: "{{ lmstudio_fetch_pending | rejectattr('stat.exists') | map(attribute='model.file') | 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(' | ') }} + {{ lmstudio_fetch_said | join(' | ') }} when: _missing | length > 0 - name: "๐Ÿ›‘ Fail when a stored model does not match its declared digest and size" @@ -142,7 +195,7 @@ {{ 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: "{{ (lmstudio_fetch_settled + lmstudio_fetch_pending) | selectattr('stat.exists') | list }}" loop_control: label: "{{ item.model.file }}" when: >- diff --git a/roles/svc-ai-lmstudio/tasks/utils/fetch/attempt.yml b/roles/svc-ai-lmstudio/tasks/utils/fetch/attempt.yml new file mode 100644 index 0000000000..296194c20b --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/fetch/attempt.yml @@ -0,0 +1,67 @@ +--- +- name: "โธ๏ธ Wait before retrying source {{ lmstudio_fetch_slot }}" + ansible.builtin.wait_for: + timeout: "{{ LMSTUDIO_PRELOAD_RETRY_DELAY | int }}" + when: lmstudio_fetch_attempt | int > 0 + +- name: "๐Ÿ•’ Give the downloads of source {{ lmstudio_fetch_slot }} the rest of its budget" + ansible.builtin.set_fact: + lmstudio_fetch_lifetime: "{{ [(lmstudio_fetch_deadline | int) - ('%s' | strftime | int), 1] | max }}" + +- name: "โฌ‡๏ธ Fetch the models of source {{ lmstudio_fetch_slot }} one by one" + get_url_retry: + url: "{{ lmstudio_fetch_job.url }}" + dest: "{{ lmstudio_fetch_store }}/{{ lmstudio_fetch_job.model.repo }}/{{ lmstudio_fetch_job.model.file }}" + tmp_dest: "{{ lmstudio_fetch_staging }}" + checksum: "sha256:{{ lmstudio_fetch_job.model.sha256 }}" + mode: "0644" + retries: "{{ LMSTUDIO_PRELOAD_RETRIES | int }}" + vars: + _own_budget: >- + {{ [ LMSTUDIO_PRELOAD_FLOOR_SECONDS | int, + ((lmstudio_fetch_job.model.bytes | int) / (LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND | int)) + | round(0, 'ceil') | int ] | max }} + timeout: "{{ lookup('timeout', _own_budget) | int }}" + delay: "{{ LMSTUDIO_PRELOAD_RETRY_DELAY }}" + loop: "{{ lmstudio_fetch_due }}" + loop_control: + loop_var: lmstudio_fetch_job + label: "{{ lmstudio_fetch_job.model.file }} from {{ lmstudio_fetch_job.url }}" + register: lmstudio_fetch_sync + changed_when: false + ignore_errors: true + when: not (ASYNC_ENABLED | bool) + +- name: "โฌ‡๏ธ Run source {{ lmstudio_fetch_slot }} downloads as async jobs" + ansible.builtin.include_tasks: utils/fetch/start.yml + vars: + _window: + lifetime: "{{ lmstudio_fetch_lifetime | int }}" + deadline: "{{ ('%s' | strftime | int) + (lmstudio_fetch_lifetime | int) + 15 }}" + _collect: >- + {{ _window | combine({'jobs': lmstudio_fetch_async.results + | selectattr('ansible_job_id', 'defined') + | map(attribute='ansible_job_id') | list}) }} + when: ASYNC_ENABLED | bool + +- name: "๐Ÿ“ Keep what source {{ lmstudio_fetch_slot }} answered" + vars: + _answers: >- + {{ ((async_reap_results.results | selectattr('finished', 'defined') | list) + + (lmstudio_fetch_async.results | rejectattr('ansible_job_id', 'defined') | list)) + if ASYNC_ENABLED | bool else lmstudio_fetch_sync.results }} + ansible.builtin.set_fact: + lmstudio_fetch_said: >- + {%- set said = namespace(lines=lmstudio_fetch_said) -%} + {%- for answer in _answers -%} + {%- set job = answer.lmstudio_fetch_job if answer.lmstudio_fetch_job is defined + else (lmstudio_fetch_async.results | selectattr('ansible_job_id', 'defined') + | selectattr('ansible_job_id', 'eq', answer.ansible_job_id) | first).lmstudio_fetch_job -%} + {%- set said.lines = said.lines + [job.model.file ~ ' from ' ~ job.url ~ ': ' ~ answer.msg | default('no answer')] -%} + {%- endfor -%} + {{ said.lines }} + +- name: "๐Ÿ“ฅ Take stock of what source {{ lmstudio_fetch_slot }} delivered" + ansible.builtin.include_tasks: utils/fetch/settle.yml + vars: + lmstudio_fetch_models: "{{ lmstudio_fetch_due | map(attribute='model') | list }}" diff --git a/roles/svc-ai-lmstudio/tasks/utils/fetch/collect.yml b/roles/svc-ai-lmstudio/tasks/utils/fetch/collect.yml new file mode 100644 index 0000000000..1eec8e9ecf --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/fetch/collect.yml @@ -0,0 +1,36 @@ +--- +# Param: lmstudio_fetch_collect async downloads this fetch started, to wait for before staging is touched again: {lifetime: seconds each job may run, jobs: [job ids]} +- name: "โณ Collect the downloads on '{{ lmstudio_fetch_node }}'" + ansible.builtin.include_tasks: + file: utils/async/reap.yml + apply: + delegate_to: "{{ lmstudio_fetch_node }}" + ignore_errors: true + vars: + async_reap_jobs: >- + {%- set fired = namespace(jobs=[]) -%} + {%- for jid in lmstudio_fetch_collect.jobs -%} + {%- set fired.jobs = fired.jobs + [{'ansible_job_id': jid}] -%} + {%- endfor -%} + {{ fired.jobs }} + async_reap_label: "LM Studio model downloads on {{ lmstudio_fetch_node }}" + async_reap_tolerate: [] + ASYNC_TIME: "{{ (lmstudio_fetch_collect.lifetime | int) + 30 }}" + +- name: "๐Ÿ›‘ Stop when a download still runs on '{{ lmstudio_fetch_node }}'" + vars: + _running: >- + {{ ((async_reap_results.results | selectattr('finished', 'undefined') | list) + + (async_reap_results.results | selectattr('finished', 'defined') | rejectattr('finished') | list)) + | map(attribute='ansible_job_id', default='unknown') | list }} + ansible.builtin.fail: + msg: >- + The downloads {{ _running | join(', ') }} on {{ lmstudio_fetch_node }} still run + or reported no state past their {{ lmstudio_fetch_collect.lifetime }} s lifetime, + so another download would write the same model beside them. + when: _running | length > 0 + +- name: "๐Ÿงพ Clear the jobs file on '{{ lmstudio_fetch_node }}' after its downloads ended" + ansible.builtin.file: + path: "{{ lmstudio_fetch_jobs_file }}" + state: absent diff --git a/roles/svc-ai-lmstudio/tasks/utils/fetch/round.yml b/roles/svc-ai-lmstudio/tasks/utils/fetch/round.yml new file mode 100644 index 0000000000..40a89ad6f2 --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/fetch/round.yml @@ -0,0 +1,26 @@ +--- +# Param: lmstudio_fetch_slot index into each lacking model's sources: 0 is its url, every further one a mirror +# Param: lmstudio_fetch_attempt 0 for the first try of the slot, every further one an async retry within the slot's budget +- name: "๐Ÿ—“๏ธ Pick source {{ lmstudio_fetch_slot }} try {{ lmstudio_fetch_attempt }}" + vars: + _due: >- + {{ lmstudio_fetch_plan + | selectattr('slot', 'eq', lmstudio_fetch_slot | int) + | selectattr('model', 'in', lmstudio_fetch_pending | map(attribute='model') | list) + | list }} + _now: "{{ '%s' | strftime | int }}" + _deadline: >- + {{ ((_now | int) + (lookup('timeout', [ LMSTUDIO_PRELOAD_FLOOR_SECONDS | int, + ((_due | map(attribute='model.bytes') | map('int') | sum) + / (LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND | int)) | round(0, 'ceil') | int ] | max) | int)) + if lmstudio_fetch_attempt | int == 0 else lmstudio_fetch_deadline | int }} + ansible.builtin.set_fact: + lmstudio_fetch_deadline: "{{ _deadline | int }}" + lmstudio_fetch_due: >- + {{ _due if lmstudio_fetch_attempt | int == 0 + or (_deadline | int) - (_now | int) - (LMSTUDIO_PRELOAD_RETRY_DELAY | int) > 0 + else [] }} + +- name: "โฌ‡๏ธ Fetch source {{ lmstudio_fetch_slot }} try {{ lmstudio_fetch_attempt }}" + ansible.builtin.include_tasks: utils/fetch/attempt.yml + when: lmstudio_fetch_due | length > 0 diff --git a/roles/svc-ai-lmstudio/tasks/utils/fetch/settle.yml b/roles/svc-ai-lmstudio/tasks/utils/fetch/settle.yml new file mode 100644 index 0000000000..a5a1777bbe --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/fetch/settle.yml @@ -0,0 +1,45 @@ +--- +# Param: lmstudio_fetch_models declared models to read back from the store; each one replaces its entry in lmstudio_fetch_settled when held at its digest, else in lmstudio_fetch_pending +- name: "๐Ÿ” Find partial downloads left in the staging dir on '{{ lmstudio_fetch_node }}'" + ansible.builtin.find: + paths: "{{ lmstudio_fetch_staging }}" + file_type: any + hidden: true + register: lmstudio_staging_leftovers + +- name: "๐Ÿงน Remove partial downloads left in staging 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 }}' holds" + ansible.builtin.stat: + path: "{{ lmstudio_fetch_store }}/{{ model.repo }}/{{ model.file }}" + checksum_algorithm: sha256 + register: lmstudio_read + changed_when: false + loop: "{{ lmstudio_fetch_models }}" + loop_control: + loop_var: model + label: "{{ model.file }}" + +- name: "๐Ÿงฎ Sort what the model store on '{{ lmstudio_fetch_node }}' holds by digest" + vars: + _off_digest: >- + {%- set off = namespace(reads=[]) -%} + {%- for read in lmstudio_read.results + if not (read.stat.exists and read.stat.checksum == read.model.sha256) -%} + {%- set off.reads = off.reads + [read] -%} + {%- endfor -%} + {{ off.reads }} + ansible.builtin.set_fact: + lmstudio_fetch_pending: >- + {{ (lmstudio_fetch_pending | rejectattr('model', 'in', lmstudio_fetch_models) | list) + + _off_digest }} + lmstudio_fetch_settled: >- + {{ (lmstudio_fetch_settled | rejectattr('model', 'in', lmstudio_fetch_models) | list) + + (lmstudio_read.results | reject('in', _off_digest) | list) }} diff --git a/roles/svc-ai-lmstudio/tasks/utils/fetch/start.yml b/roles/svc-ai-lmstudio/tasks/utils/fetch/start.yml new file mode 100644 index 0000000000..e663516495 --- /dev/null +++ b/roles/svc-ai-lmstudio/tasks/utils/fetch/start.yml @@ -0,0 +1,37 @@ +--- +# Param: _window {lifetime, deadline} of the downloads this attempt starts, the deadline taken anew on every use +# Param: _collect _window plus the ids of the jobs the start task registered +- name: "๐Ÿงพ Note in the jobs file that source {{ lmstudio_fetch_slot }} starts" + ansible.builtin.copy: + content: "{{ _window | combine({'jobs': []}) | to_json }}" + dest: "{{ lmstudio_fetch_jobs_file }}" + mode: "0600" + +- name: "โฌ‡๏ธ Start the downloads of source {{ lmstudio_fetch_slot }}" + ansible.builtin.get_url: + url: "{{ lmstudio_fetch_job.url }}" + dest: "{{ lmstudio_fetch_store }}/{{ lmstudio_fetch_job.model.repo }}/{{ lmstudio_fetch_job.model.file }}" + tmp_dest: "{{ lmstudio_fetch_staging }}" + checksum: "sha256:{{ lmstudio_fetch_job.model.sha256 }}" + mode: "0644" + # rationale: async; collect.yml waits for every job of the round and settle.yml reads the store back before another attempt or the play goes on + async: "{{ lmstudio_fetch_lifetime }}" + poll: "{{ ASYNC_POLL }}" + loop: "{{ lmstudio_fetch_due }}" + loop_control: + loop_var: lmstudio_fetch_job + label: "{{ lmstudio_fetch_job.model.file }} from {{ lmstudio_fetch_job.url }}" + register: lmstudio_fetch_async + changed_when: false + ignore_errors: true + +- name: "๐Ÿงพ Note the downloads of source {{ lmstudio_fetch_slot }} in the jobs file" + ansible.builtin.copy: + content: "{{ _collect | to_json }}" + dest: "{{ lmstudio_fetch_jobs_file }}" + mode: "0600" + +- name: "โณ Wait for the downloads of source {{ lmstudio_fetch_slot }}" + ansible.builtin.include_tasks: utils/fetch/collect.yml + vars: + lmstudio_fetch_collect: "{{ _collect }}" diff --git a/roles/svc-ai-lmstudio/vars/main.yml b/roles/svc-ai-lmstudio/vars/main.yml index 2185830f69..77a95a596f 100644 --- a/roles/svc-ai-lmstudio/vars/main.yml +++ b/roles/svc-ai-lmstudio/vars/main.yml @@ -11,6 +11,8 @@ LMSTUDIO_PORT: "{{ lookup('config', application_id, 'services.lmstudio.ports.int LMSTUDIO_PRELOAD_MODELS: "{{ lookup('config', application_id, 'services.lmstudio.preload_models') }}" 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_RETRIES: "{{ lookup('config', application_id, 'services.lmstudio.preload_retries') }}" +LMSTUDIO_PRELOAD_RETRY_DELAY: "{{ lookup('config', application_id, 'services.lmstudio.preload_retry_delay') }}" 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 }}" diff --git a/tests/integration/roles/svc-ai-lmstudio/test_fetch.py b/tests/integration/roles/svc-ai-lmstudio/test_fetch.py index 1e4ddb272d..a2935ebafe 100644 --- a/tests/integration/roles/svc-ai-lmstudio/test_fetch.py +++ b/tests/integration/roles/svc-ai-lmstudio/test_fetch.py @@ -3,6 +3,7 @@ from __future__ import annotations import hashlib import json import os +import signal import socket import struct import subprocess @@ -11,51 +12,186 @@ import tempfile import threading import time import unittest +from dataclasses import dataclass from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path +from typing import Self 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" +OTHER = "Other-Q4_K_M.gguf" +GOOD = ("good", 0.0) +CORRUPT = ("corrupt", 0.0) +RATE = 1_000_000 +RETRIES = 12 +RETRY_DELAY = 5 PLAYBOOK = """ - hosts: localhost gather_facts: false tasks: - - ansible.builtin.include_tasks: "{{ fetch }}" + - ansible.builtin.include_role: + name: svc-ai-lmstudio + tasks_from: utils/fetch.yml """ -def _serve(resets: int, corrupt: bool) -> tuple[ThreadingHTTPServer, dict]: +@dataclass(frozen=True) +class Model: """ Args: - resets: how many transfers the source cuts off halfway with a TCP reset. - corrupt: whether every body the source sends differs from BLOB. + file: the model's file name in the store. + source: how its declared url answers, as a route of _serve. + mirrors: how each of its mirrors answers, in order. + held: what the store already holds at its path, None for nothing. + declared: the bytes whose sha256 and size the model declares. + """ + + file: str + source: tuple[str, float] + mirrors: tuple[tuple[str, float], ...] + held: bytes | None + declared: bytes + + +@dataclass(frozen=True) +class Run: + """ + Args: + rc: the play's exit code. + output: the play's output. + stored: per model file, what the store holds afterwards (b"" when absent). + requests: per URL path, how many requests it answered. + peak: per model file, the most transfers of it in flight at once. + overlap: the most transfers in flight at once, across every file. + elapsed: the play's wall time in seconds. + staged: what staging holds afterwards. + """ + + rc: int + output: str + stored: dict[str, bytes] + requests: dict[str, int] + peak: dict[str, int] + overlap: int + elapsed: float + staged: list[str] + + def text(self) -> str: + """ + Returns: + The output with every run of whitespace folded to one space. + """ + return " ".join(self.output.split()) + + def items(self, marker: str) -> list[str]: + """ + Args: + marker: text a task header must contain. + + Returns: + Every loop item line printed under a task whose header holds the marker. + """ + lines: list[str] = [] + inside = False + for line in self.output.splitlines(): + if line.startswith("TASK ["): + inside = marker in line + elif inside and "(item=" in line: + lines.append(line) + return lines + + +def _serve( + routes: dict[str, tuple[str, float]], held: list[Path] +) -> tuple[ThreadingHTTPServer, dict]: + """ + Args: + routes: per URL path, how the source answers and a number of seconds. + "good" sends BLOB, "corrupt" other bytes, "reset" cuts its first + transfer off halfway with a TCP reset, "half" ends its first + transfer cleanly after half the body, "trickle" sends a kilobyte + every half second and gives up after a quarter of the body, + "tamper" rewrites every held model with other bytes before it sends + BLOB. Each of them waits the seconds before it answers, except + "outage", which answers 503 until the seconds have passed since its + first request and BLOB after that. + held: the store paths "tamper" rewrites. Returns: - The running source and its request counter. + The running source and its counters. """ - state = {"requests": 0} + lock = threading.Lock() + stats: dict = { + "requests": {}, + "first": {}, + "flight": {}, + "peak": {}, + "active": 0, + "overlap": 0, + } class Source(BaseHTTPRequestHandler): def do_GET(self) -> None: - state["requests"] += 1 - body = bytes(reversed(BLOB)) if corrupt else BLOB + kind, seconds = routes[self.path] + file = self.path.rsplit("/", 1)[-1] + with lock: + attempt = stats["requests"].get(self.path, 0) + 1 + stats["requests"][self.path] = attempt + first = stats["first"].setdefault(self.path, time.monotonic()) + stats["flight"][file] = stats["flight"].get(file, 0) + 1 + stats["peak"][file] = max( + stats["peak"].get(file, 0), stats["flight"][file] + ) + stats["active"] += 1 + stats["overlap"] = max(stats["overlap"], stats["active"]) + try: + if kind == "outage": + if time.monotonic() - first < seconds: + self.send_response(503) + self.send_header("Content-Length", "0") + self.end_headers() + return + else: + time.sleep(seconds) + self._answer(kind, attempt) + except OSError: + self.close_connection = True + finally: + with lock: + stats["flight"][file] -= 1 + stats["active"] -= 1 + + def _answer(self, kind: str, attempt: int) -> None: + if kind == "tamper": + for path in held: + forged = path.with_name(path.name + ".forged") + forged.write_bytes(bytes(reversed(BLOB))) + forged.replace(path) + body = bytes(reversed(BLOB)) if kind == "corrupt" else BLOB self.send_response(200) self.send_header("Content-Length", str(len(body))) self.end_headers() - if state["requests"] <= resets: + if kind == "trickle": + for offset in range(0, len(body) // 4, 1024): + self.wfile.write(body[offset : offset + 1024]) + self.wfile.flush() + time.sleep(0.5) + self.close_connection = True + return + if kind in ("reset", "half") and attempt == 1: 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() + if kind == "reset": + 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) @@ -65,226 +201,662 @@ def _serve(resets: int, corrupt: bool) -> tuple[ThreadingHTTPServer, dict]: server = ThreadingHTTPServer(("127.0.0.1", 0), Source) threading.Thread(target=server.serve_forever, daemon=True).start() - return server, state + return server, stats + + +class Probe: + """ + Args: + models: the declared models and how their sources answer. + floor: the download budget floor in seconds. + rate: the slowest transfer rate a budget allows, in bytes per second. + retries: how often an async download is retried within its budget. + free: the free bytes df reports for the store, None for the real figure. + """ + + def __init__( + self, + models: list[Model], + floor: int, + rate: int, + retries: int, + free: int | None, + ) -> None: + self._scratch = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + root = Path(self._scratch.name) + self.models = models + self.store = root / "store" + self.staging = self.store / ".staging" + self.jobs_file = Path(f"{self.staging}.jobs.json") + self.async_dir = root / "ansible-async" + held = [self.store / REPO / m.file for m in models if m.held is not None] + routes: dict[str, tuple[str, float]] = {} + for model in models: + routes[f"/source/{model.file}"] = model.source + for index, mirror in enumerate(model.mirrors, start=1): + routes[f"/mirror{index}/{model.file}"] = mirror + self.server, self.stats = _serve(routes, held) + base = "http://{}:{}".format(*self.server.server_address[:2]) + (root / "tasks").symlink_to(PROJECT_ROOT / "tasks") + declared = [] + for model in models: + if model.held is not None: + path = self.store / REPO / model.file + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(model.held) + entry = { + "repo": REPO, + "file": model.file, + "url": f"{base}/source/{model.file}", + "sha256": hashlib.sha256(model.declared).hexdigest(), + "bytes": len(model.declared), + } + if model.mirrors: + entry["mirrors"] = [ + f"{base}/mirror{index}/{model.file}" + for index in range(1, len(model.mirrors) + 1) + ] + declared.append(entry) + self.variables = root / "vars.json" + self.settings = { + "ansible_python_interpreter": sys.executable, + "lmstudio_fetch_store": str(self.store), + "lmstudio_fetch_staging": str(self.staging), + "lmstudio_fetch_node": "localhost", + "LMSTUDIO_PRELOAD_FLOOR_SECONDS": floor, + "LMSTUDIO_PRELOAD_MIN_BYTES_PER_SECOND": rate, + "LMSTUDIO_PRELOAD_RETRIES": retries, + "LMSTUDIO_PRELOAD_RETRY_DELAY": RETRY_DELAY, + "LMSTUDIO_PRELOAD_MODELS": declared, + } + playbook = root / "playbook.yml" + playbook.write_text(PLAYBOOK, encoding="utf-8") + self.command = [ + sys.executable, + "-m", + "ansible.cli.playbook", + "-i", + "localhost,", + "-c", + "local", + str(playbook), + "-e", + f"@{self.variables}", + ] + self.env = { + **os.environ, + "ANSIBLE_CONFIG": str(PROJECT_ROOT / "ansible.cfg"), + "ANSIBLE_ROLES_PATH": str(PROJECT_ROOT / "roles"), + "ANSIBLE_HOME": str(root / "ansible-home"), + "ANSIBLE_LOCAL_TEMP": str(root / "ansible-local"), + "ANSIBLE_REMOTE_TEMP": str(root / "ansible-remote"), + "ANSIBLE_ASYNC_DIR": str(self.async_dir), + "ANSIBLE_NOCOLOR": "1", + "ANSIBLE_DISPLAY_SKIPPED_HOSTS": "1", + } + 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) + self.env["PATH"] = f"{bin_dir}{os.pathsep}{self.env['PATH']}" + + def __enter__(self) -> Self: + return self + + def __exit__(self, *exc: object) -> None: + self.server.shutdown() + self.server.server_close() + self._scratch.cleanup() + + def leave_partial(self) -> None: + """Leave the partial download an interrupted earlier fetch would.""" + self.staging.mkdir(parents=True, exist_ok=True) + (self.staging / "tmpinterrupted").write_bytes(BLOB[:1024]) + + def leave_dead_job(self) -> None: + """Leave the jobs file of a fetch whose async job died before it ended.""" + self.async_dir.mkdir(parents=True, exist_ok=True) + (self.async_dir / "1.dead").write_text( + json.dumps({"started": 1, "finished": 0, "ansible_job_id": "1.dead"}), + encoding="utf-8", + ) + self.staging.mkdir(parents=True, exist_ok=True) + self.jobs_file.write_text( + json.dumps( + {"lifetime": 5, "deadline": int(time.time()) - 1, "jobs": ["1.dead"]} + ), + encoding="utf-8", + ) + + def leave_unnoted_start(self, seconds: int) -> None: + """Leave the jobs file of a fetch killed after it noted the start of its + downloads but before it noted their job ids. + + Args: + seconds: how long from now the downloads it started may run. + """ + self.staging.mkdir(parents=True, exist_ok=True) + self.jobs_file.write_text( + json.dumps( + { + "lifetime": seconds, + "deadline": int(time.time()) + seconds, + "jobs": [], + } + ), + encoding="utf-8", + ) + + def deliver(self, file: str) -> None: + """Land a model in the store the way a download the play did not start would. + + Args: + file: the model file to land. + """ + path = self.store / REPO / file + path.parent.mkdir(parents=True, exist_ok=True) + landing = path.with_name(path.name + ".landing") + landing.write_bytes(BLOB) + landing.replace(path) + + def noted_jobs(self) -> list[str]: + """ + Returns: + The job ids the jobs file notes, empty while it is absent or notes none. + """ + try: + noted = self.jobs_file.read_text( # nocheck: cache-read a running play rewrites it + encoding="utf-8" + ) + except FileNotFoundError: + return [] + return json.loads(noted)["jobs"] + + def _configure(self, async_enabled: bool) -> None: + """ + Args: + async_enabled: whether the next play runs the downloads as async jobs. + """ + self.variables.write_text( + json.dumps( + { + **self.settings, + "ASYNC_ENABLED": async_enabled, + "ASYNC_POLL": 0 if async_enabled else 10, + } + ), + encoding="utf-8", + ) + + def start(self, async_enabled: bool) -> subprocess.Popen: + """ + Args: + async_enabled: whether the play runs the downloads as async jobs. + + Returns: + The play, running in its own session. + """ + self._configure(async_enabled) + return subprocess.Popen( + self.command, + cwd=str(PROJECT_ROOT), + env=self.env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + start_new_session=True, + ) + + def play(self, async_enabled: bool) -> Run: + """ + Args: + async_enabled: whether the play runs the downloads as async jobs. + + Returns: + What one play did, with the source counters of every play so far. + """ + self._configure(async_enabled) + began = time.monotonic() + result = subprocess.run( + self.command, + cwd=str(PROJECT_ROOT), + env=self.env, + capture_output=True, + text=True, + check=False, + timeout=900, + ) + elapsed = time.monotonic() - began + stored = {} + for model in self.models: + path = self.store / REPO / model.file + stored[model.file] = ( + path.read_bytes() # nocheck: cache-read the play wrote it + if path.exists() + else b"" + ) + return Run( + rc=result.returncode, + output=result.stdout + result.stderr, + stored=stored, + requests=dict(self.stats["requests"]), + peak=dict(self.stats["peak"]), + overlap=self.stats["overlap"], + elapsed=elapsed, + staged=( + sorted(entry.name for entry in self.staging.iterdir()) + if self.staging.exists() + else [] + ), + ) def _fetch( - resets: int, - corrupt: bool, + models: list[Model], floor: int, stale: bool, - mirrors: list[bool], free: int | None, - held: bytes | None, -) -> tuple[int, str, bytes, int, float, list[str]]: + async_enabled: bool, +) -> Run: """ Args: - resets: how many transfers the source cuts off halfway. - corrupt: whether the source only ever sends other bytes than BLOB. + models: the declared models and how their sources answer. 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. + async_enabled: whether the play runs the downloads as async jobs. 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. + What the play did. """ - 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() + with Probe(models, floor, RATE, RETRIES, free) as probe: + if stale: + probe.leave_partial() + return probe.play(async_enabled) -def _includes_fetch(tasks: list) -> bool: +def _include_of(tasks: list, target: str) -> dict | None: """ Args: tasks: a parsed task list. + target: the task file an include names. Returns: - Whether any task in it, nested blocks included, includes utils/fetch.yml. + The first task, nested blocks included, that includes the target, else None. """ 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 + named = include.get("file") if isinstance(include, dict) else include + if named == target: + return task + for key in ("block", "rescue"): + nested = _include_of(task.get(key), target) + if nested is not None: + return nested + return None 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 + def test_every_model_downloads_at_once_when_async(self) -> None: + run = _fetch( + [ + Model(FILE, ("good", 3.0), (), None, BLOB), + Model(OTHER, ("good", 3.0), (), None, BLOB), + ], + 60, + False, + None, + True, ) - self.assertEqual(rc, 0, output[-3000:]) - self.assertEqual(body, BLOB) - self.assertEqual(requests, 2) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored, {FILE: BLOB, OTHER: BLOB}) + self.assertEqual(run.overlap, 2) + + def test_debug_runs_download_one_model_at_a_time(self) -> None: + run = _fetch( + [ + Model(FILE, ("good", 3.0), (), None, BLOB), + Model(OTHER, ("good", 3.0), (), None, BLOB), + ], + 60, + False, + None, + False, + ) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored, {FILE: BLOB, OTHER: BLOB}) + self.assertEqual(run.overlap, 1) + + def test_debug_runs_give_each_model_its_own_budget(self) -> None: + with Probe( + [ + Model(FILE, ("trickle", 0.0), (), None, BLOB), + Model(OTHER, GOOD, (), None, BLOB), + ], + 1, + len(BLOB) // 8, + RETRIES, + None, + ) as probe: + run = probe.play(False) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("Timed out after 8 second(s)", run.text(), run.output[-3000:]) + self.assertEqual(run.stored, {FILE: b"", OTHER: BLOB}) + + def test_a_reset_transfer_costs_a_retry_not_the_deploy(self) -> None: + for async_enabled in (True, False): + with self.subTest(async_enabled=async_enabled): + run = _fetch( + [Model(FILE, ("reset", 0.0), (), None, BLOB)], + 60, + False, + None, + async_enabled, + ) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertEqual(run.requests[f"/source/{FILE}"], 2) + + def test_a_twenty_second_source_outage_is_retried_through(self) -> None: + for async_enabled in (True, False): + with self.subTest(async_enabled=async_enabled): + run = _fetch( + [Model(FILE, ("outage", 20.0), (), None, BLOB)], + 60, + False, + None, + async_enabled, + ) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertGreaterEqual(run.requests[f"/source/{FILE}"], 3) + + def test_async_retries_stop_when_the_source_budget_runs_out(self) -> None: + run = _fetch([Model(FILE, CORRUPT, (), None, BLOB)], 20, False, None, True) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertGreaterEqual(run.requests[f"/source/{FILE}"], 2) + self.assertLessEqual(run.requests[f"/source/{FILE}"], 4) def test_an_interrupted_fetch_leaves_no_partial_behind(self) -> None: - rc, output, body, _requests, _elapsed, staged = _fetch( - 0, False, 60, True, [], None, None + run = _fetch([Model(FILE, GOOD, (), None, BLOB)], 60, True, None, True) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertEqual(run.staged, []) + + def test_a_cut_transfer_leaves_no_partial_for_the_next_attempt(self) -> None: + run = _fetch( + [Model(FILE, ("half", 0.0), (), None, BLOB)], 60, False, None, True ) - self.assertEqual(rc, 0, output[-3000:]) - self.assertEqual(body, BLOB) - self.assertEqual(staged, []) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertEqual(run.requests[f"/source/{FILE}"], 2) + self.assertEqual(run.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) + run = _fetch([Model(FILE, CORRUPT, (), None, BLOB)], 4, False, None, True) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("did not match", run.text(), run.output[-3000:]) + self.assertEqual(run.stored[FILE], b"") + self.assertEqual(run.requests[f"/source/{FILE}"], 1) + self.assertLess(run.elapsed, 120) - 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 + def test_a_corrupt_source_hands_over_to_the_next_mirror(self) -> None: + run = _fetch( + [Model(FILE, CORRUPT, (CORRUPT, GOOD), None, BLOB)], 4, False, None, True ) - 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) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertEqual(run.requests[f"/mirror2/{FILE}"], 1) - 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 + def test_a_corrupt_mirror_still_reaches_the_final_check(self) -> None: + run = _fetch( + [Model(FILE, CORRUPT, (CORRUPT,), None, BLOB)], 4, False, None, True ) - self.assertNotEqual(rc, 0, output[-3000:]) - self.assertIn("What the sources answered", output, output[-3000:]) - self.assertEqual(body, b"") + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("What the sources answered:", run.text(), run.output[-3000:]) + answered = run.text().split("What the sources answered:", 1)[1] + self.assertIn(f"/source/{FILE}: The checksum", answered) + self.assertIn(f"/mirror1/{FILE}: The checksum", answered) + self.assertEqual(run.stored[FILE], b"") + + def test_mirrors_wait_for_the_source_round_and_never_share_a_file(self) -> None: + run = _fetch( + [ + Model(FILE, ("good", 3.0), (GOOD,), None, BLOB), + Model(OTHER, ("corrupt", 1.0), (("corrupt", 1.0), GOOD), None, BLOB), + ], + 8, + False, + None, + True, + ) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored, {FILE: BLOB, OTHER: BLOB}) + self.assertNotIn(f"/mirror1/{FILE}", run.requests) + self.assertEqual(run.requests[f"/mirror2/{OTHER}"], 1) + self.assertEqual(run.peak, {FILE: 1, OTHER: 1}) + + def test_a_trickling_download_is_cut_at_its_budget_and_collected(self) -> None: + run = _fetch( + [Model(FILE, ("trickle", 0.0), (), None, BLOB)], 5, False, None, True + ) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("Timeout exceeded", run.text(), run.output[-3000:]) + self.assertNotIn("still running past", run.text()) + self.assertEqual(run.stored[FILE], b"") + self.assertEqual(run.staged, []) + + def test_a_killed_run_leaves_no_download_behind_for_the_next_one(self) -> None: + for next_async in (True, False): + with self.subTest(next_async=next_async): + with Probe( + [Model(FILE, ("good", 8.0), (), None, BLOB)], + 60, + RATE, + RETRIES, + None, + ) as probe: + first = probe.start(True) + deadline = time.monotonic() + 120 + while not probe.noted_jobs() and time.monotonic() < deadline: + time.sleep(0.2) + os.killpg(first.pid, signal.SIGKILL) + first.wait() + self.assertTrue(probe.noted_jobs()) + run = probe.play(next_async) + self.assertFalse(probe.jobs_file.exists()) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertEqual(run.requests[f"/source/{FILE}"], 1) + self.assertEqual(run.staged, []) + + def test_a_job_that_died_unfinished_is_dropped_at_its_deadline(self) -> None: + with Probe( + [Model(FILE, GOOD, (), None, BLOB)], 60, RATE, RETRIES, None + ) as probe: + probe.leave_dead_job() + probe.leave_partial() + run = probe.play(True) + self.assertFalse(probe.jobs_file.exists()) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertEqual(run.staged, []) + self.assertLess(run.elapsed, 120) + + def test_downloads_started_but_never_noted_are_waited_out(self) -> None: + with Probe( + [Model(FILE, GOOD, (), None, BLOB)], 60, RATE, RETRIES, None + ) as probe: + probe.leave_unnoted_start(30) + probe.leave_partial() + landing = threading.Timer(20, probe.deliver, args=(FILE,)) + landing.start() + try: + run = probe.play(True) + finally: + landing.cancel() + self.assertFalse(probe.jobs_file.exists()) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertEqual(run.requests, {}) + self.assertEqual(run.staged, []) + + def test_debug_runs_retry_a_download_only_preload_retries_times(self) -> None: + with Probe( + [Model(FILE, ("outage", 600.0), (), None, BLOB)], 60, RATE, 1, None + ) as probe: + run = probe.play(False) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.requests[f"/source/{FILE}"], 2, run.output[-3000:]) + + def test_debug_runs_cap_every_retry_of_a_source_at_its_budget(self) -> None: + run = _fetch( + [Model(FILE, ("corrupt", 2.0), (), None, BLOB)], 6, False, None, False + ) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("Timed out after 6 second(s)", run.text(), run.output[-3000:]) + self.assertLessEqual(run.requests[f"/source/{FILE}"], 2) + + def test_a_negative_retry_count_is_refused(self) -> None: + with Probe([Model(FILE, GOOD, (), None, BLOB)], 60, RATE, -1, None) as probe: + run = probe.play(True) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("must not be negative", run.text(), run.output[-3000:]) + self.assertEqual(run.requests, {}) + + def test_a_model_rewritten_during_the_fetch_is_judged_again(self) -> None: + run = _fetch( + [ + Model(FILE, GOOD, (), BLOB, BLOB), + Model(OTHER, ("tamper", 0.0), (), None, BLOB), + ], + 60, + False, + None, + True, + ) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn(f"{FILE} in the model store", run.text(), run.output[-3000:]) + self.assertEqual(run.stored[OTHER], BLOB) + + def test_the_free_space_check_sums_every_pending_model(self) -> None: + run = _fetch( + [Model(FILE, GOOD, (), None, BLOB), Model(OTHER, GOOD, (), None, BLOB)], + 60, + False, + len(BLOB) * 3 // 2, + True, + ) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("GiB free but needs", run.text(), run.output[-3000:]) + self.assertEqual(run.requests, {}) 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 + run = _fetch( + [Model(FILE, GOOD, (), None, BLOB)], 60, False, len(BLOB) * 3 // 2, True ) - self.assertEqual(rc, 0, output[-3000:]) - self.assertEqual(body, BLOB) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + + def test_a_model_declared_twice_is_fetched_once(self) -> None: + run = _fetch( + [Model(FILE, GOOD, (), None, BLOB), Model(FILE, GOOD, (), None, BLOB)], + 60, + False, + len(BLOB) * 3 // 2, + True, + ) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored[FILE], BLOB) + self.assertEqual(run.requests[f"/source/{FILE}"], 1) + self.assertEqual(run.peak, {FILE: 1}) + + def test_a_path_declared_with_two_digests_is_refused(self) -> None: + run = _fetch( + [ + Model(FILE, GOOD, (), None, BLOB), + Model(FILE, GOOD, (), None, bytes(reversed(BLOB))), + ], + 60, + False, + None, + True, + ) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("declares the same repo and file", run.text(), run.output[-3000:]) + self.assertEqual(run.requests, {}) 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 + run = _fetch( + [Model(FILE, GOOD, (), held, BLOB)], 60, False, len(BLOB) // 2, True ) - self.assertNotEqual(rc, 0, output[-3000:]) - self.assertIn("GiB free but needs", output, output[-3000:]) - self.assertEqual(body, held) - self.assertEqual(requests, 0) + self.assertNotEqual(run.rc, 0, run.output[-3000:]) + self.assertIn("GiB free but needs", run.text(), run.output[-3000:]) + self.assertEqual(run.stored[FILE], held) + self.assertEqual(run.requests, {}) + + def test_a_held_model_is_read_once_and_never_fetched(self) -> None: + run = _fetch( + [Model(FILE, CORRUPT, (), BLOB, BLOB), Model(OTHER, GOOD, (), None, BLOB)], + 60, + False, + None, + True, + ) + self.assertEqual(run.rc, 0, run.output[-3000:]) + self.assertEqual(run.stored, {FILE: BLOB, OTHER: BLOB}) + self.assertEqual( + len([line for line in run.items("๐Ÿ” Read") if f"(item={FILE})" in line]), + 1, + run.output[-3000:], + ) + self.assertEqual( + [line for line in run.items("โฌ‡๏ธ") if f"(item={FILE}" in line], [] + ) + self.assertTrue( + [line for line in run.items("โฌ‡๏ธ") if f"(item={OTHER} from " in line] + ) + self.assertNotIn(f"/source/{FILE}", run.requests) 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=[]) + self.assertIsNotNone( + _include_of( + load_yaml_any(str(TASKS / caller), default_if_missing=[]), + "utils/fetch.yml", ) ) + def test_every_fetch_job_is_collected_on_the_node_that_runs_it(self) -> None: + for caller in ("00_core.yml", "utils/preload/node.yml"): + with self.subTest(caller=caller): + include = _include_of( + load_yaml_any(str(TASKS / caller), default_if_missing=[]), + "utils/fetch.yml", + ) + self.assertEqual( + include["ansible.builtin.include_tasks"]["apply"]["delegate_to"], + include["vars"]["lmstudio_fetch_node"], + ) + reap = _include_of( + load_yaml_any( + str(TASKS / "utils/fetch/collect.yml"), default_if_missing=[] + ), + "utils/async/reap.yml", + ) + self.assertEqual( + reap["ansible.builtin.include_tasks"]["apply"]["delegate_to"], + "{{ lmstudio_fetch_node }}", + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/lint/ansible/modules/README.md b/tests/lint/ansible/modules/README.md index 951908eaa5..accc014c40 100644 --- a/tests/lint/ansible/modules/README.md +++ b/tests/lint/ansible/modules/README.md @@ -6,7 +6,7 @@ Each test catches a class of silent or confusing failure that the runtime would Tests in this directory MUST only cover Ansible module / task usage rules. - `test_network_create_via_util.py` requires that role tasks creating Docker networks route through the shared utility, never inline `community.docker.docker_network` calls. -- `test_no_legacy_get_url_module_usage.py` forbids the unqualified `get_url:` module name; tasks MUST use `ansible.builtin.get_url`. +- `test_no_legacy_get_url_module_usage.py` forbids `get_url:` and `ansible.builtin.get_url:`; tasks MUST use `get_url_retry`, except a task that always runs async, which MUST call `ansible.builtin.get_url` because `get_url_retry` retries on the controller and cannot run async. Its own `async` key MUST be a positive integer or `{{ }}` for a name the lint lists as clamped to at least 1 (`lmstudio_fetch_lifetime`); any other templated value, such as `{{ ASYNC_TIME }}`, can resolve to `omit` or 0 and run the task synchronously without a retry, so its synchronous branch belongs in a separate `get_url_retry` task. - `test_no_legacy_uri_module_usage.py` forbids the unqualified `uri:` module name; tasks MUST use `ansible.builtin.uri`. - `test_no_literal_no_log.py` forbids literal `no_log: true` / `no_log: false`; every gate MUST flow through the `MASK_CREDENTIALS_IN_LOGS` variable. - `test_no_redundant_default_on_module_io.py` forbids `| default(...)` on a task's own `register:` output or input arguments inside its own conditionals, where the value is provably set. diff --git a/tests/lint/ansible/modules/test_no_legacy_get_url_module_usage.py b/tests/lint/ansible/modules/test_no_legacy_get_url_module_usage.py index 803bc5076c..251db02c32 100644 --- a/tests/lint/ansible/modules/test_no_legacy_get_url_module_usage.py +++ b/tests/lint/ansible/modules/test_no_legacy_get_url_module_usage.py @@ -1,9 +1,26 @@ +"""Downloads go through ``get_url_retry`` so a transient outage costs a retry, +not the deploy. + +The one exception is an ``ansible.builtin.get_url`` task that always runs +async: ``get_url_retry`` retries in a loop on the controller, which +async_wrapper cannot run, so its caller collects the job and retries it. Only +an ``async`` that can never turn the task synchronous counts: a positive +integer, or ``{{ }}`` for a name in ``_ALWAYS_ASYNC_NAMES``, each of +which its role clamps to at least 1. Any other templated value can resolve to +``omit`` (``ASYNC_TIME`` does when async is off) or to 0, so the task would +run synchronously without a retry, whatever ``retries``/``until`` it carries: +its synchronous branch belongs in a ``get_url_retry`` task, whose timeout +spans every retry. +""" + from __future__ import annotations import re import unittest from pathlib import Path +import yaml + from utils.cache.files import iter_project_files_with_content from . import PROJECT_ROOT @@ -11,6 +28,62 @@ from . import PROJECT_ROOT LEGACY_GET_URL_MODULE_PATTERN = re.compile( r"^\s*(ansible\.builtin\.get_url|get_url)\s*:\s*(?:#.*)?$" ) +_QUALIFIED = "ansible.builtin.get_url" +_ALWAYS_ASYNC_NAMES = frozenset({"lmstudio_fetch_lifetime"}) +_ALWAYS_ASYNC_RE = re.compile( + r"^(?:[1-9]\d*|\{\{\s*(?:[1-9]\d*|(?P[A-Za-z_]\w*))\s*\}\})$" +) + + +def _always_async(node: yaml.Node | None) -> list[int]: + """Find the get_url calls below ``node`` whose task always runs async. + + Args: + node: a composed YAML node of an Ansible file. + + Returns: + The 0-based line of the ``ansible.builtin.get_url`` key of every task + whose own ``async`` can never turn it synchronous. + """ + if isinstance(node, yaml.SequenceNode): + return [line for child in node.value for line in _always_async(child)] + if not isinstance(node, yaml.MappingNode): + return [] + keys = { + key.value: (key, value) + for key, value in node.value + if isinstance(key, yaml.ScalarNode) + } + found = [] + if _QUALIFIED in keys and "async" in keys: + gate = keys["async"][1] + match = ( + _ALWAYS_ASYNC_RE.match(gate.value.strip()) + if isinstance(gate, yaml.ScalarNode) + else None + ) + if match and match.group("name") in (None, *_ALWAYS_ASYNC_NAMES): + found.append(keys[_QUALIFIED][0].start_mark.line) + for _, value in node.value: + found += _always_async(value) + return found + + +def exempt_lines(content: str) -> set[int]: + """Tell which get_url lines of a file are allowed async downloads. + + Args: + content: the file's text. + + Returns: + The 0-based line of every allowed ``ansible.builtin.get_url`` key; empty + when the file is no valid YAML. + """ + try: + documents = list(yaml.compose_all(content, Loader=yaml.SafeLoader)) + except yaml.YAMLError: + return set() + return {line for document in documents for line in _always_async(document)} class TestNoLegacyGetUrlModuleUsage(unittest.TestCase): @@ -23,9 +96,16 @@ class TestNoLegacyGetUrlModuleUsage(unittest.TestCase): for path_str, content in iter_project_files_with_content(extensions=(".yml",)): yml_file = Path(path_str) rel = yml_file.relative_to(PROJECT_ROOT).as_posix() - for line_no, line in enumerate(content.splitlines(), start=1): - if LEGACY_GET_URL_MODULE_PATTERN.match(line): - findings.append((rel, line_no, line.strip())) + lines = content.splitlines() + exempt: set[int] | None = None + for line_no, line in enumerate(lines, start=1): + if not LEGACY_GET_URL_MODULE_PATTERN.match(line): + continue + if exempt is None: + exempt = exempt_lines(content) + if line_no - 1 in exempt: + continue + findings.append((rel, line_no, line.strip())) if findings: formatted = "\n".join( @@ -37,10 +117,87 @@ class TestNoLegacyGetUrlModuleUsage(unittest.TestCase): self.fail( "Found legacy get_url module calls in .yml files.\n\n" "Please migrate all of them to `get_url_retry:` so deploys are resilient against " - "transient network outages.\n\n" + "transient network outages. Only a task that always runs async may call " + "`ansible.builtin.get_url`, since get_url_retry cannot run async; put its " + "synchronous branch in a separate get_url_retry task.\n\n" f"{formatted}" ) +class TestAsyncGetUrlExemption(unittest.TestCase): + def _task(self, *keys: str) -> str: + """ + Args: + keys: task lines after the module block. + + Returns: + A two-task file whose first task calls ansible.builtin.get_url on line 1. + """ + return "\n".join( + [ + "- name: Download", + " ansible.builtin.get_url:", + " url: https://example.org/model.gguf", + " dest: /tmp/model.gguf", + *keys, + "- name: Next", + " ansible.builtin.debug:", + ] + ) + + def test_a_task_without_async_is_flagged(self): + self.assertNotIn(1, exempt_lines(self._task())) + + def test_an_unqualified_async_call_is_flagged(self): + text = self._task(' async: "{{ 60 }}"').replace( + "ansible.builtin.get_url:", "get_url:" + ) + self.assertNotIn(1, exempt_lines(text)) + + def test_an_async_task_that_can_run_sync_without_retries_is_flagged(self): + text = self._task(' async: "{{ 60 if ASYNC_ENABLED | bool else omit }}"') + self.assertNotIn(1, exempt_lines(text)) + + def test_retries_do_not_exempt_a_task_that_can_run_sync(self): + text = self._task( + ' async: "{{ 60 if ASYNC_ENABLED | bool else omit }}"', + " retries: 0", + " until: true", + ) + self.assertNotIn(1, exempt_lines(text)) + + def test_a_ternary_omit_gate_is_flagged(self): + text = self._task(' async: "{{ ASYNC_ENABLED | bool | ternary(60, omit) }}"') + self.assertNotIn(1, exempt_lines(text)) + + def test_a_templated_async_that_can_resolve_to_omit_is_flagged(self): + self.assertNotIn(1, exempt_lines(self._task(' async: "{{ ASYNC_TIME }}"'))) + + def test_a_zero_async_is_flagged(self): + self.assertNotIn(1, exempt_lines(self._task(" async: 0"))) + + def test_an_async_outside_the_task_keys_is_flagged(self): + self.assertNotIn(1, exempt_lines(self._task(" vars:", " async: 60"))) + + def test_an_always_async_task_is_exempt(self): + self.assertIn(1, exempt_lines(self._task(' async: "{{ 60 }}"'))) + + def test_the_fetch_round_async_form_is_exempt(self): + text = self._task(' async: "{{ lmstudio_fetch_lifetime }}"') + self.assertIn(1, exempt_lines(text)) + + def test_a_nested_list_item_does_not_split_the_task(self): + text = self._task( + " loop:", + " - first", + " - second", + ' async: "{{ lmstudio_fetch_lifetime }}"', + ) + self.assertIn(1, exempt_lines(text)) + + def test_a_nested_list_item_does_not_lend_its_async_to_the_task(self): + self.assertNotIn(1, exempt_lines(self._task(" loop:", " - async: 60"))) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/python/plugins/action/test_get_url_retry.py b/tests/unit/python/plugins/action/test_get_url_retry.py index ee091f0b53..38831b30cb 100644 --- a/tests/unit/python/plugins/action/test_get_url_retry.py +++ b/tests/unit/python/plugins/action/test_get_url_retry.py @@ -80,6 +80,53 @@ class TestGetUrlRetryActionPlugin(unittest.TestCase): self.assertEqual(sleep_mock.call_count, 2) sleep_mock.assert_called_with(1) + def test_run_takes_its_retry_count_from_its_own_argument(self): + task = _FakeTask( + args={"url": "http://example.invalid", "dest": "/tmp/file", "retries": "1"}, + ds={"delay": 1}, + delay=1, + ) + action = _make_action(task) + + with ( + patch( + "plugins.action.get_url_retry.ActionModule._execute_module", + side_effect=[ + {"failed": True, "msg": "attempt-1"}, + {"failed": True, "msg": "attempt-2"}, + {"failed": False, "dest": "/tmp/file"}, + ], + ) as module_mock, + patch("plugins.action.get_url_retry.time.sleep") as sleep_mock, + ): + result = action.run(task_vars={}) + + self.assertTrue(result.get("failed")) + self.assertEqual(result.get("attempts"), 2) + self.assertEqual(module_mock.call_count, 2) + sleep_mock.assert_called_once_with(1) + for call in module_mock.call_args_list: + self.assertEqual( + call.kwargs["module_args"], + {"url": "http://example.invalid", "dest": "/tmp/file"}, + ) + + def test_own_retry_argument_never_reaches_an_async_get_url(self): + task = _FakeTask( + args={"url": "http://example.invalid", "dest": "/tmp/file", "retries": 3}, + async_val=30, + ) + action = _make_action(task) + + with patch( + "plugins.action.get_url_retry.ActionModule._execute_module", + return_value={"failed": False, "dest": "/tmp/file"}, + ) as module_mock: + action.run(task_vars={}) + + self.assertEqual(module_mock.call_count, 1) + self.assertNotIn("retries", module_mock.call_args.kwargs["module_args"]) + def test_run_delegates_to_native_when_until_is_set(self): task = _FakeTask( args={"url": "http://example.invalid", "dest": "/tmp/file"},