Repository navigation
feat(backends): LocalFileBinding implements verbs (PEFT/aLoRA path) + from_catalog() (Epic #929 Phase 2) - #1454
Conversation
AngeloDanducci
left a comment
There was a problem hiding this comment.
A few non-blocking notes on top of @jakelorocco's threads, which already cover the main design questions plus the adapter.py:373 guard and double-backticks nits. I've replied on the 373 thread with a related second site, and left two inline notes below: a contradictory adapter_type between identity and binding in the two new tests, and a prepare() idempotency edge. For context, the diff looks correct relative to #1141, the scope boundary (production hot path deferred to 4.1) is documented honestly, and the revision-forwarding fix has good regression coverage.
ajbozarth
left a comment
There was a problem hiding this comment.
Clean scoping, the 4.1 boundary is well-documented, and the revision-forwarding fix is a good catch with regression coverage. One blocking item on the span telemetry — two equally-fine ways to resolve it below — plus two small independent notes.
Blocker: adapter-function spans are emitted inline instead of through the tracing-plugin pattern
Spans here are opened/closed by direct start_*_span/finish_*_span calls in adapter_scope/_run_adapter_phase/prepare/release. Everywhere else in Mellea, spans are emitted by a *TracingPlugin in mellea/telemetry/tracing_plugins.py subscribing to lifecycle hooks, and core code never imports the span helpers. Inline emission is only used where code is synchronous and can't fire paired hooks (the session lifecycle spans); adapter_scope is async-capable (the e2e test awaits generate_from_context inside it), so it falls under the plugin pattern.
The underlying reason it had to be inline: the ADAPTER_FUNCTION_*_COMPLETE hooks are completion-only. This is the one hook family in HookType without a pre/start sibling — every other family (generation, component, tool, streaming, sampling, validation, session) has paired members. A span needs an opener to anchor on, so completion-only hooks can feed a metric but can't drive span open/close, which forced the inline workaround. (The metrics half of this PR is fine — it consumes those hooks correctly, the same as the other *MetricsPlugins.)
Two ways to resolve, both fine by me:
Option A — do it here, properly. Add pre/post (or start/end) hook points to the adapter-function contract and move span emission into an AdapterFunctionTracingPlugin. Metrics then read the post payload (which already carries duration/outcome) instead of a separate *_COMPLETE event. Two gaps to close while you're in there:
- The phase enum advertises
generateandparse, but nothing fires them (no span, no hook, no call site). Their real production sites are the model call in_generate_from_intrinsic(huggingface.py:575) andaction.parse(result)(huggingface.py:1776) — place the hook sites there so the contract doesn't ship dead phases. adapter_scope's phase and invocation hooks are currently unasserted (onlyprepare's is tested) — the new plugin + paired hooks should get coverage like the existing pairs have.
Option B — pull span telemetry out, follow up separately. Keep the LocalFileBinding lifecycle, from_catalog, verb extraction, and the revision fix (all self-standing), drop the inline spans, and open a follow-up issue to add adapter-function tracing through the plugin pattern. Reasonable if the hook-contract redesign is more than you want in this PR — and it lines up naturally with the 4.1 cutover, which is what would fire generate/parse anyway. Whether the metrics half stays or goes with it is your call.
Small note (file not in the diff, so can't inline it)
mellea/telemetry/metrics_plugins.py — the AdapterFunctionMetricsPlugin docstring still says "No production call site fires these hooks yet." This PR adds them; please update or remove it, depending on which option above you take.
|
@ajbozarth thanks — you're right, and the mechanism is more wrong than the diff makes it look. Summary The spans in this PR are produced the wrong way — inline in How we got here Until #1181 in June, calling the span helpers directly from library code was What it didn't do was write the new rule down. The bit I'd most like fixed: even knowing the plugin rule, I couldn't have In this PR
Follow-ups under #929
One correction before anyone builds on it: the Shout if you'd sequence any of this differently. |
|
Thanks for the comments so far. Will wait to see if the proposed approach is in the right direction on otel (@ajbozarth ) - i read this first, and more generally on the abstraction (@jakelorocco ) - thread - (since this is more than a in-pr review comment to be handled) before addressing the various other detailed comments which need changes & closing off conversation threads etc. |
commented
Jul 31, 2026
|
Moved to draft pending the outcome of some design discussions — see #1486. |
commented
Aug 6, 2026
|
Progress here stalled on the API-shape question in #1486 — I've posted a summary there of @ajbozarth — none of your review depends on that outcome, so I'll work through your points |
1a51900 to
a3e0d36
Compare
commented
Aug 11, 2026
|
Unblocked and ready for review. #1486 is closed as resolved, which was what this was What changed since you last looked
One thing I tried and backed out, flagged rather than buried: the Verification — all run on the rebased head: Four threads left open on purpose, all @jakelorocco's: the lock-duplication question Sequencing note: #1465 is the follow-up that routes generation through |
|
@ajbozarth — apologies, I answered your inline threads and never replied to this review Your blocker — I took Option B. Inline spans are gone: Your diagnosis of why it had to be inline was the useful part, and I've written it into Your small note — done. Two of your Option A points landed anyway, since they weren't really Option-specific:
While tracing the same "contract ships something dead" pattern I found a third instance and One correction to the review, for the record: the Verification on the current head ( Pushed as a separate commit on top rather than a force-push, so you can diff exactly |
…ve_adapter()
LocalFileBinding and IntrinsicAdapter share the same qualified-name key
space (f"{name}_{type}") in a backend's _added_adapters registry. If a
LocalFileBinding is registered for a capability, a later
resolve_adapter() call for the same name silently fails: add_adapter's
duplicate-key guard refuses the new IntrinsicAdapter, and _find_adapter
can't see the LocalFileBinding either (not an _AdapterCore), so the
caller got a bare "Adapter 'x' not found after registration" with no
hint of the cause.
Name the occupying type in both failure points: add_adapter's warning
log, and a new check in resolve_adapter's KeyError path. Doesn't change
the underlying collision -- nothing in the codebase mixes the two
registration paths for the same name today -- just makes the failure
self-diagnosing instead of opaque. Verified the new resolve_adapter test
against the pre-fix code (fails with the old bare message) before
confirming it passes on the fix.
Assisted-by: Claude Code
Signed-off-by: Nigel Jones <[email protected]>
adapter_scope() moved from an unconditional no-op (Phase 1) to calling adapter.weights.activate(), which raises NotImplementedError for the _ShimWeightsBinding every IntrinsicAdapter/LocalHFAdapter returned by resolve_adapter() still carries. Nothing in the codebase calls adapter_scope() with a resolved adapter today, so nothing breaks in practice, but this was an undocumented, unpinned behaviour change on a public method. Add a test asserting the new raise and a note in docs/dev/adapter_observability.md pointing at generative-computing#1465, the tracked cutover that has to reconcile shim/unprepared bindings with real activation before production wires generation through this path. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
…lure, guard the invocation-complete hook, and report resolved revision Three fixes from independently verifying two external reviews (codex, deepseek) of this PR: - event_loop_helper.py: closing `co` on a scheduling failure wasn't enough -- `_wrapped()`'s own coroutine object is created before `run_coroutine_threadsafe` is called, so a scheduling failure left it unstarted and unclosed, leaking a second "coroutine was never awaited" warning distinct from `co`'s. Reproduced empirically before fixing. - adapter_scope: `_fire_invocation_complete` ran unguarded in the outer `finally`, so a hook-dispatch failure there could turn a clean `with` block into a thrown error, or replace a genuine body exception with a telemetry one. Wrap it in try/except that logs and swallows -- the activate-phase hook already got this treatment, the invocation hook hadn't. - adapter_scope: revision was read from the raw `.revision` attribute, which is `None` for a lazily-resolved LocalFileBinding even though it downloaded and ran against a concrete catalogue pin. Use `resolved_revision()` when available so telemetry doesn't mislabel an effectively-pinned invocation as unpinned. Every regression guard was run against the pre-fix code and confirmed to fail there before confirming it passes on the fix. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
… release() as terminal Two fixes from independently verifying two external reviews of this PR: - LocalFileBinding.prepare(): add_adapter() sets .backend before load_peft_adapter() runs. If the load raised (e.g. a transient download/load failure), .backend was already non-None, so the idempotency guard (`if self.backend is not None: return`) made every retry a silent no-op -- the caller got no error and no working adapter, forever. Track the load's own success separately (`_loaded`) so a retry redoes only the failed step instead of re-registering (which would hit the backend's own duplicate-registration guard) or silently doing nothing. activate()/deactivate() now also check `_loaded`, since "registered but not loaded" is a newly-reachable, distinct state. - LocalFileBinding.release(): the docstring already said "terminal ... bind_backend() + prepare() will not revive it", but the code let release() clear .backend back to None, so a subsequent bind_backend() + prepare() on a fresh backend silently succeeded anyway. Add a `_released` flag; bind_backend() and prepare() now raise RuntimeError if called after release(), matching the contract the docstring already claimed. Every regression guard was run against the pre-fix code and confirmed to fail there before confirming it passes on the fix. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
… adapter_scope's non-atomicity prepare()/release() call load_peft_adapter()/unload_peft_adapter(), which mutate the same shared PEFT model state activate_peft_adapter/ deactivate_peft_adapter document "must be called while holding _generation_lock" for -- but neither prepare() nor release() took any lock. Wrap both in _adapter_activation_lock(), matching the other two verb pairs. Also attempted, then reverted, widening _adapter_activation_lock to span adapter_scope's whole activate/body/deactivate duration (to fix concurrent-scope interleaving, a real gap independently found in two external reviews) using a reentrant lock. That deadlocks the moment the body does real async generation: the actual generation work runs on mellea's shared event-loop thread, not the calling thread, so a same-thread RLock doesn't provide the needed exclusivity across threads -- confirmed by running test_local_file_e2e.py, which hung. Reverted that change; documented the non-atomicity as a known, tracked limitation on adapter_scope's docstring instead, with a test pinning today's actual (non-atomic) behavior so it isn't silently "fixed" back to interleaving or silently made worse. generative-computing#1465 (wiring real generation through this scope) has to solve the atomicity and the threading interaction together. Assisted-by: Claude Code Signed-off-by: Nigel Jones <[email protected]>
Assisted-by: Codex Signed-off-by: Nigel Jones <[email protected]>
Assisted-by: Codex Signed-off-by: Nigel Jones <[email protected]>
c6747dc to
94b2b7c
Compare
Assisted-by: Codex Signed-off-by: Nigel Jones <[email protected]>
Assisted-by: Codex Signed-off-by: Nigel Jones <[email protected]>
Assisted-by: Codex Signed-off-by: Nigel Jones <[email protected]>
commented
Aug 17, 2026
|
Hi @jakelorocco and @ajbozarth — the earlier approvals predate a small set of lifecycle hardening changes. These isolate phase-hook failures, clarify retry/error behaviour, reject invalid binding transitions, and serialise binding prepare/release to prevent a race. The changes are covered by focused regression tests and the full non-qualitative suite. Would you mind taking a quick fresh look at the updated lifecycle code before merge? |
left a comment
There was a problem hiding this comment.
Some feedback from Claude
LGTM. Verified locally: 276 adapter/event-loop/hf unit tests pass, ruff + mypy clean, and every behavioral claim in the description has a matching test (terminal release, retryable prepare, the non-atomic-scope limitation via a real two-thread test). Lock ordering (_lifecycle_lock → _generation_lock) is consistent with no reverse acquisition, and the except Exception narrowing in event_loop_helper is correctly reasoned.
One optional nit inline. Non-blocking.
Pull Request
Issue
Fixes #1141
Summary
LocalFileBinding— the weights binding for locally-downloaded LoRA/aLoRA adapters — was fourNotImplementedErrorstubs. This PR makes it real: workingprepare/activate/deactivate/releaseverbs, afrom_catalog()constructor, andAdapterMixin.adapter_scope()wired to actually activate/deactivate weights and fire metric hooks, instead of being a Phase 1 no-op.Two smaller, independent bugs came along for the ride because they blocked writing correct tests for the above:
IntrinsicAdapterwas silently resolvingrevision="main"instead of forwarding the catalogue's pinned SHA, andLocalFileBinding's own revision default did the same thing.Spans and the production generation cutover are explicitly not in this PR — see "Where this fits" below for exactly where they land instead.
Where this fits — Epic #929, Phase 2
This is #1141. Two things are deliberately not here, each with its own issue and acceptance criteria — don't file findings against their absence:
adapter_scope(). Three problems converge on this one issue:adapter_scope()now activates real weights, sowith backend.adapter_scope(backend.resolve_adapter(name)):goes from a no-op toNotImplementedErrorfor every adapterresolve_adapter()currently returns (they carry a Phase-1 shim binding). Deliberate, pinned bytest_adapter_scope_raises_for_a_shim_backed_adapter, not a silent regression — nothing today callsadapter_scope()outside tests.adapter_scope()is not atomic:_adapter_activation_lock()is held only inside eachactivate()/deactivate()verb call, not across thewithbody, so two concurrentadapter_scope()calls on one backend can interleave. Confirmed with a real two-thread test (test_adapter_scope_is_not_atomic_across_concurrent_calls) rather than left as a theoretical concern. Latent today — nothing calls it concurrently — but real._generation_lockreentrant and holding it across the whole scope deadlocks the instant the body does real async generation, because that work runs on mellea's shared event-loop thread, not the calling thread — same-thread reentrancy doesn't help across threads. Confirmed by runningtest_local_file_e2e.py, which hung. refactor(backends): route intrinsic generation through adapter_scope (Epic #929 Phase 2) #1465's own acceptance criteria already require solving the reentrancy and the atomicity together with the threading model, so that's where this belongs rather than a partial fix here.Also referenced, narrower in scope:
Adapterconstants inrag.py/guardian.pycarry unconfigured placeholder bindings; a stricteridentity/weightsadapter_typecross-check can't be enforced until those get real bindings.release()d binding'squalified_nameshould ever become re-claimable (today it doesn't;release()is terminal by contract).What changed
LocalFileBindingprepare/activate/deactivate/releaseimplemented;from_catalog(name)constructor;release()is enforced-terminal (bind_backend/prepareraise if called afterrelease());prepare()retries only the failed step after a load failure instead of silently no-op'ing forever;prepare()/release()now hold the backend's exclusivity lock around the PEFT load/unload calls, matchingactivate/deactivateAdapterMixinactivate_peft_adapter/deactivate_peft_adapter(extracted from_generate_with_adapter_lock's inline PEFT calls — behaviour-preserving);_adapter_activation_lock()for the exclusivity these verbs document as requiredAdapterMixin.adapter_scope()ADAPTER_FUNCTION_PHASE_COMPLETE,ADAPTER_FUNCTION_INVOCATION_COMPLETE) instead of a no-op; a hook-dispatch failure can never strand the adapter active or mask the real outcome (including the invocation-complete hook itself);revisionin telemetry is the resolved catalogue pin, not the raw unresolvedNoneIntrinsicAdapterobtain_io_yaml/obtain_lorainstead of implicitly resolving"main"mellea/helpers/event_loop_helper.py_run_async_in_thread's shared coroutine-close handling covers all 13 real call sites instead of 3, including its own internal wrapper coroutine (not just the caller's); narrowed toexcept Exception(notBaseException) to avoid a cross-thread race onKeyboardInterruptTelemetry: what changed and why
The original branch called
start_adapter_function_span(...)directly frommellea/backends/adapters/. Wrong mechanism — since #1181, span production belongs to plugins subscribing to hooks, and library code never opens a span itself. The mechanism was more wrong than the diff made it look:span = start_generate_span(...).docs/dev/adapter_observability.md, which still namedstart_backend_span/start_action_spanas the model to mirror. This PR's first draft followed that stale doc.ADAPTER_FUNCTION_INVOCATION_COMPLETE/ADAPTER_FUNCTION_PHASE_COMPLETEare the onlyHookTypefamily with no pre/start sibling for a plugin to open a span on.So: all inline span code is removed (
mellea/telemetry/tracing.pyis back to itsupstream/mainstate), metric hooks are the only telemetry here, the doc now states the hook/plugin rule and says plainly there's no span coverage of this lifecycle until #1466, and tests assert hooks/payloads rather than span names.Deviations from the literal issue spec
intrinsic.call/intrinsic.prepare; the convention that actually merged (refactor(backends): AdapterMixin verb rename/narrow + resolve_model_options + IntrinsicMetricsPlugin (Epic #929 Phase 2) #1140/refactor(backends)!: narrow AdapterMixin verbs, centralize option resolution, add AdapterFunctionMetricsPlugin skeleton #1422) isadapter_function/adapter_function.<phase>. Moot here since spans are gone, but feat(backends): LocalFileBinding implements verbs (PEFT/aLoRA path) + from_catalog() (Epic #929 Phase 2) #1141 and feat(telemetry): add complete adapter-function lifecycle observability #1466 are corrected so the next implementer doesn't copy the invented names.MELLEA_TRACES_CONTENT, not the issue'sMELLEA_TRACE_CONTENT.IntrinsicMetricsPlugin; the real class isAdapterFunctionMetricsPlugin.docs/docs/advanced/intrinsics.mdanddocs/examples/intrinsics/are untouched — documentingLocalFileBinding.from_catalog(...)as the construction pattern would document a path nothing in production can reach yet (deferred to refactor(backends): route intrinsic generation through adapter_scope (Epic #929 Phase 2) #1465/refactor(intrinsics): remove deprecation shims; rewrite intrinsics_and_adapters.md; write 3 tutorials (Epic #929 Phase 4) #1144, recorded on feat(backends): LocalFileBinding implements verbs (PEFT/aLoRA path) + from_catalog() (Epic #929 Phase 2) #1141).Testing
uv run pytest test/ -m "not qualitative"— 3931 passed, 21 skipped (hardware-gated), 0 failures.ruff format/ruff check/mypyclean.test/backends/test_adapters/test_local_file_e2e.py(GPU-gated) passes against a real model, including through the lock changes in this PR.Pre-existing failures unrelated to this diff:
test/package/test_dependency_isolation.py'stest_hooks/test_telemetry/test_telemetry_plugins_registerreproduce identically on a cleanupstream/maincheckout.Testing
Attribution
Adding a new component, requirement, sampling strategy, or tool?
If your PR adds or modifies one of the types below, check the matching box. A checklist of type-specific review items will be posted as a comment.
NOTE: Please ensure you have an issue that has been acknowledged by a core contributor and routed you to open a pull request against this repository. Otherwise, please open an issue before continuing with this pull request.