-
Notifications
You must be signed in to change notification settings - Fork 355
refactor(hooks): make the unload on_agent_switch builtin pure #2706
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dgageot
wants to merge
3
commits into
docker:main
Choose a base branch
from
dgageot:board/50f4b45c23b1511a
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
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
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| package builtins | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "io" | ||
| "log/slog" | ||
| "net/http" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/docker/docker-agent/pkg/hooks" | ||
| "github.com/docker/docker-agent/pkg/model/provider/dmr" | ||
| ) | ||
|
|
||
| // Unload is the registered name of the on_agent_switch builtin that | ||
| // asks the previous agent's local inference engines (today: Docker | ||
| // Model Runner) to release the resources they hold. | ||
| // | ||
| // Wire it into a config with: | ||
| // | ||
| // hooks: | ||
| // on_agent_switch: | ||
| // - type: builtin | ||
| // command: unload | ||
| // | ||
| // The hook is pure: it depends only on the [hooks.Input.FromAgentModels] | ||
| // snapshot the runtime ships on every on_agent_switch dispatch, plus | ||
| // net/http. It carries no runtime-side coupling and silently skips any | ||
| // model whose endpoint isn't reachable as plain HTTP (e.g. cloud | ||
| // providers that don't expose [hooks.ModelEndpoint.BaseURL]). | ||
| // | ||
| // Provider dispatch and URL resolution are owned by | ||
| // [pkg/model/provider/dmr] (see [dmr.ProviderType] and [dmr.UnloadURL]), | ||
| // so this builtin stays a dumb dispatcher and DMR keeps full control | ||
| // of its conventions. | ||
| const Unload = "unload" | ||
|
|
||
| // unloadTimeout caps each per-model Unload call so a stalled engine | ||
| // cannot stall agent switching. | ||
| const unloadTimeout = 10 * time.Second | ||
|
|
||
| // unload iterates the [hooks.Input.FromAgentModels] snapshot the | ||
| // runtime captured at dispatch time and POSTs `{"model": "<id>"}` to | ||
| // the resolved unload endpoint of each DMR model. Errors are logged | ||
| // but never propagated — agent switching must never block on a slow | ||
| // or unreachable engine. | ||
| func unload(ctx context.Context, in *hooks.Input, _ []string) (*hooks.Output, error) { | ||
| if in == nil || in.FromAgent == "" || in.FromAgent == in.ToAgent { | ||
| return nil, nil | ||
| } | ||
| for _, m := range in.FromAgentModels { | ||
| if m.Provider != dmr.ProviderType { | ||
| continue | ||
| } | ||
| if err := unloadOne(ctx, m); err != nil { | ||
| slog.WarnContext(ctx, "unload: failed", | ||
| "agent", in.FromAgent, "model", m.Model, "error", err) | ||
| } | ||
| } | ||
| return nil, nil | ||
| } | ||
|
|
||
| // unloadOne resolves the unload URL for m and POSTs the model id to | ||
| // it, bounded by [unloadTimeout]. A model with no resolvable endpoint | ||
| // (no base_url and no unload_api) is a silent no-op so the hook stays | ||
| // harmless on test / in-process providers. | ||
| func unloadOne(parent context.Context, m hooks.ModelEndpoint) error { | ||
| endpoint, err := dmr.UnloadURL(m.BaseURL, m.UnloadAPI) | ||
| if err != nil || endpoint == "" { | ||
| return err | ||
| } | ||
| ctx, cancel := context.WithTimeout(parent, unloadTimeout) | ||
| defer cancel() | ||
|
|
||
| body, _ := json.Marshal(map[string]string{"model": m.Model}) | ||
| req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) | ||
| if err != nil { | ||
| return fmt.Errorf("building unload request: %w", err) | ||
| } | ||
| req.Header.Set("Content-Type", "application/json") | ||
|
|
||
| slog.DebugContext(ctx, "Unloading model", "url", endpoint, "model", m.Model) | ||
|
|
||
| // Unlike the http_post builtin, the unload target is the | ||
| // operator-configured DMR base URL — typically a loopback engine | ||
| // (Docker Desktop socket, 127.0.0.1:12434, …). The SSRF-safe | ||
| // dialer used by http_post would refuse those addresses by | ||
| // design, so we use the default client here. | ||
| resp, err := http.DefaultClient.Do(req) | ||
| if err != nil { | ||
| return fmt.Errorf("calling unload endpoint %s: %w", endpoint, err) | ||
| } | ||
| defer resp.Body.Close() | ||
|
|
||
| if resp.StatusCode < 200 || resp.StatusCode >= 300 { | ||
| respBody, _ := io.ReadAll(io.LimitReader(resp.Body, 4*1024)) | ||
| return fmt.Errorf("unload endpoint returned %d: %s", | ||
| resp.StatusCode, strings.TrimSpace(string(respBody))) | ||
| } | ||
| // Drain the success-path body so the underlying transport can reuse | ||
| // the connection (Go's http.Client only re-pools a connection whose | ||
| // body has been read to EOF and closed). | ||
| _, _ = io.Copy(io.Discard, resp.Body) | ||
| return nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Question:
http.DefaultClienthere vs. thehttpclient.NewSafeClientused by the newhttp_postbuiltin (#2705). The asymmetry is justified — DMR runs on loopback, which the SSRF dialer would block — but it's not obvious to a future reader. Worth a one-liner comment noting why the safe client isn't used here (operator-supplied URL, expected localhost target).