Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: add auto-update delay for new images (#4459)
Kyle Mendellc8fda2bd4459
diff --git a/backend/internal/config/schema/schema.go b/backend/internal/config/schema/schema.goindex 50a13340c..d34bf9b18 100644--- a/backend/internal/config/schema/schema.go+++ b/backend/internal/config/schema/schema.go@@ -99,6 +99,9 @@ var overrideDocRules = map[string]overrideDocRule{"autoUpdateInterval": {requires: "AUTO_UPDATE=true to have effect at runtime.",},+ "autoUpdateDelay": {+ requires: "AUTO_UPDATE=true to have effect at runtime.",+ },"scheduledPruneInterval": {requires: "SCHEDULED_PRUNE_ENABLED=true to have effect at runtime.",},diff --git a/backend/internal/config/schema/schema_test.go b/backend/internal/config/schema/schema_test.goindex 12912729c..67833993c 100644--- a/backend/internal/config/schema/schema_test.go+++ b/backend/internal/config/schema/schema_test.go@@ -289,6 +289,7 @@ var expectedSettingOverrideKeys = []string{"autoHealRestartWindow","autoInjectEnv","autoUpdate",+ "autoUpdateDelay","autoUpdateExcludedContainers","autoUpdateInterval","avatarMaxUploadSizeMb",diff --git a/backend/internal/imageupdate/children/tags/service.go b/backend/internal/imageupdate/children/tags/service.goindex 2af8d8733..aa2d6e149 100644--- a/backend/internal/imageupdate/children/tags/service.go+++ b/backend/internal/imageupdate/children/tags/service.go@@ -147,7 +147,7 @@ func (s *Service) Check(for i, cnt := range candidates {g.Go(func() (workerErr error) {defer utils.RecoverToError(&workerErr, "container tag check worker", "containerId", cnt.ID)- checks[i] = s.checkContainerTag(groupCtx, engine, cnt)+ checks[i] = s.checkContainerTag(groupCtx, engine, adapter, cnt)saveMu.Lock()defer saveMu.Unlock()return save(groupCtx, cnt, checks[i])@@ -236,7 +236,7 @@ func (r tagRegistry) ImageDigest(ctx context.Context, imageRef string) (string,return r.digests.do(parsed.NormalizedRef, fetch)}-func (s *Service) checkContainerTag(ctx context.Context, engine *updater.Service, cnt container.Summary) *imageupdate.Response {+func (s *Service) checkContainerTag(ctx context.Context, engine *updater.Service, digests tagRegistry, cnt container.Summary) *imageupdate.Response {start := time.Now()failed := func(err error) *imageupdate.Response {return &imageupdate.Response{@@ -266,6 +266,19 @@ func (s *Service) checkContainerTag(ctx context.Context, engine *updater.Serviceif err != nil {return failed(err)}+ // A newer tag has no digest yet; resolve it so a tag rewritten during the+ // auto-update delay counts as a new target. An unresolved digest only+ // restarts that delay, so the update itself is still reported.+ targetDigest := func() string {+ if !check.UpdateAvailable || check.TargetDigest != "" {+ return check.TargetDigest+ }+ resolved, resolveErr := digests.ImageDigest(checkCtx, check.TargetRef)+ if resolveErr != nil {+ slog.DebugContext(ctx, "Could not resolve tag update digest", "containerId", cnt.ID, "targetRef", check.TargetRef, "error", resolveErr)+ }+ return resolved+ }()latestVersion, targetErrMessage := func() (string, string) {if check.TargetRef == "" {return "", ""@@ -283,7 +296,7 @@ func (s *Service) checkContainerTag(ctx context.Context, engine *updater.ServiceCurrentVersion: check.CurrentVersion,LatestVersion: latestVersion,CurrentDigest: check.CurrentDigest,- LatestDigest: check.TargetDigest,+ LatestDigest: targetDigest,Error: targetErrMessage,ResponseTimeMs: int(time.Since(start).Milliseconds()),HasUpdate: check.UpdateAvailable && targetErrMessage == "",diff --git a/backend/internal/imageupdate/model.go b/backend/internal/imageupdate/model.goindex b5a736581..15d76ff37 100644--- a/backend/internal/imageupdate/model.go+++ b/backend/internal/imageupdate/model.go@@ -19,23 +19,24 @@ type ImageUpdateRecord struct {ContainerID string `json:"containerId,omitempty" gorm:"column:container_id;not null;default:'';index"`ImageID string `json:"imageId,omitempty" gorm:"column:image_id;not null;default:'';index"`- CheckTime time.Time `json:"checkTime" gorm:"column:check_time"`- LatestVersion *string `json:"latestVersion,omitempty" gorm:"column:latest_version"`- CurrentDigest *string `json:"currentDigest,omitempty" gorm:"column:current_digest"`- LatestDigest *string `json:"latestDigest,omitempty" gorm:"column:latest_digest"`- LastError *string `json:"lastError,omitempty" gorm:"column:last_error"`- AuthMethod *string `json:"authMethod,omitempty" gorm:"column:auth_method"`- AuthUsername *string `json:"authUsername,omitempty" gorm:"column:auth_username"`- AuthRegistry *string `json:"authRegistry,omitempty" gorm:"column:auth_registry"`- ID string `json:"id" gorm:"primaryKey;type:text"`- Repository string `json:"repository"`- Tag string `json:"tag"`- UpdateType string `json:"updateType" gorm:"column:update_type"`- CurrentVersion string `json:"currentVersion" gorm:"column:current_version"`- ResponseTimeMs int `json:"responseTimeMs" gorm:"column:response_time_ms"`- HasUpdate bool `json:"hasUpdate" gorm:"column:has_update"`- UsedCredential bool `json:"usedCredential,omitempty" gorm:"column:used_credential"`- NotificationSent bool `json:"notificationSent" gorm:"column:notification_sent;default:false"`+ CheckTime time.Time `json:"checkTime" gorm:"column:check_time"`+ LatestSeenAt *time.Time `json:"latestSeenAt,omitempty" gorm:"column:latest_seen_at"`+ LatestVersion *string `json:"latestVersion,omitempty" gorm:"column:latest_version"`+ CurrentDigest *string `json:"currentDigest,omitempty" gorm:"column:current_digest"`+ LatestDigest *string `json:"latestDigest,omitempty" gorm:"column:latest_digest"`+ LastError *string `json:"lastError,omitempty" gorm:"column:last_error"`+ AuthMethod *string `json:"authMethod,omitempty" gorm:"column:auth_method"`+ AuthUsername *string `json:"authUsername,omitempty" gorm:"column:auth_username"`+ AuthRegistry *string `json:"authRegistry,omitempty" gorm:"column:auth_registry"`+ ID string `json:"id" gorm:"primaryKey;type:text"`+ Repository string `json:"repository"`+ Tag string `json:"tag"`+ UpdateType string `json:"updateType" gorm:"column:update_type"`+ CurrentVersion string `json:"currentVersion" gorm:"column:current_version"`+ ResponseTimeMs int `json:"responseTimeMs" gorm:"column:response_time_ms"`+ HasUpdate bool `json:"hasUpdate" gorm:"column:has_update"`+ UsedCredential bool `json:"usedCredential,omitempty" gorm:"column:used_credential"`+ NotificationSent bool `json:"notificationSent" gorm:"column:notification_sent;default:false"`}func (i *ImageUpdateRecord) TableName() string {diff --git a/backend/internal/imageupdate/service.go b/backend/internal/imageupdate/service.goindex 2e367b715..12d3f8fc2 100644--- a/backend/internal/imageupdate/service.go+++ b/backend/internal/imageupdate/service.go@@ -816,7 +816,7 @@ func extractRepoAndTagFromImage(dockerImage image.InspectResponse) (repo, tag streturn "<none>", "<none>"}-func buildImageUpdateRecord(imageID, repo, tag string, result *imageupdate.Response, notificationSent bool) *ImageUpdateRecord {+func buildImageUpdateRecord(imageID, repo, tag string, result *imageupdate.Response, notificationSent bool, latestSeenAt *time.Time, carried *ImageUpdateRecord) *ImageUpdateRecord {return &ImageUpdateRecord{ //exhaustruct:enforceBaseModel: database.BaseModel{ID: "",@@ -829,9 +829,10 @@ func buildImageUpdateRecord(imageID, repo, tag string, result *imageupdate.RespoContainerID: "",ImageID: "",CheckTime: result.CheckTime,- LatestVersion: mo.EmptyableToOption(result.LatestVersion).ToPointer(),+ LatestSeenAt: latestSeenAt,+ LatestVersion: cmp.Or(mo.EmptyableToOption(result.LatestVersion).ToPointer(), kit.FromPtr(carried).LatestVersion),CurrentDigest: mo.EmptyableToOption(result.CurrentDigest).ToPointer(),- LatestDigest: mo.EmptyableToOption(result.LatestDigest).ToPointer(),+ LatestDigest: cmp.Or(mo.EmptyableToOption(result.LatestDigest).ToPointer(), kit.FromPtr(carried).LatestDigest),LastError: mo.EmptyableToOption(result.Error).ToPointer(),AuthMethod: mo.EmptyableToOption(result.AuthMethod).ToPointer(),AuthUsername: mo.EmptyableToOption(result.AuthUsername).ToPointer(),@@ -864,13 +865,31 @@ func savePreparedUpdateResultWithTx(tx *gorm.DB, imageID, repo, tag string, resureturn nil}+ sameLatest := kit.FromPtr(existingRecord.LatestDigest) == result.LatestDigest && kit.FromPtr(existingRecord.LatestVersion) == result.LatestVersion+ // A failed check keeps a pending target and when it was first seen, so a+ // transient registry error does not restart the auto-update delay.+ failed := !result.HasUpdate && strings.TrimSpace(result.Error) != "" && existingRecord.LatestSeenAt != nil+// Reset notification_sent if the update state changed in any way; keep the existing// value if nothing changed. New records start with notification_sent = false.+ // latest_seen_at keeps the time the pending update was first seen until it changes.return tx.Save(buildImageUpdateRecord(imageID, repo, tag, result,hasExisting &&existingRecord.HasUpdate == result.HasUpdate &&- (!result.HasUpdate || (kit.FromPtr(existingRecord.LatestDigest) == result.LatestDigest && kit.FromPtr(existingRecord.LatestVersion) == result.LatestVersion)) &&+ (!result.HasUpdate || sameLatest) &&existingRecord.NotificationSent,+ func() *time.Time {+ switch {+ case failed:+ return existingRecord.LatestSeenAt+ case !result.HasUpdate:+ return nil+ case sameLatest:+ return cmp.Or(existingRecord.LatestSeenAt, new(result.CheckTime))+ }+ return new(result.CheckTime)+ }(),+ kit.Ternary(failed, &existingRecord, nil),)).Error}@@ -974,7 +993,7 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,// running the old image as up-to-date (see: #2453).if clearStaleUpdatesErr := tx.Model(&ImageUpdateRecord{}).Where("id LIKE 'ref::%' AND tag = ? AND repository IN ?", tag, slices.Collect(maps.Keys(repositoryCandidates))).- Update("has_update", false).Error; clearStaleUpdatesErr != nil {+ Updates(map[string]any{"has_update": false, "latest_seen_at": nil}).Error; clearStaleUpdatesErr != nil {return fmt.Errorf("clear stale image updates: %w", clearStaleUpdatesErr)}}@@ -999,6 +1018,7 @@ func (s *ImageUpdateService) MarkImageRefUpToDateAfterPull(ctx context.Context,}).Updates(map[string]any{"has_update": false,+ "latest_seen_at": nil,"update_type": UpdateTypeDigest,"current_version": tag,"latest_version": tag,diff --git a/backend/internal/imageupdate/service_test.go b/backend/internal/imageupdate/service_test.goindex 667292416..8619c3bca 100644--- a/backend/internal/imageupdate/service_test.go+++ b/backend/internal/imageupdate/service_test.go@@ -1471,7 +1471,7 @@ func TestImageUpdateService_NotificationSentLogic(t *testing.T) {ResponseTimeMs: 100,}- updateRecord := buildImageUpdateRecord(imageID, repo, tag, result, false)+ updateRecord := buildImageUpdateRecord(imageID, repo, tag, result, false, nil, nil)// New record should have NotificationSent = falseassert.False(t, updateRecord.NotificationSent)@@ -1689,6 +1689,53 @@ func TestImageUpdateService_RateLimitErrorPreservesPreviousResult(t *testing.T)}}+func TestSavePreparedUpdateResult_TracksLatestSeenAt(t *testing.T) {+ db := setupImageUpdateTestDB(t)+ imageID := "sha256:seen"+ repo := "docker.io/library/nginx"+ tag := "latest"+ firstSeen := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC)+ save := func(checkTime time.Time, hasUpdate bool, latestDigest, checkErr string) ImageUpdateRecord {+ t.Helper()+ require.NoError(t, savePreparedUpdateResultWithTx(db.DB, imageID, repo, tag, &imageupdate.Response{+ HasUpdate: hasUpdate,+ UpdateType: UpdateTypeDigest,+ CurrentDigest: "sha256:current",+ LatestDigest: latestDigest,+ Error: checkErr,+ CheckTime: checkTime,+ }))+ var saved ImageUpdateRecord+ require.NoError(t, db.First(&saved, "id = ?", imageID).Error)+ return saved+ }++ saved := save(firstSeen, true, "sha256:new", "")+ require.NotNil(t, saved.LatestSeenAt, "a new update records when it was first seen")+ assert.Equal(t, firstSeen, saved.LatestSeenAt.UTC())++ saved = save(firstSeen.Add(time.Hour), true, "sha256:new", "")+ require.NotNil(t, saved.LatestSeenAt)+ assert.Equal(t, firstSeen, saved.LatestSeenAt.UTC(), "an unchanged recheck keeps the first-seen time")++ saved = save(firstSeen.Add(90*time.Minute), false, "", "registry unavailable")+ require.NotNil(t, saved.LatestSeenAt)+ assert.Equal(t, firstSeen, saved.LatestSeenAt.UTC(), "a failed check keeps the first-seen time")+ assert.Equal(t, new("sha256:new"), saved.LatestDigest, "a failed check keeps the last target")++ saved = save(firstSeen.Add(100*time.Minute), true, "sha256:new", "")+ require.NotNil(t, saved.LatestSeenAt)+ assert.Equal(t, firstSeen, saved.LatestSeenAt.UTC(), "the same target after a failed check keeps the first-seen time")++ changed := firstSeen.Add(2 * time.Hour)+ saved = save(changed, true, "sha256:newer", "")+ require.NotNil(t, saved.LatestSeenAt)+ assert.Equal(t, changed, saved.LatestSeenAt.UTC(), "a new digest restarts the clock")++ saved = save(changed.Add(time.Hour), false, "sha256:current", "")+ assert.Nil(t, saved.LatestSeenAt, "no pending update clears the first-seen time")+}+// TestGetUnnotifiedUpdates tests retrieving updates that haven't been notifiedfunc TestImageUpdateService_GetUnnotifiedUpdates(t *testing.T) {ctx := t.Context()diff --git a/backend/internal/settings/model.go b/backend/internal/settings/model.goindex 37319c023..fa3a46d30 100644--- a/backend/internal/settings/model.go+++ b/backend/internal/settings/model.go@@ -81,6 +81,7 @@ type Settings struct {// Docker categoryAutoUpdate SettingVariable `key:"autoUpdate" meta:"label=Auto Update;type=boolean;keywords=auto,update,automatic,upgrade,refresh,restart,deploy;category=internal;description=Automatically update containers when new images are available"`AutoUpdateInterval SettingVariable `key:"autoUpdateInterval" meta:"label=Auto Update Interval;type=cron;keywords=auto,update,interval,frequency,schedule,automatic,timing;category=internal;description=How often to check for automatic updates (cron expression)"`+ AutoUpdateDelay SettingVariable `key:"autoUpdateDelay" meta:"label=Auto Update Delay;type=number;keywords=auto,update,delay,hours,wait,age,supply,chain,security,quarantine;category=internal;description=Hours a new image must be available before auto-update applies it (0 = immediately)"`AutoUpdateExcludedContainers SettingVariable `key:"autoUpdateExcludedContainers" meta:"label=Excluded Containers;type=text;keywords=exclude,containers,ignore,skip;category=internal;description=Comma-separated list of containers to exclude from auto-update"`PollingEnabled SettingVariable `key:"pollingEnabled" meta:"label=Enable Polling;type=boolean;keywords=polling,check,monitor,watch,scan,detection,automatic;category=internal;description=Enable automatic checking for image updates"`PollingInterval SettingVariable `key:"pollingInterval" meta:"label=Polling Interval;type=cron;keywords=interval,frequency,schedule,time,minutes,period,delay;category=internal;description=How often to check for image updates (cron expression)"`diff --git a/backend/internal/settings/service.go b/backend/internal/settings/service.goindex c664e05c9..420274e2d 100644--- a/backend/internal/settings/service.go+++ b/backend/internal/settings/service.go@@ -41,6 +41,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/utils""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/concurrency""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/httpx"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/validation")@@ -265,6 +266,7 @@ func DefaultSettingsConfig() *Settings {DiskUsagePath: SettingVariable{Value: "/app/data/projects"},AutoUpdate: SettingVariable{Value: "false"},AutoUpdateInterval: SettingVariable{Value: "0 0 0 * * *"},+ AutoUpdateDelay: SettingVariable{Value: "0"},AutoUpdateExcludedContainers: SettingVariable{Value: ""},PollingEnabled: SettingVariable{Value: "true"},PollingInterval: SettingVariable{Value: "0 0 * * * *"},@@ -424,6 +426,12 @@ func validateSettingValue(key, value string) error {return common.Classify(common.ErrValidation, errors.New("upgradeLogRetentionDays must be a whole number between 0 and 3650"))}}+ if key == "autoUpdateDelay" && value != "" {+ hours, err := strconv.Atoi(value)+ if err != nil || hours < 0 || hours > imageref.MaxUpdateDelayHours {+ return common.Classify(common.ErrValidation, fmt.Errorf("autoUpdateDelay must be a whole number between 0 and %d", imageref.MaxUpdateDelayHours))+ }+ }if key == "allEnvironmentsLimit" {limit, err := strconv.Atoi(value)if err != nil || limit < 2 || limit > 256 {diff --git a/backend/internal/updater/children/recovery/service.go b/backend/internal/updater/children/recovery/service.goindex 91fd69c03..3492a1d4e 100644--- a/backend/internal/updater/children/recovery/service.go+++ b/backend/internal/updater/children/recovery/service.go@@ -10,6 +10,7 @@ import ("github.com/getarcaneapp/arcane/types/v2/scheduler"arcaneupdater "github.com/getarcaneapp/arcane/types/v2/updater"+ "github.com/moby/moby/api/types/container""github.com/moby/moby/client""go.getarcane.app/docker/compat"kit "go.getarcane.app/kit/pkg"@@ -102,7 +103,8 @@ func (s *Service) VerifyResult(ctx context.Context, resourceID string) error {// FreezePending persists identities and desired images before any pull. A run// that already holds a plan keeps it. Image refs and container IDs in excluded are left// out, and a target that cannot be frozen fails alone instead of aborting the batch.-func (s *Service) FreezePending(ctx context.Context, run scheduler.Run, excluded map[string]bool) (context.Context, error) {+// Candidates that deferred reports are skipped without failing, so a later run picks them up.+func (s *Service) FreezePending(ctx context.Context, run scheduler.Run, excluded map[string]bool, deferred func(updater.ImageUpdateRecord, container.Summary) bool) (context.Context, error) {if _, ok := ctx.Value(frozenPendingKey{}).(*frozenUpdatePlan); ok {return ctx, nil}@@ -139,6 +141,9 @@ func (s *Service) FreezePending(ctx context.Context, run scheduler.Run, excludedif record.ContainerID == "" && refs.NormalizeImageUpdateRef(candidate.Image) != refs.NormalizeImageUpdateRef(record.ImageRef()) {continue}+ if deferred(record, candidate) {+ continue+ }target, frozenRecord, freezeRecordTargetErr := s.freezeRecordTarget(ctx, record, candidate.ID)if freezeRecordTargetErr != nil {failures[candidate.ID] = freezeRecordTargetErrdiff --git a/backend/internal/updater/children/recovery/service_test.go b/backend/internal/updater/children/recovery/service_test.goindex 1f2ed1878..d76390adf 100644--- a/backend/internal/updater/children/recovery/service_test.go+++ b/backend/internal/updater/children/recovery/service_test.go@@ -20,6 +20,8 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext")+var neverDeferred = func(updater.ImageUpdateRecord, container.Summary) bool { return false }+func newTestService(t *testing.T, server *httptest.Server, pending func(context.Context) ([]updater.ImageUpdateRecord, error)) *Service {t.Helper()dockerClient, err := client.New(client.WithHost(server.URL), client.WithAPIVersion("1.41"), client.WithHTTPClient(server.Client()))@@ -100,7 +102,7 @@ func TestFrozenTargetsPreserveAllSelectedContainers(t *testing.T) {}return nil})- frozenCtx, err := svc.FreezePending(ctx, scheduler.Run{ID: "run"}, nil)+ frozenCtx, err := svc.FreezePending(ctx, scheduler.Run{ID: "run"}, nil, neverDeferred)require.NoError(t, err)plan := frozenCtx.Value(frozenPendingKey{}).(*frozenUpdatePlan)require.Len(t, plan.Records, 2)@@ -254,7 +256,7 @@ func TestFreezePendingExcludesFailedChecksAndIsolatesFreezeFailures(t *testing.Treturn nil})- frozenCtx, err := svc.FreezePending(ctx, scheduler.Run{ID: "run"}, map[string]bool{"registry.example.com/unchecked:latest": true})+ frozenCtx, err := svc.FreezePending(ctx, scheduler.Run{ID: "run"}, map[string]bool{"registry.example.com/unchecked:latest": true}, neverDeferred)require.NoError(t, err)plan := frozenCtx.Value(frozenPendingKey{}).(*frozenUpdatePlan)require.Len(t, plan.Targets, 1)@@ -265,6 +267,76 @@ func TestFreezePendingExcludesFailedChecksAndIsolatesFreezeFailures(t *testing.Trequire.NotContains(t, targets, "unchecked", "images whose check failed stay out of the plan")}+func TestFreezePendingSkipsDeferredCandidatesWithoutFailing(t *testing.T) {+ desired := "sha256:desired"+ pending := []updater.ImageUpdateRecord{+ {+ ID: "app",+ Repository: "registry.example.com/app",+ Tag: "latest",+ HasUpdate: true,+ LatestDigest: &desired,+ },+ {+ ID: "young",+ Repository: "registry.example.com/young",+ Tag: "latest",+ HasUpdate: true,+ LatestDigest: &desired,+ },+ }+ running := []container.Summary{+ {+ ID: "app",+ Names: []string{"/app"},+ Image: "registry.example.com/app:latest",+ },+ {+ ID: "young",+ Names: []string{"/young"},+ Image: "registry.example.com/young:latest",+ Labels: map[string]string{"delay": "true"},+ },+ }+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ if strings.HasSuffix(r.URL.Path, "/containers/json") {+ assert.NoError(t, json.MarshalWrite(w, running))+ return+ }+ for _, summary := range running {+ if strings.HasSuffix(r.URL.Path, "/containers/"+summary.ID+"/json") {+ assert.NoError(t, json.MarshalWrite(w, container.InspectResponse{+ ID: summary.ID,+ Name: summary.Names[0],+ Image: "sha256:old",+ Config: &container.Config{Image: summary.Image},+ State: &container.State{StartedAt: "baseline"},+ }))+ return+ }+ }+ http.NotFound(w, r)+ }))+ defer server.Close()+ svc := newTestService(t, server, func(context.Context) ([]updater.ImageUpdateRecord, error) { return pending, nil })+ targets := map[string]scheduler.TargetOutcome{}+ ctx := jobcontext.WithExecution(t.Context(), scheduler.Run{ID: "run"}, func(target scheduler.TargetOutcome) error {+ targets[target.ID] = target+ return nil+ })++ frozenCtx, err := svc.FreezePending(ctx, scheduler.Run{ID: "run"}, nil, func(record updater.ImageUpdateRecord, candidate container.Summary) bool {+ return record.ID == "young" && candidate.Labels["delay"] == "true"+ })+ require.NoError(t, err)+ plan := frozenCtx.Value(frozenPendingKey{}).(*frozenUpdatePlan)+ require.Len(t, plan.Targets, 1)+ require.Equal(t, "app", plan.Targets[0].ContainerID)+ require.Equal(t, scheduler.Queued, targets["app"].Status)+ require.NotContains(t, targets, "young", "a deferred candidate is neither planned nor failed")+}+func TestResumePlanConfirmsRedeliveredChangeWithoutReapplying(t *testing.T) {target := arcaneupdater.FrozenUpdateTarget{ContainerID: "old",diff --git a/backend/internal/updater/service.go b/backend/internal/updater/service.goindex bfb6dd743..fc43a87bf 100644--- a/backend/internal/updater/service.go+++ b/backend/internal/updater/service.go@@ -771,9 +771,9 @@ func (s *UpdaterService) ClearImageUpdateRecord(ctx context.Context, record updaif record.ContainerID == "" || strings.HasPrefix(record.ID, "container::") {query = query.Where("container_id = ?", record.ContainerID)if record.ID != "" {- return query.Where("id = ?", record.ID).Update("has_update", false).Error+ return query.Where("id = ?", record.ID).Updates(map[string]any{"has_update": false, "latest_seen_at": nil}).Error}- return query.Where("repository = ? AND tag = ?", record.Repository, record.Tag).Update("has_update", false).Error+ return query.Where("repository = ? AND tag = ?", record.Repository, record.Tag).Updates(map[string]any{"has_update": false, "latest_seen_at": nil}).Error}// A shared record stays pending while another non-tag-policy container still runs an older image.@@ -798,7 +798,7 @@ func (s *UpdaterService) ClearImageUpdateRecord(ctx context.Context, record updareturn nil}}- return query.Where("id = ? AND container_id = ?", record.ID, "").Update("has_update", false).Error+ return query.Where("id = ? AND container_id = ?", record.ID, "").Updates(map[string]any{"has_update": false, "latest_seen_at": nil}).Error}// ExcludedContainers returns auto-update exclusions from Arcane settings.@@ -1648,12 +1648,46 @@ func (s *UpdaterService) planAutoUpdate(ctx context.Context, t flow.Task) (any,excluded[target.ID] = true}}- if _, err := s.recovery.FreezePending(contextWithActivityID(ctx, t.ActivityID()), run, excluded); err != nil {+ deferred, err := s.autoUpdateDeferral(ctx, time.Now())+ if err != nil {return nil, common.Classify(common.ErrUnavailable, err)}+ if _, freezeErr := s.recovery.FreezePending(contextWithActivityID(ctx, t.ActivityID()), run, excluded, deferred); freezeErr != nil {+ return nil, common.Classify(common.ErrUnavailable, freezeErr)+ }return nil, nil}+// autoUpdateDeferral reports which pending updates are younger than their+// auto-update delay. The delay label wins over the environment setting, including 0,+// and age counts from when Arcane first saw the update.+func (s *UpdaterService) autoUpdateDeferral(ctx context.Context, now time.Time) (func(updater.ImageUpdateRecord, container.Summary) bool, error) {+ var seen []imageupdate.ImageUpdateRecord+ if err := s.deps.DB.WithContext(ctx).Select("id", "latest_seen_at").Where("has_update = ?", true).Find(&seen).Error; err != nil {+ return nil, err+ }+ seenAt := make(map[string]*time.Time, len(seen))+ for _, record := range seen {+ seenAt[record.ID] = record.LatestSeenAt+ }+ envDelay := s.deps.Settings.GetIntSetting(ctx, "autoUpdateDelay", 0)+ return func(record updater.ImageUpdateRecord, candidate container.Summary) bool {+ override, ok := imageref.UpdateDelay(candidate.Labels)+ delay := time.Duration(min(kit.Ternary(ok, override, envDelay), imageref.MaxUpdateDelayHours)) * time.Hour+ if delay <= 0 {+ return false+ }+ // A missing first-seen time counts as seen now, so the delay is never skipped.+ remaining := kit.FromPtr(cmp.Or(seenAt[record.ID], new(now))).Add(delay).Sub(now)+ if remaining <= 0 {+ return false+ }+ slog.InfoContext(ctx, "Deferring auto-update until the new image has been available for the configured delay",+ "containerId", candidate.ID, "imageRef", record.ImageRef(), "remaining", remaining.Round(time.Minute).String())+ return true+ }, nil+}+// applyAutoUpdate confirms every frozen target on each delivery before// applying the ones still unchanged, so redelivery never repeats a Docker change.func (s *UpdaterService) applyAutoUpdate(ctx context.Context, t flow.Task) (any, error) {diff --git a/backend/internal/updater/service_test.go b/backend/internal/updater/service_test.goindex 96d418ee8..134ddd012 100644--- a/backend/internal/updater/service_test.go+++ b/backend/internal/updater/service_test.go@@ -59,6 +59,7 @@ import ("github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/jobcontext""github.com/getarcaneapp/arcane/backend/v2/pkg/scheduler/runs""github.com/getarcaneapp/arcane/backend/v2/pkg/utils"+ "github.com/getarcaneapp/arcane/backend/v2/pkg/utils/imageref""github.com/getarcaneapp/arcane/backend/v2/pkg/utils/notifications")@@ -1813,3 +1814,60 @@ func TestUpdaterService_WorkflowDefinitionsAreVersioned(t *testing.T) {// auto-update embeds image-check, so bumping image-check also requires bumping auto-update.flowtest.AssertDefinitions(t, harness)}++func TestUpdaterService_AutoUpdateDeferral(t *testing.T) {+ ctx := t.Context()+ db := setupProjectTestDB(t)+ now := time.Date(2026, 10, 17, 12, 0, 0, 0, time.UTC)+ require.NoError(t, db.Create(&[]imageupdate.ImageUpdateRecord{+ {+ ID: "young",+ Repository: "registry.example.com/young",+ Tag: "latest",+ HasUpdate: true,+ LatestSeenAt: new(now.Add(-time.Hour)),+ },+ {+ ID: "old",+ Repository: "registry.example.com/old",+ Tag: "latest",+ HasUpdate: true,+ LatestSeenAt: new(now.Add(-48 * time.Hour)),+ },+ {+ ID: "unseen",+ Repository: "registry.example.com/unseen",+ Tag: "latest",+ HasUpdate: true,+ },+ }).Error)+ settingsService, err := settings.NewSettingsService(ctx, db)+ require.NoError(t, err)+ t.Cleanup(func() { require.NoError(t, settingsService.Stop(context.WithoutCancel(ctx))) })+ require.NoError(t, settingsService.SetIntSetting(ctx, "autoUpdateDelay", 24))+ svc, err := NewUpdaterService(db, settingsService, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)+ require.NoError(t, err)++ deferred, err := svc.autoUpdateDeferral(ctx, now)+ require.NoError(t, err)++ tests := []struct {+ name string+ id string+ labels map[string]string+ want bool+ }{+ {name: "younger than the environment delay", id: "young", want: true},+ {name: "older than the environment delay", id: "old"},+ {name: "missing first-seen time defers", id: "unseen", want: true},+ {name: "label override of 0 applies immediately", id: "young", labels: map[string]string{imageref.UpdateDelayLabel: "0"}},+ {name: "label override longer than the age defers", id: "old", labels: map[string]string{imageref.UpdateDelayLabel: "72"}, want: true},+ {name: "invalid label falls back to the environment delay", id: "young", labels: map[string]string{imageref.UpdateDelayLabel: "-1"}, want: true},+ {name: "oversized label is capped instead of ignored", id: "old", labels: map[string]string{imageref.UpdateDelayLabel: "3000000"}, want: true},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ require.Equal(t, tt.want, deferred(updater.ImageUpdateRecord{ID: tt.id}, container.Summary{Labels: tt.labels}))+ })+ }+}diff --git a/backend/pkg/projects/custom_labels.go b/backend/pkg/projects/custom_labels.goindex 7aecef1f5..93c6dff73 100644--- a/backend/pkg/projects/custom_labels.go+++ b/backend/pkg/projects/custom_labels.go@@ -593,6 +593,14 @@ func updaterMetadataLabels(block any) (map[string]string, error) {result[updaterlabels.LabelUpdater] = strconv.FormatBool(enabled)continue}+ if key == "delay" {+ hours, err := metadataHours(value)+ if err != nil {+ return nil, err+ }+ result[imageref.UpdateDelayLabel] = strconv.Itoa(hours)+ continue+ }var label stringswitch key {case "strategy":@@ -617,6 +625,16 @@ func updaterMetadataLabels(block any) (map[string]string, error) {return result, nil}+// metadataHours accepts a whole, non-negative number of hours. YAML decoders+// may surface it as any numeric type or as a numeric string.+func metadataHours(value any) (int, error) {+ hours, err := strconv.Atoi(strings.TrimSpace(fmt.Sprint(value)))+ if err != nil || hours < 0 || hours > imageref.MaxUpdateDelayHours {+ return 0, fmt.Errorf("updater delay must be a whole number of hours between 0 and %d", imageref.MaxUpdateDelayHours)+ }+ return hours, nil+}+func metadataBool(value any) (bool, error) {if enabled, ok := value.(bool); ok {return enabled, nildiff --git a/backend/pkg/projects/custom_labels_test.go b/backend/pkg/projects/custom_labels_test.goindex fd709c402..c2e8f9f73 100644--- a/backend/pkg/projects/custom_labels_test.go+++ b/backend/pkg/projects/custom_labels_test.go@@ -336,6 +336,55 @@ func TestUpdateCheckMetadataValidation(t *testing.T) {}}+func TestUpdaterDelayMetadataLabels(t *testing.T) {+ const content = `x-arcane:+ updater:+ delay: 72+services:+ inherited:+ image: alpine:3.20.0+ immediate:+ image: alpine:3.20.0+ x-arcane:+ updater:+ delay: 0+ quoted:+ image: alpine:3.20.0+ x-arcane:+ updater:+ delay: "12"+`+ project, err := LoadComposeProjectFromContent(+ t.Context(),+ projecttypes.ComposeContentOptions{+ ComposeContent: content,+ WorkingDir: t.TempDir(),+ ProjectName: "metadata",+ },+ )+ require.NoError(t, err)+ require.Equal(t, "72", project.Services["inherited"].Labels[imageref.UpdateDelayLabel])+ require.Equal(t, "0", project.Services["immediate"].Labels[imageref.UpdateDelayLabel])+ require.Equal(t, "12", project.Services["quoted"].Labels[imageref.UpdateDelayLabel])+}++func TestUpdaterDelayMetadataValidation(t *testing.T) {+ for _, delay := range []string{"-1", "1.5", "soon", "[]", "8761"} {+ t.Run(delay, func(t *testing.T) {+ _, err := LoadComposeProjectFromContent(+ t.Context(),+ projecttypes.ComposeContentOptions{+ ComposeContent: "services:\n app:\n image: alpine:3.20.0\n x-arcane:\n updater:\n delay: " + delay + "\n",+ WorkingDir: t.TempDir(),+ ProjectName: "metadata",+ },+ )+ require.Error(t, err)+ require.Contains(t, err.Error(), "updater delay must be a whole number of hours between 0 and 8760")+ })+ }+}+func TestUpdaterMetadataInterpolationAndIncludesInternal(t *testing.T) {dir := t.TempDir()require.NoError(t, os.WriteFile(filepath.Join(dir, ".env"), []byte("UPDATE_RANGE=3.20.x\nUPDATE_ENABLED=false\n"), 0o600))diff --git a/backend/pkg/utils/imageref/update_lookup.go b/backend/pkg/utils/imageref/update_lookup.goindex 808af761e..7d4f01665 100644--- a/backend/pkg/utils/imageref/update_lookup.go+++ b/backend/pkg/utils/imageref/update_lookup.go@@ -4,6 +4,7 @@ package imagerefimport ("cmp""fmt"+ "strconv""strings"ref "github.com/distribution/reference"@@ -21,6 +22,14 @@ const (// updater label and the UI exclusion list.UpdateCheckLabel = "com.getarcaneapp.arcane.update-check"+ // UpdateDelayLabel overrides the environment's auto-update delay, in hours,+ // for a container or service. A value of 0 applies updates immediately.+ UpdateDelayLabel = "com.getarcaneapp.arcane.updater.delay"++ // MaxUpdateDelayHours caps the auto-update delay at one year, keeping it+ // within time.Duration.+ MaxUpdateDelayHours = 8760+// LocalBuildRegistry is Arcane's reserved registry host for locally built image tags.LocalBuildRegistry = "arcane.local")@@ -46,6 +55,17 @@ func IsUpdateCheckDisabled(labels map[string]string) bool {return parsed && !enabled}+// UpdateDelay returns the auto-update delay override in hours, capped at+// MaxUpdateDelayHours. ok is false when the label is absent or is not a+// non-negative integer.+func UpdateDelay(labels map[string]string) (hours int, ok bool) {+ hours, err := strconv.Atoi(strings.TrimSpace(labels[UpdateDelayLabel]))+ if err != nil || hours < 0 {+ return 0, false+ }+ return min(hours, MaxUpdateDelayHours), true+}+// ParseUpdateLookup normalizes an image reference into the repository and tag// candidates used to match persisted update records.func ParseUpdateLookup(imageRef string) (originalRef, tag string, repositoryCandidates map[string]struct{}, ok bool) {diff --git a/backend/resources/migrations/postgres/094_add_image_update_latest_seen_at.sql b/backend/resources/migrations/postgres/094_add_image_update_latest_seen_at.sqlnew file mode 100644index 000000000..fff9e4f09--- /dev/null+++ b/backend/resources/migrations/postgres/094_add_image_update_latest_seen_at.sql@@ -0,0 +1,6 @@+-- +goose Up+ALTER TABLE image_updates ADD COLUMN IF NOT EXISTS latest_seen_at TIMESTAMPTZ;+UPDATE image_updates SET latest_seen_at = CURRENT_TIMESTAMP WHERE has_update = true;++-- +goose Down+ALTER TABLE image_updates DROP COLUMN IF EXISTS latest_seen_at;diff --git a/backend/resources/migrations/sqlite/094_add_image_update_latest_seen_at.sql b/backend/resources/migrations/sqlite/094_add_image_update_latest_seen_at.sqlnew file mode 100644index 000000000..d94d02ee0--- /dev/null+++ b/backend/resources/migrations/sqlite/094_add_image_update_latest_seen_at.sql@@ -0,0 +1,6 @@+-- +goose Up+ALTER TABLE image_updates ADD COLUMN latest_seen_at DATETIME;+UPDATE image_updates SET latest_seen_at = CURRENT_TIMESTAMP WHERE has_update = 1;++-- +goose Down+ALTER TABLE image_updates DROP COLUMN latest_seen_at;diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex cd15ed0d0..61215ef1f 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -292,6 +292,8 @@"prune_images_dialog_description": "Choose how aggressively Arcane should prune unused Docker images.","auto_update_exclude_description": "Select containers that should not be updated automatically. Arcane keeps checking them for updates and sending notifications.","auto_update_check_label_hint": "To stop update checks and notifications for a container, add the label {label} to it.",+ "auto_update_delay_label": "Update Delay (hours)",+ "auto_update_delay_description": "Hours a new image must be available, counted from when Arcane first detects it, before auto-update installs it. 0 installs immediately and manual updates are never delayed. Override it per container with the label {label}.","auto_update_disabled_checks_continue": "Update checks and notifications stay enabled; only automatic installation is turned off.","auto_update_title": "Auto-Update","auto_update_enabled_toast": "Auto-update enabled",diff --git a/frontend/src/lib/types/settings.ts b/frontend/src/lib/types/settings.tsindex ef2bc24bb..95e0e0bb7 100644--- a/frontend/src/lib/types/settings.ts+++ b/frontend/src/lib/types/settings.ts@@ -25,6 +25,7 @@ export type Settings = {diskUsagePath: string;autoUpdate: boolean;autoUpdateInterval: number;+ autoUpdateDelay?: number;autoUpdateExcludedContainers?: string;pollingEnabled: boolean;imageEventWatcherEnabled: boolean;diff --git a/frontend/src/lib/utils/container-auto-update.ts b/frontend/src/lib/utils/container-auto-update.tsindex 94856f432..1fbfee13c 100644--- a/frontend/src/lib/utils/container-auto-update.ts+++ b/frontend/src/lib/utils/container-auto-update.ts@@ -11,6 +11,8 @@const AUTO_UPDATE_LABEL = 'com.getarcaneapp.arcane.updater';/** Setting this label to a false-like value disables update checks and notifications. */export const UPDATE_CHECK_LABEL = 'com.getarcaneapp.arcane.update-check';+/** Overrides the environment's auto-update delay, in hours, for one container. */+export const UPDATE_DELAY_LABEL = 'com.getarcaneapp.arcane.updater.delay';const DISABLED_LABEL_VALUES = ['false', '0', 'no', 'off'];/** Strips the leading slashes Docker puts on container names. */diff --git a/frontend/src/routes/(app)/environments/[id]/+page.svelte b/frontend/src/routes/(app)/environments/[id]/+page.svelteindex 58d9e7c48..ba15d3c02 100644--- a/frontend/src/routes/(app)/environments/[id]/+page.svelte+++ b/frontend/src/routes/(app)/environments/[id]/+page.svelte@@ -358,6 +358,7 @@lifecycleEnabled: settings?.lifecycleEnabled ?? false,lifecycleDefaultRunnerImage: settings?.lifecycleDefaultRunnerImage || 'alpine:latest',lifecycleMaxTimeoutSec: settings?.lifecycleMaxTimeoutSec ?? 300,+ autoUpdateDelay: settings?.autoUpdateDelay ?? 0,autoUpdateExcludedContainers: settings?.autoUpdateExcludedContainers || '',autoHealEnabled: settings?.autoHealEnabled ?? false,autoHealExcludedContainers: settings?.autoHealExcludedContainers || '',@@ -463,6 +464,7 @@lifecycleEnabled: formData.lifecycleEnabled,lifecycleDefaultRunnerImage: formData.lifecycleDefaultRunnerImage,lifecycleMaxTimeoutSec: formData.lifecycleMaxTimeoutSec,+ autoUpdateDelay: formData.autoUpdateDelay,autoUpdateExcludedContainers: formData.autoUpdateExcludedContainers,autoHealEnabled: formData.autoHealEnabled,autoHealExcludedContainers: formData.autoHealExcludedContainers,diff --git a/frontend/src/routes/(app)/environments/[id]/components/environment-form-schema.ts b/frontend/src/routes/(app)/environments/[id]/components/environment-form-schema.tsindex 8065c6836..600420d3c 100644--- a/frontend/src/routes/(app)/environments/[id]/components/environment-form-schema.ts+++ b/frontend/src/routes/(app)/environments/[id]/components/environment-form-schema.ts@@ -69,6 +69,7 @@ export const environmentFormSchema = environmentUpdateSchemalifecycleEnabled: z.boolean(),lifecycleDefaultRunnerImage: z.string(),lifecycleMaxTimeoutSec: z.coerce.number().int().nonnegative(),+ autoUpdateDelay: z.coerce.number().int().min(0).max(8760),autoUpdateExcludedContainers: z.string().optional(),autoHealEnabled: z.boolean(),autoHealExcludedContainers: z.string(),diff --git a/frontend/src/routes/(app)/environments/[id]/components/jobs-tab.svelte b/frontend/src/routes/(app)/environments/[id]/components/jobs-tab.svelteindex 4f5ad2410..68c3f9551 100644--- a/frontend/src/routes/(app)/environments/[id]/components/jobs-tab.svelte+++ b/frontend/src/routes/(app)/environments/[id]/components/jobs-tab.svelte@@ -27,6 +27,7 @@import { hasPermission } from '#lib/utils/auth.js';import {UPDATE_CHECK_LABEL,+ UPDATE_DELAY_LABEL,isAutoUpdateLabelDisabled,normalizeContainerName,parseExcludedContainerSet@@ -252,6 +253,21 @@{#snippet autoUpdateSettings(job: JobStatus)}{#if job.id === 'auto-update'}<div class="space-y-3">+ <div class="space-y-1">+ <Label for="auto-update-delay">{m.auto_update_delay_label()}</Label>+ <p class="text-xs text-muted-foreground">+ {m.auto_update_delay_description({ label: `${UPDATE_DELAY_LABEL}=<hours>` })}+ </p>+ <Input+ id="auto-update-delay"+ type="number"+ min="0"+ max="8760"+ class="h-8 w-full sm:w-48"+ bind:value={formInputs.autoUpdateDelay.value}+ />+ </div>+<div class="space-y-1"><Label>{m.excluded_containers()}diff --git a/types/settings/settings.go b/types/settings/settings.goindex 1ead8d8e6..5176744ca 100644--- a/types/settings/settings.go+++ b/types/settings/settings.go@@ -69,6 +69,11 @@ type Update struct {// Required: falseAutoUpdateInterval *string `json:"autoUpdateInterval,omitzero"`+ // AutoUpdateDelay is the number of hours a new image must be available before auto-update applies it.+ //+ // Required: false+ AutoUpdateDelay *string `json:"autoUpdateDelay,omitzero"`+// PollingEnabled indicates if polling is enabled.//// Required: false