Context-aware LoRA adapter routing for VS Code
LoRA-JIT is organised as four cooperating layers:
MockRuntime for tests and CI,
PyTorchPeftRuntime for real GPU inference.The core design principle is separation of concerns: telemetry, routing, paging, runtime activation, and benchmarking are isolated so each can evolve or be replaced independently.
| Component | Path | Responsibility |
|---|---|---|
| Daemon | backend/daemon/app.py |
FastAPI app — all HTTP endpoints |
| Contracts | backend/contracts/schemas.py |
Pydantic schemas shared across all layers |
| JitRouter | backend/routing/jit_router.py |
Closed-loop predict → page → activate orchestrator |
| Predictors | backend/routing/ |
structural, text, embedding, learned baselines |
| RuntimeBackend | backend/runtime/interface.py |
Abstract activate_adapter() + generate() contract |
| MockRuntime | backend/runtime/mock_runtime.py |
Deterministic stub for tests and CI |
| PyTorchPeftRuntime | backend/runtime/pytorch_peft.py |
Real PEFT hot-swap on GPU |
| PagingSimulator | backend/paging/simulator.py |
LRU hot-set tracking and cache statistics |
| BenchmarkRunner | backend/benchmark/runner.py |
Trace replay and predictor scoring |
| TraceCompiler | backend/benchmark/trace_compiler.py |
State reconstruction from NDJSON event logs |
| AutoLabeler | backend/labeling/auto_labeler.py |
Ontology-constrained row labeling |
| LlmLabelProvider | backend/labeling/llm_provider.py |
Optional LLM-backed offline labeling |
| TelemetryBuffer | backend/telemetry/buffer.py |
Rolling in-memory event buffer |
| SequenceTracker | backend/telemetry/sequence_tracker.py |
Per-file gap detection and resync |
| VS Code Extension | vscode-extension/src/extension.ts |
Telemetry producer + JIT visualisation |
| Method | Path | Schema in → out |
|---|---|---|
GET |
/health |
→ HealthResponse |
POST |
/jit/route |
TelemetryStreamEvent → JitRoutingDecision |
POST |
/jit/complete |
CompletionRequest → CompletionResponse |
POST |
/jit/preload |
PreloadRequest → PreloadResponse |
POST |
/telemetry/stream |
TelemetryBatchRequest → TelemetryBatchResponse |
GET |
/telemetry/recent |
→ list[TelemetryStreamEvent] |
GET |
/trace/sessions |
→ list[str] |
GET |
/trace/session/{id} |
→ {path: str} |
POST |
/benchmark/run |
BenchmarkRequest → BenchmarkResult |
POST |
/benchmark/compare |
BenchmarkComparisonRequest → BenchmarkComparisonResult |
VS Code extension
-> debounced TelemetryBatchRequest
-> POST /telemetry/stream
-> TelemetryBuffer (rolling 20 000-event cap)
-> NDJSON trace log (append-only, per session)
-> SequenceTracker (gap detection)
-> if gap: resync_files field in response triggers full-text heartbeat
VS Code extension (cursor / text_change event)
-> POST /jit/route (TelemetryStreamEvent)
-> JitRouter.route()
-> predictor.predict() [structural | text | embedding | learned]
-> PagingSimulator.touch(adapter_id) warm_hit or cold_miss
-> RuntimeBackend.activate_adapter(adapter_id)
-> return JitRoutingDecision
-> extension updates status bar + output channel
VS Code extension (280 ms debounce after typing stops)
-> POST /jit/complete (CompletionRequest)
-> daemon: check active_adapter_id is set
-> RuntimeBackend.generate(prompt, max_tokens)
MockRuntime: 45 ms sleep, returns stub text
PyTorchPeftRuntime: torch.no_grad() + tokenizer + model.generate()
-> return CompletionResponse
-> extension logs completion text + latency to output channel
NDJSON trace
-> TraceCompiler.compile() reconstruct file state, emit benchmark rows
-> AutoLabeler.annotate() add expected_label via ontology-constrained rules
-> BenchmarkRunner.run() replay rows, score predictions
-> BenchmarkResult top1_accuracy, cache_miss_rate, avg_prediction_ms
PagingSimulator models adapter VRAM residency with LRU semantics over both count and
optional approximate memory budget:
touch(adapter_id) → PagingTouchResult with paging_status, evicted_adapters,
warm_adapters, and total_hot_mbLORA_JIT_MAX_HOT_ADAPTERS (default: 3)LORA_JIT_MAX_HOT_MB (evicts LRU until under budget)LORA_JIT_PRELOAD_ADAPTERS — the daemon calls touch() for each
listed adapter during startup so the first real route events hit the warm pathPOST /jit/preload for extension-driven warm-up_active_adapter from activate_adapter() callsgenerate() sleeps 45 ms and returns a fixed stub stringActivated by LORA_JIT_RUNTIME_BACKEND=pytorch in .env.
Boot sequence:
runtime_config_from_env() reads all LORA_JIT_* variablescreate_runtime_backend() instantiates PyTorchPeftRuntimeLORA_JIT_EAGER_LOAD=true, base model loaded immediately; otherwise lazyLORA_JIT_PRELOAD_ADAPTERS is set, those adapters are preload_adapter()-ed at bootactivate_adapter(id) hot-swaps the PEFT delta weights via PeftModel.set_adapter()generate(prompt, max_tokens) runs model.generate() under torch.no_grad()Strict mode:
LORA_JIT_STRICT_RUNTIME=true disables silent fallback completionsRuntimeGenerationError and are surfaced by daemon as HTTP 500Graceful fallback: if any step in PyTorchPeftRuntime initialisation fails (missing model,
missing adapter, CUDA not available), create_runtime_backend() catches the exception, logs
a warning, and silently returns MockRuntime.
adapters/
sql_postgres/
adapter_config.json PEFT adapter config (r, lora_alpha, target_modules …)
adapter_model.safetensors LoRA delta weights
tokenizer.json tokenizer vocab
tokenizer_config.json tokenizer settings
chat_template.jinja optional chat template
sequence_idsymbol_path when document symbols are availabletraces/All benchmark labels are validated against the fixed adapter ontology in
docs/ADAPTER_ONTOLOGY.md. This prevents hallucinated adapter IDs from corrupting benchmarks.
Label schema:
{
"primary_adapter": "sql_postgres",
"acceptable_alternatives": ["data_engineering_general"],
"confidence": 0.92,
"reasoning": "File contains PostgreSQL DDL and parameterised queries"
}
Scoring:
primary_adapter → 1.0acceptable_alternative → 0.5LlmLabelProvider calls any OpenAI-compatible endpoint for richer reasoning.
Fallback to heuristic labeling on network error (configurable).
onDidChangeCursorPosition -> debounce 150 ms -> POST /jit/route
onDidChangeTextDocument -> debounce 280 ms -> POST /jit/complete
-> POST /telemetry/stream
On each /jit/route response:
JIT: <adapter_id> (warm|cold)[ROUTER], [PAGING], [INFER], [TIMING] linesOn each /jit/complete response:
Errors are logged to the output channel and never surface as modal popups.
409 from /jit/complete (no active adapter yet) is silently ignored.
| Predictor | Strategy | Trainable |
|---|---|---|
structural |
Heuristic token matching on file path, language ID, symbol path | No |
text |
Lexical overlap on file path, language, symbols, query/prompt metadata | No |
embedding |
Deterministic pseudo-embedding cosine similarity | No |
learned |
Multinomial Naive Bayes over tokenised event context | Yes — JSON artifact |
All predictors implement the same predict(event: TelemetryEvent) -> RoutingDecision interface
so they are interchangeable in both the benchmark runner and the live daemon.
PyTorchPeftRuntime)PagingSimulator, not measured from actual GPU memoryMockRuntime is the default backend; PyTorchPeftRuntime is opt-inThe boundary is deliberate: the systems design is fully testable without ML dependencies, and the ML path can be switched on without changing any contracts.
LoRA-JIT is designed to answer two measurable questions:
The architecture makes both questions independently measurable and improvable.