Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

## Unreleased

- **Prompt artifact provisioning** — Snapshot catalog file lists and the configured download origin, validate every manifest before sharing a download, and remove read-only staging trees after another cache instance wins publication.

## Release candidate v0.9.2 — Gemma QAT caching, adaptive MTP and Nemotron Lightning (not shipped; 2026-09-10)

Source changes since `v0.9.1`. Provider changes require a new signed bundle.
Expand Down
24 changes: 14 additions & 10 deletions coordinator/promptcontract/artifact_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,16 @@ func NewArtifactCache(config ArtifactCacheConfig) (*ArtifactCache, error) {
if config.BaseURL.User != nil || config.BaseURL.RawQuery != "" || config.BaseURL.Fragment != "" {
return nil, ErrUnsafeArtifactPath
}
// Retain the validated origin independently of caller-owned URL storage.
baseURL := *config.BaseURL
client := config.HTTPClient
if client == nil {
client = &http.Client{}
}
clientCopy := *client
originalRedirectPolicy := client.CheckRedirect
clientCopy.CheckRedirect = func(request *http.Request, via []*http.Request) error {
if !sameOrigin(request.URL, config.BaseURL) {
if !sameOrigin(request.URL, &baseURL) {
return ErrArtifactIntegrity
}
if originalRedirectPolicy != nil {
Expand All @@ -100,7 +102,7 @@ func NewArtifactCache(config ArtifactCacheConfig) (*ArtifactCache, error) {
}
return &ArtifactCache{
root: root,
baseURL: config.BaseURL,
baseURL: &baseURL,
httpClient: client,
downloadTimeout: downloadTimeout,
inflight: make(map[string]*artifactCall),
Expand All @@ -118,6 +120,14 @@ func (c *ArtifactCache) Ensure(ctx context.Context, manifest Manifest) (string,
if err != nil {
return "", err
}
// Every caller supplies its own model manifest, even when prompt artifacts
// share one contract and download. Validate before joining that work.
if !validRelativePath(manifest.R2Prefix) {
return "", ErrUnsafeArtifactPath
}
if err := verifyManifestAggregate(manifest); err != nil {
return "", err
}
c.mu.Lock()
if call := c.inflight[contractID]; call != nil {
c.mu.Unlock()
Expand All @@ -141,12 +151,6 @@ func (c *ArtifactCache) Ensure(ctx context.Context, manifest Manifest) (string,
}

func (c *ArtifactCache) ensureOne(ctx context.Context, manifest Manifest, artifacts []Artifact, contractID string) (string, error) {
if !validRelativePath(manifest.R2Prefix) {
return "", ErrUnsafeArtifactPath
}
if err := verifyManifestAggregate(manifest); err != nil {
return "", err
}
root, err := openVerifiedRoot(c.root, 0o700)
if err != nil {
if errors.Is(err, ErrUnsafeArtifactPath) {
Expand Down Expand Up @@ -216,8 +220,8 @@ func (c *ArtifactCache) ensureOne(ctx context.Context, manifest Manifest, artifa
}
if err := renameRootEntry(root, c.root, tempName, contractID); err != nil {
if ok, verifyErr := verifyPublished(root, contractID); ok {
_ = root.RemoveAll(tempName)
published = true
// Another publisher won. The deferred cleanup makes our read-only
// staging directories writable before removing only our tree.
return path.Join(c.root, contractID), nil
} else if verifyErr != nil &&
!errors.Is(verifyErr, fs.ErrNotExist) &&
Expand Down
177 changes: 177 additions & 0 deletions coordinator/promptcontract/artifact_ownership_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
package promptcontract

import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)

func TestArtifactCacheOwnsConfiguredOrigin(t *testing.T) {
body := []byte(`{"version":"1.0"}`)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/original/pinned/tokenizer.json" {
http.NotFound(w, r)
return
}
_, _ = w.Write(body)
}))
defer server.Close()
base, _ := url.Parse(server.URL + "/original/")
cache, err := NewArtifactCache(ArtifactCacheConfig{
Root: readOnlyTempRoot(t), BaseURL: base, HTTPClient: server.Client(), AllowHTTP: true,
})
if err != nil {
t.Fatal(err)
}
base.Path = "/caller-reused-url/"
if _, err := cache.Ensure(context.Background(), fixtureManifest(map[string][]byte{"tokenizer.json": body})); err != nil {
t.Fatalf("caller URL mutation changed configured artifact source: %v", err)
}
}

func TestArtifactPublicationLoserRemovesReadOnlyStaging(t *testing.T) {
body := []byte(`{"version":"1.0"}`)
entered := make(chan struct{}, 2)
release := make(chan struct{})
var releaseOnce sync.Once
unblock := func() { releaseOnce.Do(func() { close(release) }) }
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
entered <- struct{}{}
select {
case <-release:
_, _ = w.Write(body)
case <-r.Context().Done():
}
}))
defer server.Close()
defer unblock()
base, _ := url.Parse(server.URL + "/")
root := readOnlyTempRoot(t)
manifest := fixtureNestedManifest("nested/tokenizer.json", body)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
results := make(chan error, 2)
for range 2 {
cache, err := NewArtifactCache(ArtifactCacheConfig{Root: root, BaseURL: base, HTTPClient: server.Client(), AllowHTTP: true})
if err != nil {
t.Fatal(err)
}
go func() { _, err := cache.Ensure(ctx, manifest); results <- err }()
}
for range 2 {
select {
case <-entered:
case <-ctx.Done():
t.Fatal("both independent publishers did not reach their download")
}
}
unblock()
for range 2 {
if err := <-results; err != nil {
t.Fatal(err)
}
}
entries, err := os.ReadDir(root)
if err != nil {
t.Fatal(err)
}
if len(entries) != 1 || strings.HasPrefix(entries[0].Name(), ".tmp-") {
t.Fatalf("publication retained staging alongside the winner: %v", entries)
}
if mode := fileMode(t, filepath.Join(root, entries[0].Name())).Perm(); mode != 0o500 {
t.Fatalf("winner permissions changed during loser cleanup: %o", mode)
}
}

func TestProvisionerOwnsQueuedManifestFiles(t *testing.T) {
body := []byte(`{"version":"1.0"}`)
started := make(chan struct{})
release := make(chan struct{})
var releaseOnce sync.Once
unblock := func() { releaseOnce.Do(func() { close(release) }) }
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/pinned/first.json" {
close(started)
select {
case <-release:
case <-r.Context().Done():
return
}
}
_, _ = w.Write(body)
}))
defer server.Close()
defer unblock()
base, _ := url.Parse(server.URL + "/")
cache, err := NewArtifactCache(ArtifactCacheConfig{Root: readOnlyTempRoot(t), BaseURL: base, HTTPClient: server.Client(), AllowHTTP: true})
if err != nil {
t.Fatal(err)
}
provisioner, err := NewProvisioner(context.Background(), cache, ProvisionerConfig{MaxConcurrent: 1})
if err != nil {
t.Fatal(err)
}
defer provisioner.Close()
manifests := []Manifest{fixtureNestedManifest("first.json", body), fixtureNestedManifest("second.json", body)}
manifests[0].ModelID, manifests[1].ModelID = "first", "second"
if err := provisioner.Reconcile(manifests); err != nil {
t.Fatal(err)
}
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("first download did not start")
}
// One worker is blocked above: the second file has not been read by Ensure.
// Callers can reuse their manifest backing arrays after Reconcile returns.
manifests[1].Files[0].Path = "caller-mutated.json"
unblock()
waitForProvision(t, provisioner, 2)
status, ok := provisioner.Status("second")
if !ok || filepath.Base(status.Path) != status.PromptContractID {
t.Fatalf("queued artifact changed after its contract was recorded: %+v", status)
}
if _, err := os.Stat(filepath.Join(status.Path, "second.json")); err != nil {
t.Fatalf("original queued artifact not published: %v", err)
}
}

