Repository navigation
Conversation
The module was 43,872 lines: ~300 helpers and one LlamaCppBackend class with 525 methods. It is now core/inference/llama_cpp/, 22 helper modules by topic, 21 mixin modules following the class's section banners, backend.py composing the class, and an __init__ that keeps the module's surface. Every statement moved verbatim, by a script that assigned statements by line range, derived imports from the compiler's symbol table, refused import cycles and checked that every old line landed exactly once. Four edits to moved text: the logger keeps its old name as a literal, two parents[4] lookups become parents[5], and the _vulkan_probe.py sibling is resolved from the package's parent. __init__ re-exports every definition, repeats the old import block, and is a ModuleType subclass whose __setattr__ rebinds the same object in every submodule alias, so the 163 names the suite patches on the module still reach the code that reads them. The two globals rebound with `global` are read live from their owner. LlamaCppBackend is bound into the 15 submodules whose static methods name it. Tests that read the file by path or getsource read the package through tests/_shared/llama_cpp_source.py; refactor_guard accepts a package and verifies against its unchanged baseline; a new layout test pins the facade, propagation, live globals, import graph, every production import (routes included) and the file-depth lookups. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This was referenced Oct 27, 2026
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Studio: split
core/inference/llama_cpp.pyinto a packagestudio/backend/core/inference/llama_cpp.pywas 43,872 lines and 2.3 MB: ~300 module-levelhelpers followed by one
LlamaCppBackendclass with 525 methods (load_modelalone is 9,500lines). This moves it, statement by statement, into
core/inference/llama_cpp/: 22 helpermodules by topic, 21 mixin modules that follow the class's own section banners,
backend.pycomposing
LlamaCppBackendfrom the mixins, and an__init__that keeps the old module'ssurface.
What moved where
compaction,core_types,server_log,binary_runtime,answer_artifacts,tool_loop_text,gguf_cache,swa_cache,hf_offline,reasoning,drafters,load_markers,memory_policy,launch_flags,placement_args,draft_args,batch_args,moe_cache,spec_args,timings,launch_support,log.# ── GPU allocation ──and friends), with the6,500-line GPU section split in three and the 16,000-line lifecycle section in seven:
backend_properties,backend_binary,backend_capabilities,backend_gpu_devices,backend_gpu_memory,backend_gpu_fit,backend_kv_cache,backend_download,backend_process_io,backend_diffusion,backend_preflight,backend_start_failures,backend_launch_retries,backend_load,backend_shutdown,backend_spill,backend_slots,backend_health,backend_generation,backend_tool_loop,backend_tokens.backend.pyholds the docstring, the two locks and__init__.backend_load.pyat 10,600 lines becauseload_modelis one method.How the move was made
Mechanically. A script read the old file's AST, assigned every top-level and class-body
statement to a module by line range (comments and blank lines travel with the statement that
follows them), computed each module's imports from the compiler's own symbol table
(
symtable), refused on any import cycle, and asserted that every source line of the old filelanded in exactly one module. Only four edits were made to the moved text, each asserted to
match once:
logger = get_logger(__name__)keeps the literal name"core.inference.llama_cpp", so logrecords and the tests that patch
llama_cpp.loggersee one logger;Path(__file__).resolve().parents[4]becomeparents[5]: the package is one directorydeeper (
_find_llama_server_binary,_kill_orphaned_servers);Path(__file__).with_name("_vulkan_probe.py")resolves the sibling probe from the package'sparent directory.
The committed files are that output passed through
scripts/run_ruff_format.py, which onlywrapped a few long import lines in the generated headers; a diff of the regenerated package
against the committed one touches no moved code.
What the facade keeps true
The old module was also a seam: 33 production modules import 153 distinct names from it
(
routes/inference.pyalone imports from it at module level), and the test suite patches 163distinct names on the module object, by attribute and by string.
__init__therefore:so
from core.inference.llama_cpp import Xandllama_cpp.subprocessare unchanged;ModuleTypesubclass whose__setattr__rebinds the same object in every submodulethat imported it.
monkeypatch.setattr(llama_cpp, "cached_gguf_for_load", fake)reaches thethree modules that call it, and the undo restores them; a name two modules bind to different
objects is left alone;
global(_SWA_CACHE,_CHAT_LOADS_IN_FLIGHT) live from their owning module instead of copying them, and writesthem back there;
LlamaCppBackendinto the 15 submodules whose static methods callLlamaCppBackend.<helper>by name, after the class exists, as the one module's global usedto resolve.
What changes for callers:
inspect.getsource(LlamaCppBackend)now returns the composingclass body, and
LlamaCppBackend.__dict__["method"]no longer finds mixin methods(
inspect.getattr_staticdoes). Both only affected tests, updated below.Tests
llama_cpp.pyoff disk or throughinspect.getsource, and three frontendparity tests read it with
readFileSync. They now read the package through one helper,tests/_shared/llama_cpp_source.py(package_source(),package_tree(),class_source(),module_source()), andstudio/frontend/tests/helpers/backend-llama-cpp-source.ts. Theconcatenation leaves
__init__out so a scan that looks a constant up by name finds itsdefinition, not the re-export list. Checks that compared positions across the file were
verified to compare positions inside one module (
load_modelfor most of them).tests/tools/refactor_guard.pyaccepts a package directory forcore.inference.llama_cpp;its recorded baseline was NOT regenerated, and
verifypasses against it: no symboldropped, every string patch target in the suite still resolves.
studio/backend/tests/test_llama_cpp_package_layout.py(19 tests) pins the package'sown contract: every definition exported once and identical to the owner's; the recorded
refactor-guard inventory is a subset of what the package defines; patch propagation and undo;
live globals;
globaltargets owned and never copied; submodules import siblings relativelyand never the package; the class is bound wherever named and no two mixins define one
attribute; every
from core.inference.llama_cpp import ...in production code (lazy ones andevery
routes/*.pyincluded) names an attribute the package has; theparents[5]and_vulkan_probe.pylookups resolve.test_orchestrator_unload_cancel.pytreats the package as one spawner unit, as it treatedthe one file: the diffusion runner is adopted in
backend_diffusionand the shutdown latchis consulted in
backend_load.test_gpu_memory_nvml_fallback.pypatches__file__on the module that owns the finder,one directory deeper.
Results
Measured on an M2 Pro Mac (CPU torch, no llama-server runs), the whole
studio/backendsuite as the backend CI job runs it (same
--ignorelist,-n 5), on a pristine worktree atthe base commit and on this branch:
studio/backend/teststests/studioThe failure sets are the same 44 names for
tests/studio. For the backend suite, everyfailure present on one side only passes when rerun on its own on both trees, and the set
shifts between two runs of the same tree: order- and timing-dependent tests
(
test_llama_cpp_placement,test_slot_reduction_context_refit,test_decision_serving,test_conversation_archive), not the split. The 391 shared failures are Mac-only:/proc,nvidia-smi,readelf, non-UTF-8 paths on APFS, and the ltx2 pipeline import againsttransformers 5.5.
Also checked:
python tests/tools/refactor_guard.py verifypasses against the recorded baseline.studio/backend/tests/test_llama_cpp_package_layout.py: 19 passed.routes/*.pymodules import; the FastAPI route table and the OpenAPI documentdigest are identical between the two trees;
unsloth studio --api-onlyboots to a healthy/api/healthserving 528 paths.import core.inference.llama_cpp: 0.13 s before, 0.14 s after.npm run typecheckpasses, biome reports nothing new.scripts/run_ruff_format.py(ruff 0.6.9) andruff checkwith the repo's rules are clean.Not covered
moved code is byte-identical and the import graph is verified, so the risk is in name
resolution, which the suite exercises on CPU.
codespellreportsunparseableandCANNin the moved text; both are pre-existing.🤖 Generated with Claude Code