Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Preserve customer data across plan downgrades

rcourtman848b4d5038b0
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 2f76da18ed..5047cf6e25 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -4533,3 +4533,9 @@ lifecycle is now the first production path to ingest a server-side provider
observation as independent evidence; the Docker restart lab journey remains a
positive control but does not imply that agent-reported Docker inventory is an
independent production observer.
+
+The API router's tenant-scoped commercial resolver for report scheduling is an
+adjacent entitlement boundary, not agent authority. It may stop a background
+report before generation when the current license lacks `advanced_reporting`,
+but it must not mint agent credentials, dispatch agent work, reinterpret an
+agent receipt, or expand any lifecycle capability.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index f2833a25e7..7bc7bccc6c 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -7621,3 +7621,10 @@ evidence from a trust domain distinct from the executor. Confirmed
verification projection, but the finding maps to `fix_verification_unknown`
and remains unresolved. Malformed digests, missing evidence, and false
independence fail closed through canonical result normalization.
+
+Background report execution now consumes the same tenant-scoped commercial
+license service as the HTTP reporting routes. `runReportSchedule` must check
+`advanced_reporting` before resource resolution or artifact generation, and a
+missing resolver service fails closed in the routed runtime. Downgrade cleanup
+is an internal scheduled side effect only: it does not add a public report API,
+change report payload schemas, or delete schedule definitions.
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index c9f868fa8e..e664743667 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -20,6 +20,18 @@ agreement, the Pulse Cloud control plane, provider-hosted MSP account
bootstrap/licensing, hosted tenant lifecycle, and cloud-specific enforcement
rules.
+The subsystem also owns the canonical commercial offer and transition
+boundary across Community, Relay, Pro, Cloud, and MSP. One versioned offer
+contract must project into public pricing, Pulse Account, in-product plan
+presentation, checkout, the read-only Stripe catalog audit, support policy,
+license-server billing state, and runtime entitlements. Stripe remains billing
+truth, while one Pulse-owned idempotent transition authority must atomically
+project authoritative Stripe subscription snapshots into the local billing
+contract, continuity epoch, entitlement state, license version, transition
+history, and grant-revocation outbox. Checkout, webhook, reconciliation,
+refund, support/admin, and future account transition paths must not implement
+independent entitlement mutation rules.
+
Pulse Pro commercial Pulse Intelligence value reporting is a cloud-paid proof
surface. It must compare full-loop, approved-execution-loop, Assistant-loop,
Assistant-resolved-loop, external-agent-loop, external-agent-resolved-loop,
@@ -1102,12 +1114,32 @@ hands-on Patrol modes, issue investigation, verified fixes, and longer history`.
Absent claim = 0 = unlimited at every hop, which keeps all existing
licenses, grants, and plans inert until the governed rollout sets
`max_users` on a plan.
+27. Add or change the canonical commercial offer, self-hosted subscription
+ transition matrix, cancellation/payment-failure grace, downgrade
+ preservation, or Cloud/MSP availability only through the approved contract
+ in
+ `docs/release-control/v6/internal/records/commercial-offer-lifecycle-contract-2026-07-14.md`.
+ Stripe Customer Portal `subscription_update` remains disabled. Pulse-owned
+ plan changes must use the canonical transition authority, present an
+ explicit amount/effective-date quote, and converge from an authoritative
+ Stripe snapshot rather than trusting one webhook payload or a browser-
+ supplied plan identity. Unknown prices, catalog-version disagreement, and
+ incomplete entitlement projections fail closed. Every material tier,
+ cadence, capability, or restrictive-state change increments
+ `license_version` and emits the version-floor/outbox event in the same
+ local transaction.
## Forbidden Paths
1. New ad hoc plan names in runtime or UI
2. Silent aliases between old and new limit keys in live runtime paths
3. Pricing/UI claims that are not enforced by runtime entitlements
+4. Direct Stripe subscription price changes that update billing identifiers
+ without atomically updating tier, cadence, features, continuity, and license
+ version
+5. Customer Portal configuration as the authority for plan transitions
+6. Separate offer definitions in landing, account, app, support, or Stripe
+ provisioning code
## Completion Obligations
@@ -1237,9 +1269,41 @@ hands-on Patrol modes, issue investigation, verified fixes, and longer history`.
hosted capacity policy, keep it hidden from self-hosted plan cards, and
avoid customer-facing "Unlimited Instances" copy that sounds like the old
capped self-hosted packaging.
+21. Keep the approved self-hosted scope coherent: one owner-operated
+ environment, three primary/migration/recovery activations, and unmetered
+ monitored systems and child resources. Terms, public copy, activation
+ enforcement, support transfer tooling, and MSP boundaries must use the
+ same definition.
+22. Keep Pro's Relay bundle explicit in every offer and fulfillment
+ projection, including Stripe product-description audits. Relay and Pro are
+ distinct jobs rather than sequential ladder steps, and a Pro buyer must
+ never be told to buy Relay separately for the same environment.
+23. Do not expose Relay/Pro or cadence self-service transitions until the
+ `self-hosted-commercial-transition-coherence` gate proves proration,
+ scheduled reductions, cancellation/recovery grace, payment-failure grace,
+ refund/dispute handling, replay/order convergence, downgrade preservation,
+ and grant-version invalidation.
+24. Keep Cloud unavailable and MSP request-assisted until their respective
+ availability contracts are explicitly reopened. Historical Cloud prices,
+ caps, trial, and support labels are dormant planning data, while provider-
+ hosted MSP remains the default assisted-preview delivery boundary.
## Current State
+The approved commercial contract is recorded in
+`docs/release-control/v6/internal/records/commercial-offer-lifecycle-contract-2026-07-14.md`.
+The local self-hosted license server now has an atomic commercial projection
+and a Pulse-owned quoted transition saga for Relay/Pro and cadence changes.
+Cancellation recovery is non-entitling, payment failure has a distinct
+functional grace, unknown or multi-price snapshots fail closed, and runtime
+downgrade state delays physical history/artifact cleanup while blocking paid
+background work immediately. The implementation is not yet a released self-
+service capability: the governed external Stripe transition matrix, event-
+order/reconciliation exercise, Relay version-floor proof, and production
+catalog/portal audit remain required by
+`self-hosted-commercial-transition-coherence`. Cloud remains unavailable and
+MSP remains an assisted preview.
+
Hosted handoff target paths are normalized by the shared host-local redirect
validator at token minting, exchange, and provider-proof boundaries. Absolute,
scheme-relative, backslash-authority, encoded-separator, and control-character
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 0b57ef56ac..03ea017684 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -1176,6 +1176,12 @@ while row retention works correctly. The reclaim stays a once-per-cycle bounded
operation (it skips the checkpoint entirely when the freelist is empty) so WAL
cadence is not made more aggressive, and `TestStoreRetentionReclaimsFreePages`
guards that a pre-existing backlog drains and the file shrinks.
+Commercial history reduction is a second, delayed ceiling on this same store
+boundary. Entitlement access narrows immediately, but `pkg/metrics/store.go`
+must not tighten physical retention until the durable downgrade state reaches
+its governed day-60 purge timestamp. Re-upgrade clears that ceiling before the
+next retention run. The ceiling may only reduce configured retention; it must
+never expand an operator's shorter storage policy.
contract instead of inventing an infrastructure-local summary filter branch.
For shared line charts on that hot path, the shared sparkline primitive may
isolate the selected series inside the existing render budget, but that
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index cf7d278d8b..fe6945353c 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -1377,3 +1377,12 @@ acknowledgement.
This is not an MFA implementation. No acknowledgement label or local browser
state may satisfy an action MFA floor without the existing server-verified,
action-bound cryptographic step-up contract.
+
+Self-hosted commercial transitions authenticate the customer through the
+existing emailed manage-code boundary, then bind the quoted catalog identity,
+amount, proration timestamp, effective date, license version, continuity epoch,
+Stripe customer, subscription, and item to one short-lived hashed quote token.
+The apply route accepts that opaque token only and re-verifies authoritative
+Stripe ownership and current state before mutation. Downgrade artifact cleanup
+must stay within the tenant `reports/generated` directory and skip symlinks so
+commercial retention cannot become an arbitrary-file deletion primitive.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index a1c1d2ce84..04bd1482a9 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -250,6 +250,13 @@ PDF/CSV files are not recovery points, backup artifacts, storage-health
evidence, restore manifests, or cross-client storage inventory. Storage and
recovery flows may preserve them as normal tenant data during backup/restore,
but must not interpret their presence as infrastructure protection.
+Commercial downgrade preserves the schedule definitions as inert tenant
+configuration and blocks background generation when `advanced_reporting` is
+absent. Existing generated files outside the lower entitlement become hidden
+through the commercial access boundary and are purge-eligible only after the
+durable day-60 timestamp. Purge must stay inside `reports/generated`, skip
+directories and symlinks, and never treat the cleanup as deletion of report
+definitions, audit records, backups, or recovery points.
Generated Proxmox setup-script, runtime host-agent setup, and installer
auto-registration changes that affect backup visibility permissions are
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index f2afdca292..49e1f952a0 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -20990,3 +20990,11 @@ func TestContract_PatrolFixVerifiedRequiresIndependentEvidence(t *testing.T) {
t.Fatal("fix_verified must require canonical independent verification; agent-attested confirmation must remain verification unknown")
}
}
+
+func TestContract_BackgroundReportingFailsClosedWithoutCommercialEntitlement(t *testing.T) {
+ handler := NewReportingHandlers(nil, nil)
+ handler.SetCommercialLicenseResolver(func(context.Context) *licenseService { return nil })
+ if err := handler.requireCommercialFeature(context.Background(), featureAdvancedReportingValue); err == nil {
+ t.Fatal("background reporting accepted a missing tenant license service")
+ }
+}
diff --git a/internal/api/licensing_bridge.go b/internal/api/licensing_bridge.go
index a0c3518f5f..cb4413cee5 100644
--- a/internal/api/licensing_bridge.go
+++ b/internal/api/licensing_bridge.go
@@ -44,6 +44,8 @@ type legacyConnectionCountsModel = pkglicensing.LegacyConnectionCounts
type commercialMigrationStatusModel = pkglicensing.CommercialMigrationStatus
type purchaseReturnClaimsModel = pkglicensing.PurchaseReturnClaims
type entitlementLeaseClaimsModel = pkglicensing.EntitlementLeaseClaims
+
+type downgradeRetentionStateModel = pkglicensing.DowngradeRetentionState
type licenseTier = pkglicensing.Tier
type checkoutPortalHandoffRequestModel = pkglicensing.CheckoutPortalHandoffRequest
type checkoutPortalHandoffResponseModel = pkglicensing.CheckoutPortalHandoffResponse
@@ -268,6 +270,10 @@ func parseEntitlementLeaseTokenFromLicensing(token string, key ed25519.PublicKey
return pkglicensing.ParseEntitlementLeaseToken(token, key, expectedInstanceHost)
}
+func normalizeDowngradeRetentionStateFromLicensing(state downgradeRetentionStateModel) downgradeRetentionStateModel {
+ return pkglicensing.NormalizeDowngradeRetentionState(state)
+}
+
func writePaymentRequiredFromLicensing(w http.ResponseWriter, payload map[string]interface{}) {
pkglicensing.WritePaymentRequired(w, payload)
}
diff --git a/internal/api/metrics_reporting_handlers.go b/internal/api/metrics_reporting_handlers.go
index f371a22606..eed80fc38b 100644
--- a/internal/api/metrics_reporting_handlers.go
+++ b/internal/api/metrics_reporting_handlers.go
@@ -93,11 +93,12 @@ func normalizeReportResourceType(raw string) (string, error) {
// ReportingHandlers handles reporting-related requests
type ReportingHandlers struct {
- mtMonitor *monitoring.MultiTenantMonitor
- recoveryManager *recoverymanager.Manager
- narratorResolver func(ctx context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider)
- settingsStore reportingSystemSettingsStore
- scheduleRunMu sync.Mutex
+ mtMonitor *monitoring.MultiTenantMonitor
+ recoveryManager *recoverymanager.Manager
+ narratorResolver func(ctx context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider)
+ settingsStore reportingSystemSettingsStore
+ scheduleRunMu sync.Mutex
+ commercialLicenseResolver func(ctx context.Context) *licenseService
}
type reportingSystemSettingsStore interface {
@@ -123,6 +124,27 @@ func (h *ReportingHandlers) SetSystemSettingsStore(store reportingSystemSettings
h.settingsStore = store
}
+// SetCommercialLicenseResolver wires the tenant-scoped entitlement source used
+// by background report scheduling and downgrade retention. HTTP routes retain
+// their existing middleware gates.
+func (h *ReportingHandlers) SetCommercialLicenseResolver(resolver func(ctx context.Context) *licenseService) {
+ if h == nil {
+ return
+ }
+ h.commercialLicenseResolver = resolver
+}
+
+func (h *ReportingHandlers) requireCommercialFeature(ctx context.Context, feature string) error {
+ if h == nil || h.commercialLicenseResolver == nil {
+ return nil
+ }
+ service := h.commercialLicenseResolver(ctx)
+ if service == nil {
+ return fmt.Errorf("commercial entitlement unavailable")
+ }
+ return service.RequireFeature(feature)
+}
+
func (h *ReportingHandlers) resolveNarrator(ctx context.Context) (reporting.Narrator, reporting.FleetNarrator, reporting.FindingsProvider) {
if h == nil || h.narratorResolver == nil {
return nil, nil, nil
diff --git a/internal/api/report_schedules.go b/internal/api/report_schedules.go
index a034e26eaf..826100c991 100644
--- a/internal/api/report_schedules.go
+++ b/internal/api/report_schedules.go
@@ -459,6 +459,9 @@ func (h *ReportingHandlers) runReportSchedule(ctx context.Context, persistence *
if next, err := nextReportScheduleRunAt(schedule, now); err == nil {
schedule.NextRunAt = &next
}
+ if err := h.requireCommercialFeature(ctx, featureAdvancedReportingValue); err != nil {
+ return result, markReportScheduleFailed(schedule, now, fmt.Errorf("advanced reporting entitlement required: %w", err))
+ }
orgID := GetOrgID(ctx)
resources, err := h.resolveReportScheduleResources(ctx, orgID, schedule.Scope)
@@ -810,10 +813,90 @@ func (h *ReportingHandlers) runDueReportSchedules(ctx context.Context, now time.
}
for _, orgID := range orgIDs {
orgCtx := context.WithValue(ctx, OrgIDContextKey, orgID)
+ h.syncCommercialHistoryRetention(orgCtx, orgID, now)
h.runDueReportSchedulesForOrg(orgCtx, orgID, now)
}
}
+func (h *ReportingHandlers) syncCommercialHistoryRetention(ctx context.Context, orgID string, now time.Time) {
+ if h == nil || h.mtMonitor == nil || h.commercialLicenseResolver == nil {
+ return
+ }
+ monitor, err := h.mtMonitor.GetMonitor(orgID)
+ if err != nil || monitor == nil || monitor.GetMetricsStore() == nil {
+ return
+ }
+ service := h.commercialLicenseResolver(ctx)
+ if service == nil {
+ monitor.GetMetricsStore().SetCommercialHistoryRetention(0, time.Time{})
+ return
+ }
+ activation := service.GetActivationState()
+ if activation == nil || activation.Continuity.DowngradeRetention == nil {
+ monitor.GetMetricsStore().SetCommercialHistoryRetention(0, time.Time{})
+ return
+ }
+ downgrade := normalizeDowngradeRetentionStateFromLicensing(*activation.Continuity.DowngradeRetention)
+ monitor.GetMetricsStore().SetCommercialHistoryRetention(
+ downgrade.CurrentHistoryDays,
+ time.Unix(downgrade.PurgeEligibleAt, 0).UTC(),
+ )
+ if now.UTC().Unix() < downgrade.PurgeEligibleAt || service.RequireFeature(featureAdvancedReportingValue) == nil {
+ return
+ }
+ persistence, err := h.reportSchedulePersistence(ctx)
+ if err != nil {
+ return
+ }
+ if err := purgeGeneratedReportsAfterDowngrade(persistence); err != nil {
+ log.Warn().Err(err).Str("org_id", orgID).Msg("report schedules: purge downgrade artifacts")
+ }
+}
+
+func purgeGeneratedReportsAfterDowngrade(persistence *config.ConfigPersistence) error {
+ if persistence == nil {
+ return nil
+ }
+ baseDir, err := securityutil.JoinStorageLeaf(persistence.DataDir(), "reports")
+ if err != nil {
+ return err
+ }
+ generatedDir, err := securityutil.JoinStorageLeaf(baseDir, "generated")
+ if err != nil {
+ return err
+ }
+ scheduleDirs, err := os.ReadDir(generatedDir)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ for _, scheduleDir := range scheduleDirs {
+ if !scheduleDir.IsDir() || scheduleDir.Type()&os.ModeSymlink != 0 {
+ continue
+ }
+ dir, err := securityutil.JoinStorageLeaf(generatedDir, scheduleDir.Name())
+ if err != nil {
+ continue
+ }
+ files, err := os.ReadDir(dir)
+ if err != nil {
+ continue
+ }
+ for _, file := range files {
+ if file.IsDir() || file.Type()&os.ModeSymlink != 0 {
+ continue
+ }
+ path, err := securityutil.JoinStorageLeaf(dir, file.Name())
+ if err == nil {
+ _ = os.Remove(path)
+ }
+ }
+ }
+ return nil
+}
+
func (h *ReportingHandlers) runDueReportSchedulesForOrg(ctx context.Context, orgID string, now time.Time) {
persistence, store, err := h.reportSchedulePersistenceAndStore(ctx)
if err != nil {
diff --git a/internal/api/report_schedules_test.go b/internal/api/report_schedules_test.go
index d605dc5653..cd11eef322 100644
--- a/internal/api/report_schedules_test.go
+++ b/internal/api/report_schedules_test.go
@@ -4,11 +4,14 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
+ "os"
"path/filepath"
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
@@ -33,6 +36,52 @@ func newTestReportingScheduleHandlers(t *testing.T) (*ReportingHandlers, *config
return NewReportingHandlers(mtm, nil), persistence
}
+func TestRunReportScheduleRequiresCurrentAdvancedReportingEntitlement(t *testing.T) {
+ handler := NewReportingHandlers(nil, nil)
+ service := newLicenseService()
+ handler.SetCommercialLicenseResolver(func(context.Context) *licenseService { return service })
+ now := time.Date(2026, 7, 14, 10, 0, 0, 0, time.UTC)
+ schedule := config.NormalizeReportSchedule(config.ReportSchedule{
+ ID: "report-schedule-entitlement",
+ Name: "Entitlement proof",
+ Enabled: true,
+ })
+ result, updated := handler.runReportSchedule(context.Background(), nil, schedule, now, false, "weekly:proof")
+ if result.path != "" || result.email != "" {
+ t.Fatalf("unentitled scheduler generated output: %+v", result)
+ }
+ if updated.LastRunStatus != config.ReportScheduleLastRunFailed || !strings.Contains(updated.LastError, "advanced reporting entitlement required") {
+ t.Fatalf("unexpected unentitled result: %+v", updated)
+ }
+}
+
+func TestPurgeGeneratedReportsAfterDowngradePreservesDefinitionsAndRejectsSymlinks(t *testing.T) {
+ baseDir := t.TempDir()
+ persistence := config.NewConfigPersistence(baseDir)
+ schedule := config.NormalizeReportSchedule(config.ReportSchedule{ID: "report-schedule-purge", Name: "Purge proof"})
+ report := generatedMultiReport{Filename: "report.pdf", Format: reporting.FormatPDF, Data: []byte("report")}
+ path, err := saveGeneratedReport(persistence, schedule, report)
+ if err != nil {
+ t.Fatalf("save report: %v", err)
+ }
+ outside := filepath.Join(t.TempDir(), "outside.pdf")
+ if err := os.WriteFile(outside, []byte("keep"), 0o600); err != nil {
+ t.Fatalf("write outside: %v", err)
+ }
+ if err := os.Symlink(outside, filepath.Join(filepath.Dir(path), "outside-link.pdf")); err != nil {
+ t.Fatalf("symlink: %v", err)
+ }
+ if err := purgeGeneratedReportsAfterDowngrade(persistence); err != nil {
+ t.Fatalf("purge: %v", err)
+ }
+ if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("generated report still exists: %v", err)
+ }
+ if data, err := os.ReadFile(outside); err != nil || string(data) != "keep" {
+ t.Fatalf("outside target changed: data=%q err=%v", data, err)
+ }
+}
+
func validReportSchedulePayload() config.ReportSchedule {
return config.ReportSchedule{
Name: "Monthly client report",
diff --git a/internal/api/router.go b/internal/api/router.go
index 1c2ead7ea0..af7cd8ca01 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -600,6 +600,9 @@ func (r *Router) setupRoutes() {
SetLicenseServiceProvider(r.licenseHandlers)
r.reportingHandlers = NewReportingHandlers(r.mtMonitor, recoveryManager)
r.reportingHandlers.SetSystemSettingsStore(r.persistence)
+ r.reportingHandlers.SetCommercialLicenseResolver(func(ctx context.Context) *licenseService {
+ return r.licenseHandlers.Service(ctx)
+ })
r.logHandlers = NewLogHandlers(r.config, r.persistence)
rbacHandlers := NewRBACHandlers(r.config, rbacProvider)
var magicLinkService *MagicLinkService
diff --git a/pkg/licensing/activation_types.go b/pkg/licensing/activation_types.go
index aa8d3f16df..0794db3ced 100644
--- a/pkg/licensing/activation_types.go
+++ b/pkg/licensing/activation_types.go
@@ -37,9 +37,22 @@ type ActivationContinuity struct {
// LegacyMigration marks installations activated from a supported v5 license
// exchange rather than a native v6 activation key.
LegacyMigration bool `json:"legacy_migration,omitempty"`
+
+ // DowngradeRetention records the local data-preservation window created by
+ // a reduction in history entitlement. It is local continuity metadata, not
+ // a server-granted capability.
+ DowngradeRetention *DowngradeRetentionState `json:"downgrade_retention,omitempty"`
}
func normalizeActivationContinuity(continuity ActivationContinuity) ActivationContinuity {
+ if continuity.DowngradeRetention != nil {
+ normalized := NormalizeDowngradeRetentionState(*continuity.DowngradeRetention)
+ if normalized.CurrentHistoryDays <= 0 || normalized.PurgeEligibleAt <= normalized.DetectedAt {
+ continuity.DowngradeRetention = nil
+ } else {
+ continuity.DowngradeRetention = &normalized
+ }
+ }
return continuity
}
diff --git a/pkg/licensing/activation_types_test.go b/pkg/licensing/activation_types_test.go
index af2bd2c24b..e2069dc356 100644
--- a/pkg/licensing/activation_types_test.go
+++ b/pkg/licensing/activation_types_test.go
@@ -467,3 +467,19 @@ func searchString(s, substr string) bool {
}
return false
}
+
+func TestActivationContinuityNormalizesDurableDowngradeRetention(t *testing.T) {
+ now := time.Date(2026, 7, 14, 10, 0, 0, 0, time.UTC)
+ state := AdvanceDowngradeRetention(nil, TierPro, TierRelay, now)
+ continuity := normalizeActivationContinuity(ActivationContinuity{DowngradeRetention: state})
+ if continuity.DowngradeRetention == nil {
+ t.Fatal("valid downgrade retention was discarded")
+ }
+ if continuity.DowngradeRetention.CurrentTier != TierRelay || continuity.DowngradeRetention.PurgeEligibleAt != now.AddDate(0, 0, 60).Unix() {
+ t.Fatalf("unexpected normalized downgrade retention: %+v", continuity.DowngradeRetention)
+ }
+ invalid := normalizeActivationContinuity(ActivationContinuity{DowngradeRetention: &DowngradeRetentionState{CurrentHistoryDays: 14, DetectedAt: 100, PurgeEligibleAt: 100}})
+ if invalid.DowngradeRetention != nil {
+ t.Fatalf("invalid downgrade retention survived: %+v", invalid.DowngradeRetention)
+ }
+}
diff --git a/pkg/licensing/grant_refresh.go b/pkg/licensing/grant_refresh.go
index 723bb1f7bb..50b518d8aa 100644
--- a/pkg/licensing/grant_refresh.go
+++ b/pkg/licensing/grant_refresh.go
@@ -193,6 +193,10 @@ func (s *Service) refreshGrantOnce(ctx context.Context) error {
s.mu.RLock()
client := s.serverClient
state := s.activationState
+ previousTier := TierFree
+ if s.license != nil {
+ previousTier = s.license.Claims.Tier
+ }
persistence := s.persistence
clientVersion := s.clientVersion
runtimeIdentity := NormalizeRuntimeIdentity(s.runtimeIdentity)
@@ -229,6 +233,7 @@ func (s *Service) refreshGrantOnce(ctx context.Context) error {
if state != nil {
continuity = normalizeActivationContinuity(state.Continuity)
}
+ continuity.DowngradeRetention = AdvanceDowngradeRetention(continuity.DowngradeRetention, previousTier, Tier(gc.Tier), time.Now())
lic := grantClaimsToLicenseWithContinuity(gc, resp.Grant.JWT, continuity)
s.mu.Lock()
diff --git a/pkg/licensing/grant_refresh_test.go b/pkg/licensing/grant_refresh_test.go
index b2f66d7734..7f03cefedd 100644
--- a/pkg/licensing/grant_refresh_test.go
+++ b/pkg/licensing/grant_refresh_test.go
@@ -893,3 +893,15 @@ func TestGenerateFingerprint(t *testing.T) {
t.Error("two fingerprints should be different")
}
}
+
+func TestGrantRefreshDowngradeWindowSurvivesSameTierRefreshAndClearsOnUpgrade(t *testing.T) {
+ now := time.Date(2026, 7, 14, 10, 0, 0, 0, time.UTC)
+ downgraded := AdvanceDowngradeRetention(nil, TierPro, TierRelay, now)
+ refreshed := AdvanceDowngradeRetention(downgraded, TierRelay, TierRelay, now.Add(time.Hour))
+ if refreshed == nil || refreshed.DetectedAt != downgraded.DetectedAt || refreshed.PurgeEligibleAt != downgraded.PurgeEligibleAt {
+ t.Fatalf("same-tier grant refresh changed downgrade window: %+v", refreshed)
+ }
+ if upgraded := AdvanceDowngradeRetention(refreshed, TierRelay, TierPro, now.Add(2*time.Hour)); upgraded != nil {
+ t.Fatalf("upgraded grant retained purge state: %+v", upgraded)
+ }
+}
diff --git a/pkg/licensing/service.go b/pkg/licensing/service.go
index 3f7ab5c738..0ee0f2c6e4 100644
--- a/pkg/licensing/service.go
+++ b/pkg/licensing/service.go
@@ -891,6 +891,10 @@ func cloneActivationState(in *ActivationState) *ActivationState {
out := *in
out.Continuity = normalizeActivationContinuity(in.Continuity)
+ if out.Continuity.DowngradeRetention != nil {
+ downgrade := *out.Continuity.DowngradeRetention
+ out.Continuity.DowngradeRetention = &downgrade
+ }
return &out
}
diff --git a/pkg/licensing/subscription_test.go b/pkg/licensing/subscription_test.go
index 6d03560dc3..538cb73311 100644
--- a/pkg/licensing/subscription_test.go
+++ b/pkg/licensing/subscription_test.go
@@ -2,6 +2,7 @@ package licensing
import (
"testing"
+ "time"
)
func TestCanTransition_ValidTransitions(t *testing.T) {
@@ -201,3 +202,25 @@ func TestDefaultDowngradePolicy(t *testing.T) {
t.Fatalf("unexpected HardDeleteAfterDays: got=%d want=60", DefaultDowngradePolicy.HardDeleteAfterDays)
}
}
+
+func TestAdvanceDowngradeRetentionPreservesAndClearsRecoveryWindow(t *testing.T) {
+ now := time.Date(2026, 7, 14, 10, 0, 0, 0, time.UTC)
+ state := AdvanceDowngradeRetention(nil, TierPro, TierRelay, now)
+ if state == nil {
+ t.Fatal("expected downgrade retention state")
+ }
+ if state.PreviousHistoryDays != 90 || state.CurrentHistoryDays != 14 {
+ t.Fatalf("history days=%d->%d", state.PreviousHistoryDays, state.CurrentHistoryDays)
+ }
+ if state.RecoveryGuaranteedTo != now.AddDate(0, 0, 30).Unix() || state.PurgeEligibleAt != now.AddDate(0, 0, 60).Unix() {
+ t.Fatalf("unexpected retention window: %+v", state)
+ }
+
+ preserved := AdvanceDowngradeRetention(state, TierRelay, TierRelay, now.Add(24*time.Hour))
+ if preserved == nil || preserved.DetectedAt != state.DetectedAt || preserved.PurgeEligibleAt != state.PurgeEligibleAt {
+ t.Fatalf("same-tier refresh changed retention window: %+v", preserved)
+ }
+ if expanded := AdvanceDowngradeRetention(state, TierRelay, TierPro, now.Add(48*time.Hour)); expanded != nil {
+ t.Fatalf("upgrade should clear pending purge: %+v", expanded)
+ }
+}
diff --git a/pkg/licensing/subscription_transitions.go b/pkg/licensing/subscription_transitions.go
index f879caf419..25592b282c 100644
--- a/pkg/licensing/subscription_transitions.go
+++ b/pkg/licensing/subscription_transitions.go
@@ -2,6 +2,8 @@ package licensing
import (
"slices"
+ "strings"
+ "time"
)
// Transition represents a valid state transition.
@@ -58,3 +60,61 @@ var DefaultDowngradePolicy = DowngradePolicy{
SoftHideGraceDays: 30,
HardDeleteAfterDays: 60,
}
+
+// DowngradeRetentionState is the durable local handoff between a reduced
+// commercial history entitlement and storage retention. Access is restricted
+// immediately by the entitlement evaluator; physical deletion cannot begin
+// before PurgeEligibleAt.
+type DowngradeRetentionState struct {
+ PreviousTier Tier `json:"previous_tier"`
+ CurrentTier Tier `json:"current_tier"`
+ PreviousHistoryDays int `json:"previous_history_days"`
+ CurrentHistoryDays int `json:"current_history_days"`
+ DetectedAt int64 `json:"detected_at"`
+ RecoveryGuaranteedTo int64 `json:"recovery_guaranteed_to"`
+ PurgeEligibleAt int64 `json:"purge_eligible_at"`
+}
+
+// NormalizeDowngradeRetentionState canonicalizes persisted downgrade state.
+func NormalizeDowngradeRetentionState(state DowngradeRetentionState) DowngradeRetentionState {
+ state.PreviousTier = Tier(strings.ToLower(strings.TrimSpace(string(state.PreviousTier))))
+ state.CurrentTier = Tier(strings.ToLower(strings.TrimSpace(string(state.CurrentTier))))
+ return state
+}
+
+// AdvanceDowngradeRetention records a new history reduction, preserves an
+// existing window for same-tier refreshes, and clears it on entitlement
+// expansion before data has been purged.
+func AdvanceDowngradeRetention(existing *DowngradeRetentionState, previousTier, currentTier Tier, now time.Time) *DowngradeRetentionState {
+ previousDays := historyDaysForDowngradeRetention(previousTier)
+ currentDays := historyDaysForDowngradeRetention(currentTier)
+ if currentDays >= previousDays {
+ if currentDays > previousDays {
+ return nil
+ }
+ if existing == nil {
+ return nil
+ }
+ preserved := NormalizeDowngradeRetentionState(*existing)
+ return &preserved
+ }
+
+ detectedAt := now.UTC().Unix()
+ state := &DowngradeRetentionState{
+ PreviousTier: previousTier,
+ CurrentTier: currentTier,
+ PreviousHistoryDays: previousDays,
+ CurrentHistoryDays: currentDays,
+ DetectedAt: detectedAt,
+ RecoveryGuaranteedTo: now.UTC().AddDate(0, 0, DefaultDowngradePolicy.SoftHideGraceDays).Unix(),
+ PurgeEligibleAt: now.UTC().AddDate(0, 0, DefaultDowngradePolicy.HardDeleteAfterDays).Unix(),
+ }
+ return state
+}
+
+func historyDaysForDowngradeRetention(tier Tier) int {
+ if days, ok := TierHistoryDays[tier]; ok && days > 0 {
+ return days
+ }
+ return TierHistoryDays[TierFree]
+}
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index 9ec4540bc1..c14db50075 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -195,12 +195,43 @@ type Store struct {
buffer []bufferedMetric
// Background workers
- writeCh chan writeRequest
- maintenanceCh chan maintenanceRequest
- stopCh chan struct{}
- doneCh chan struct{}
- stopOnce sync.Once
- stopping atomic.Bool
+ writeCh chan writeRequest
+ maintenanceCh chan maintenanceRequest
+ stopCh chan struct{}
+ doneCh chan struct{}
+ stopOnce sync.Once
+ stopping atomic.Bool
+ commercialRetentionSeconds atomic.Int64
+ commercialPurgeEligibleAt atomic.Int64
+}
+
+// SetCommercialHistoryRetention applies a delayed commercial ceiling to the
+// configured physical retention. A zero or negative day count clears the
+// ceiling. Access control is enforced elsewhere immediately; this method only
+// governs when excess history becomes physically purgeable.
+func (s *Store) SetCommercialHistoryRetention(days int, purgeEligibleAt time.Time) {
+ if s == nil || days <= 0 || purgeEligibleAt.IsZero() {
+ if s != nil {
+ s.commercialRetentionSeconds.Store(0)
+ s.commercialPurgeEligibleAt.Store(0)
+ }
+ return
+ }
+ s.commercialRetentionSeconds.Store(int64(time.Duration(days) * 24 * time.Hour / time.Second))
+ s.commercialPurgeEligibleAt.Store(purgeEligibleAt.UTC().Unix())
+}
+
+func (s *Store) effectiveRetention(base time.Duration, now time.Time) time.Duration {
+ seconds := s.commercialRetentionSeconds.Load()
+ eligibleAt := s.commercialPurgeEligibleAt.Load()
+ if seconds <= 0 || eligibleAt <= 0 || now.UTC().Unix() < eligibleAt {
+ return base
+ }
+ commercial := time.Duration(seconds) * time.Second
+ if commercial < base {
+ return commercial
+ }
+ return base
}
// NewStore creates a new metrics store with the given configuration
@@ -1832,10 +1863,10 @@ func (s *Store) runRetention() {
tier Tier
retention time.Duration
}{
- {TierRaw, s.config.RetentionRaw},
- {TierMinute, s.config.RetentionMinute},
- {TierHourly, s.config.RetentionHourly},
- {TierDaily, s.config.RetentionDaily},
+ {TierRaw, s.effectiveRetention(s.config.RetentionRaw, now)},
+ {TierMinute, s.effectiveRetention(s.config.RetentionMinute, now)},
+ {TierHourly, s.effectiveRetention(s.config.RetentionHourly, now)},
+ {TierDaily, s.effectiveRetention(s.config.RetentionDaily, now)},
}
var totalDeleted int64
diff --git a/pkg/metrics/store_additional_test.go b/pkg/metrics/store_additional_test.go
index b8bdd7d359..88abe52bf6 100644
--- a/pkg/metrics/store_additional_test.go
+++ b/pkg/metrics/store_additional_test.go
@@ -906,3 +906,12 @@ func TestStoreRetentionReclaimsFreePages(t *testing.T) {
t.Fatalf("expected freelist to shrink after reclaim: %d -> %d", freelistBefore, freelistAfter)
}
}
+
+func TestCommercialHistoryRetentionNeverExpandsOperatorPolicy(t *testing.T) {
+ store := &Store{}
+ now := time.Date(2026, 7, 14, 10, 0, 0, 0, time.UTC)
+ store.SetCommercialHistoryRetention(14, now)
+ if got := store.effectiveRetention(7*24*time.Hour, now); got != 7*24*time.Hour {
+ t.Fatalf("commercial ceiling expanded shorter operator retention: %v", got)
+ }
+}
diff --git a/pkg/metrics/store_test.go b/pkg/metrics/store_test.go
index 295116f1e2..b6ed2ac519 100644
--- a/pkg/metrics/store_test.go
+++ b/pkg/metrics/store_test.go
@@ -440,6 +440,23 @@ func TestStoreRetentionPrunesOldData(t *testing.T) {
}
}
+func TestCommercialHistoryRetentionWaitsUntilPurgeEligibility(t *testing.T) {
+ store := &Store{}
+ base := 90 * 24 * time.Hour
+ now := time.Date(2026, 7, 14, 10, 0, 0, 0, time.UTC)
+ store.SetCommercialHistoryRetention(14, now.Add(60*24*time.Hour))
+ if got := store.effectiveRetention(base, now.Add(59*24*time.Hour)); got != base {
+ t.Fatalf("retention tightened before purge eligibility: %v", got)
+ }
+ if got := store.effectiveRetention(base, now.Add(60*24*time.Hour)); got != 14*24*time.Hour {
+ t.Fatalf("retention after eligibility=%v", got)
+ }
+ store.SetCommercialHistoryRetention(0, time.Time{})
+ if got := store.effectiveRetention(base, now.Add(90*24*time.Hour)); got != base {
+ t.Fatalf("cleared commercial retention=%v", got)
+ }
+}
+
func TestStoreWriteFlushesBuffer(t *testing.T) {
dir := t.TempDir()
cfg := DefaultConfig(dir)
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 027236884a..f8a58a749d 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -3980,6 +3980,7 @@ class SubsystemLookupTest(unittest.TestCase):
"msp-provider-tenant-management",
"paid-feature-entitlement-gating",
"paid-runtime-build-attribution-alerting",
+ "self-hosted-commercial-transition-coherence",
"upgrade-state-and-entitlement-preservation",
},
)
@@ -3996,6 +3997,7 @@ class SubsystemLookupTest(unittest.TestCase):
self.assertEqual(
{decision["id"] for decision in lane_context["resolved_decisions"]},
{
+ "cloud-msp-availability-contract",
"cloud-msp-price-id-propagation",
"cloud-msp-stripe-prices",
"hosted-tenant-runtime-hibernation",
@@ -4008,10 +4010,13 @@ class SubsystemLookupTest(unittest.TestCase):
"self-hosted-plans-surface-entitlement-first",
"self-hosted-paid-surface-classification",
"self-hosted-core-monitoring-free",
+ "self-hosted-commercial-scope-support-contract",
+ "self-hosted-commercial-transition-contract",
"self-hosted-paid-extras-packaging",
"stable-release-promotion-model",
"stripe-mapping-contract-lock",
"trial-authority-saas-controlled",
+ "unified-commercial-offer-projection-contract",
"v5-pro-price-grandfathering",
},
)