func TestArtifactCacheValidatesEveryJoiningManifest(t *testing.T) {
body := []byte(`{"version":"1.0"}`)
manifest := fixtureManifest(map[string][]byte{"tokenizer.json": body})
started := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(started)
<-r.Context().Done()
}))
defer server.Close()
base, _ := url.Parse(server.URL + "/")
cache, err := NewArtifactCache(ArtifactCacheConfig{Root: readOnlyTempRoot(t), BaseURL: base, HTTPClient: server.Client(), AllowHTTP: true})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
finished := make(chan struct{})
go func() { defer close(finished); _, _ = cache.Ensure(ctx, manifest) }()
defer func() { cancel(); <-finished }()
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("leader download did not start")
}
invalid := manifest
invalid.AggregateSHA256 = strings.Repeat("0", 64)
follower, cancelFollower := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancelFollower()
if _, err := cache.Ensure(follower, invalid); !errors.Is(err, ErrArtifactIntegrity) {
t.Fatalf("joining manifest escaped its integrity check: %v", err)
}
}
15 changes: 7 additions & 8 deletions coordinator/promptcontract/preload_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,13 +245,17 @@ func (c *PreloadController) matches(provisioned ProvisionSnapshot, child Supervi

func (c *PreloadController) setUnavailable(reason string) {
c.mu.Lock()
c.setUnavailableLocked(boundedStatusError(reason))
c.mu.Unlock()
}

func (c *PreloadController) setUnavailableLocked(reason string) {
c.status.Ready = false
c.status.CatalogGeneration = 0
c.status.ChildGeneration = 0
c.status.ContractCount = 0
c.status.LastError = boundedStatusError(reason)
c.status.LastError = reason
c.contracts = make(map[string]struct{})
c.mu.Unlock()
}

func (c *PreloadController) recordFailure(
Expand All @@ -271,13 +275,8 @@ func (c *PreloadController) recordFailure(
c.retryCatalogGeneration = catalogGeneration
c.retryChildGeneration = childGeneration
c.retryAt = time.Now().Add(c.failureBackoff)
c.status.Ready = false
c.status.CatalogGeneration = 0
c.status.ChildGeneration = 0
c.status.ContractCount = 0
c.setUnavailableLocked(errorText)
c.status.Failures++
c.status.LastError = errorText
c.contracts = make(map[string]struct{})
backoff := c.failureBackoff
c.mu.Unlock()
slog.Warn("prompt sidecar active-set preload failed",
Expand Down
7 changes: 5 additions & 2 deletions coordinator/promptcontract/provisioner.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"log/slog"
"slices"
"sort"
"strings"
"sync"
Expand Down Expand Up @@ -95,8 +96,10 @@ func (p *Provisioner) Reconcile(manifests []Manifest) error {
if len(manifests) > p.maxModels {
return p.rejectCatalog(ErrInvalidConfig)
}
copied := make([]Manifest, len(manifests))
copy(copied, manifests)
copied := slices.Clone(manifests)
for index := range copied {
copied[index].Files = slices.Clone(copied[index].Files)
}
seen := make(map[string]bool, len(copied))
statuses := make(map[string]ProvisionStatus, len(copied))
for _, manifest := range copied {
Expand Down
22 changes: 10 additions & 12 deletions coordinator/promptcontract/supervisor.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,16 +149,14 @@ func (s *Supervisor) run(ctx context.Context) {
continue
}
s.setRestartSuppressed(time.Time{})
reason, detail, stderr, ran, stable := s.runChild(ctx)
reason, detail, stderr, stable := s.runChild(ctx)
if ctx.Err() != nil {
break
}
s.noteRestart(reason, detail, stderr)
restartTimes = append(restartTimes, time.Now())
if stable {
backoff = s.config.RestartBackoffMin
} else if ran {
backoff = nextBackoff(backoff, s.config.RestartBackoffMax)
} else {
backoff = nextBackoff(backoff, s.config.RestartBackoffMax)
}
Expand All @@ -170,19 +168,19 @@ func (s *Supervisor) run(ctx context.Context) {
}

// runChild returns a bounded reason/detail/stderr record and whether the child
// started and ever answered liveness. Readiness degradation alone never ends
// ever answered liveness. Readiness degradation alone never ends
// the child; it only closes the cache-routing gate.
func (s *Supervisor) runChild(ctx context.Context) (string, string, string, bool, bool) {
func (s *Supervisor) runChild(ctx context.Context) (string, string, string, bool) {
if err := prepareSocketDirectory(s.config.SocketPath); err != nil {
return "socket_error", err.Error(), "", false, false
return "socket_error", err.Error(), "", false
}
stderr := newTailBuffer(s.config.StderrMaxBytes)
cmd := exec.Command(s.config.BinaryPath, s.arguments()...)
cmd.Stdin = nil
cmd.Stdout = io.Discard
cmd.Stderr = stderr
if err := cmd.Start(); err != nil {
return "start_error", err.Error(), stderr.String(), false, false
return "start_error", err.Error(), stderr.String(), false
}
generation := s.noteChildStarted(processRSSBytes(cmd.Process.Pid))
waited := make(chan error, 1)
Expand All @@ -197,24 +195,24 @@ func (s *Supervisor) runChild(ctx context.Context) (string, string, string, bool
select {
case <-ctx.Done():
s.terminate(cmd, waited)
return "shutdown", "", stderr.String(), true, live
return "shutdown", "", stderr.String(), live
case err := <-waited:
detail := childExitReason(err, cmd.ProcessState)
s.setChildStopped(generation)
return "child_exit", detail, stderr.String(), true, live
return "child_exit", detail, stderr.String(), live
case <-startup.C:
if !live {
s.terminate(cmd, waited)
s.setChildStopped(generation)
return "startup_timeout", "liveness startup deadline exceeded", stderr.String(), true, false
return "startup_timeout", "liveness startup deadline exceeded", stderr.String(), false
}
case <-ticker.C:
rss := processRSSBytes(cmd.Process.Pid)
if exceedsRSSLimit(rss, s.config.MemoryLimitMiB) {
s.setRuntimeState(generation, true, false, rss, consecutiveFailures)
s.terminate(cmd, waited)
s.setChildStopped(generation)
return "rss_limit", fmt.Sprintf("RSS %d exceeded %d MiB", rss, s.config.MemoryLimitMiB), stderr.String(), true, live
return "rss_limit", fmt.Sprintf("RSS %d exceeded %d MiB", rss, s.config.MemoryLimitMiB), stderr.String(), live
}
if err := s.client.Health(ctx); err != nil {
if live {
Expand All @@ -224,7 +222,7 @@ func (s *Supervisor) runChild(ctx context.Context) (string, string, string, bool
if live && consecutiveFailures >= s.config.HealthFailureThreshold {
s.terminate(cmd, waited)
s.setChildStopped(generation)
return "health_failure_threshold", err.Error(), stderr.String(), true, true
return "health_failure_threshold", err.Error(), stderr.String(), true
}
continue
}
Expand Down
Loading
Loading