diff --git a/.github/workflows/memory-high-recovery.yml b/.github/workflows/memory-high-recovery.yml new file mode 100644 index 0000000..de4fb0f --- /dev/null +++ b/.github/workflows/memory-high-recovery.yml @@ -0,0 +1,35 @@ +name: memory-high-recovery +on: + workflow_dispatch: + push: + branches: [feature/memory-high-recovery] + paths: + - .github/workflows/memory-high-recovery.yml + - tests/native-memory-high-recovery.py + - internal/** + - cmd/** + - go.mod +permissions: + contents: read +jobs: + recovery: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff + with: + go-version: '1.27.3' + cache: false + - run: go test -race ./internal/guard ./cmd/crg + - run: | + CGO_ENABLED=0 go build -trimpath -buildvcs=false -ldflags "-X main.revision=$GITHUB_SHA" -o /tmp/crg-recovery ./cmd/crg + mkdir -p "$RUNNER_TEMP/crg-recovery-results" + sudo env CRG_NATIVE_MEMORY_TEST=ephemeral-github-vm-only python3 tests/native-memory-high-recovery.py \ + --binary /tmp/crg-recovery --output "$RUNNER_TEMP/crg-recovery-results/report.json" + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + if: always() + with: + name: memory-high-recovery-results + path: ${{ runner.temp }}/crg-recovery-results/ + if-no-files-found: error diff --git a/CHANGELOG.md b/CHANGELOG.md index b51ad1f..22e29df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # 变更记录 +## v1.0.1 + +新增按容器开启的 `memory.high` 漂移恢复,复用检查间隔、热重载和 journal。支持维护暂停,对重复覆盖退避并告警。[发布说明](docs/releases/v1.0.1.md) · [内核回读和事件日志](docs/test-results-memory-high-recovery.json) + ## v1.0.0(2026-11-17,正式发布) 按用户要求立即发布已验证源37的两架构准确程序,独立百分比、memory.high、BPS、v2门禁、一对一和30天/1GB每日日志交付。长稳/真实回退仍未完成,原验收标准不改,测试继续。详见[正式发布说明](docs/releases/v1.0.0.md)和[发布决策](docs/release-decision-v1.0.0.json)。 diff --git a/README.md b/README.md index 81cffe1..5071ee7 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ > 正式v1.0.0已发布:八项公开附件完整下载/摘要及两架构离线验包通过,[实际发布收据](docs/publication-v1.0.0.zh.md)。长稳、老化后与真实回退验收继续,不因发布改为已通过。 -正式交付:[v1.0.0 下载](https://github.com/cuipengdba/ContainerResourceGuard/releases/tag/v1.0.0) · [发布说明与未完成验收](docs/releases/v1.0.0.md)。按用户要求立即发布正式版;24h基线和原业务/控制检查已通过,同容器限制24h、新七天、老化后与真实回退验收继续,不能将版本发布等同于所有稳定性验收完成。 +当前补丁版 `v1.0.1` 加入按容器开启的 `memory.high` 自动恢复,复用现有间隔和热重载。[下载 v1.0.1](https://github.com/cuipengdba/ContainerResourceGuard/releases/tag/v1.0.1) · [发布说明](docs/releases/v1.0.1.md) · [配置与维护](docs/memory-high-recovery.zh.md) ContainerResourceGuard(CRG)在容器内部控制当前容器的CPU、内存和IO。一个容器一份Agent,DBS与HISDBS分别运行;无需Operator、CRD、Docker socket或Kubernetes API。容器/Pod重建后自动重新识别自身cgroup,无需手改ID。CPU、内存、IO三个独立百分比各默认20%,memory.high回收优先,IO百分比仅读写带宽,保留每日日志及权限不足放行业务的行为。 diff --git a/cmd/crg/main.go b/cmd/crg/main.go index e071443..04a4c22 100644 --- a/cmd/crg/main.go +++ b/cmd/crg/main.go @@ -437,7 +437,19 @@ func mainErr() (result error) { if e != nil { return e } - defer lock.Close() + defer func() { + done := engine.MemoryHighRecoveryDone() + if done == nil { + _ = lock.Close() + return + } + // An older kernel may still be reclaiming in write(). Keep the + // writer locks until that syscall finishes or the process exits. + go func() { + <-done + _ = lock.Close() + }() + }() if err := guard.VerifyIdentity(env); err != nil { return err } @@ -520,6 +532,8 @@ func mainErr() (result error) { lastOutput := "" requestID, controlError := "", "" forceReload := false + recoveryContext, cancelRecovery := context.WithCancel(ctx) + defer cancelRecovery() for { if disabled, err := guard.IsDisabled(c, env); err != nil { return err @@ -528,25 +542,35 @@ func mainErr() (result error) { } currentEnvironment, err := guard.RefreshEnvironment(env) if err != nil { + if c.MemoryHighRecovery && runLog != nil { + runLog.Event("WARN", "memory_high_recovery_identity", map[string]string{"detail": err.Error()}) + } return err } env = currentEnvironment engine.Env = currentEnvironment - watcher.Poll(env, engine.Originals(), forceReload) - forceReload = false - if c.IntervalSeconds != watcher.Current.IntervalSeconds { - ticker.Reset(time.Duration(watcher.Current.IntervalSeconds) * time.Second) - } - c = watcher.Current - if runLog != nil { - runLog.SetDirectory(c.LogDir) - } - engine.Config = c - p, e := guard.BuildPlan(c, env, engine.Originals()) - if e != nil { - return e + r, recovering := engine.PollMemoryHighRecovery() + if !recovering { + watcher.Poll(env, engine.Originals(), forceReload) + forceReload = false + if c.IntervalSeconds != watcher.Current.IntervalSeconds { + ticker.Reset(time.Duration(watcher.Current.IntervalSeconds) * time.Second) + } + c = watcher.Current + if runLog != nil { + runLog.SetDirectory(c.LogDir) + } + engine.Config = c + p, err := guard.BuildPlan(c, env, engine.Originals()) + if err != nil { + return err + } + if *once { + r = engine.Reconcile(p) + } else { + r = engine.ReconcileLive(p, watcher.Revision.Generation, memoryHighRecoveryCheck(recoveryContext, watcher, env)) + } } - r := engine.Reconcile(p) if c.ResourceMode == "percent" && c.Mode == "enforce" && c.IOCalibration == "auto" && automaticIO != nil && c.IOProfile == automaticIO.Profile { r.AutomaticIO = automaticIO if automaticIO.State == "degraded" { @@ -580,12 +604,15 @@ func mainErr() (result error) { stable := guard.StableStatus(r) if stable != lastOutput { emit(r) - logRunStatus(runLog, r) + logRunStatus(runLog, r, c.MemoryHighRecovery) lastOutput = stable } if *once { return nil } + if forceReload && engine.MemoryHighRecoveryDone() == nil { + continue + } waitLoop: for { select { @@ -619,6 +646,8 @@ func mainErr() (result error) { } case <-ticker.C: break waitLoop + case <-engine.MemoryHighRecoveryDone(): + break waitLoop } } } diff --git a/cmd/crg/run_logging.go b/cmd/crg/run_logging.go index b854e86..35ddc69 100644 --- a/cmd/crg/run_logging.go +++ b/cmd/crg/run_logging.go @@ -1,7 +1,10 @@ package main import ( + "context" + "errors" "os" + "strings" "github.com/cuipengdba/ContainerResourceGuard/internal/guard" "github.com/cuipengdba/ContainerResourceGuard/internal/runlog" @@ -25,13 +28,40 @@ func finishRunLogging(log *runlog.Logger, result *error) { } } -func logRunStatus(log *runlog.Logger, status guard.Status) { +func logRunStatus(log *runlog.Logger, status guard.Status, highRecovery bool) { if log == nil { return } items := make([]map[string]string, 0, len(status.Items)) for _, item := range status.Items { - items = append(items, map[string]string{"controller": item.File, "device": item.Device, "value": item.Value, "state": item.State, "detail": item.Detail}) + itemLog := map[string]string{"controller": item.File, "device": item.Device, "value": item.Value, "state": item.State, "detail": item.Detail, "reason_code": item.ReasonCode} + items = append(items, itemLog) + if item.File == "memory.high" && strings.HasPrefix(item.ReasonCode, "memory_high_") { + level := "INFO" + if item.State == "conflict" || item.State == "skipped" { + level = "WARN" + } + log.Event(level, item.ReasonCode, itemLog) + } else if highRecovery && item.File == "memory.high" && item.ReasonCode == "external_conflict" { + log.Event("WARN", "memory_high_external_conflict", itemLog) + } } log.Event("INFO", "resource_status", map[string]any{"state": status.State, "mode": status.Mode, "error": status.Error, "percentages": status.Plan.Percentages, "legacy_percent": status.Plan.Percent, "memory_policy": status.Plan.MemoryPolicy, "io_policy": status.Plan.IOPolicy, "warnings": status.Plan.Warnings, "items": items}) } + +func memoryHighRecoveryCheck(ctx context.Context, watcher *guard.ConfigWatcher, env guard.Environment) func() error { + config := watcher.Current + checkGeneration := watcher.RecoveryCheck() + return func() error { + if err := guard.VerifyIdentity(env); err != nil { + return err + } + if disabled, err := guard.IsDisabled(config, env); err != nil || disabled { + return guard.CancelMemoryHighRecovery(errors.New("agent disabled or maintenance state unavailable")) + } + if err := checkGeneration(); err != nil { + return guard.CancelMemoryHighRecovery(err) + } + return guard.CancelMemoryHighRecovery(ctx.Err()) + } +} diff --git a/docs/configuration.md b/docs/configuration.md index dd7d4d1..2566553 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1,5 +1,7 @@ # 配置参数 +每个容器可通过 `memory_high_recovery` 启用 `memory.high` 漂移恢复,并用 `interval_seconds` 设置检查频率。详见 [自动恢复 memory.high](memory-high-recovery.zh.md)。 + 截至节点2026-11-13 15:41:11 UTC的已完成组快照,已发布工程预览[preview.5](releases/v1.0.0-preview.5.md),两架构包及[八项公开附件下载](test-results-preview5-publication.json)逐字节核对通过。CPU/内存/IO独立百分比各默认20,memory.high、IO百分比仅读写BPS且IOPS手动可选/外部原值保留。新程序在原DBS/HISDBS路径下,默认20%两组各36项、合计[72项完整组通过](testing-bandwidth-default20-two-role.md),六次不同ID启动均在原300秒内,189登记实例与两namespace/六组父叶独立清理。该快照四组144项矩阵处于DBS30、HIS30未执行,后续继续;工程CI为准确ced4617的52项实际cgroup/180项分区/原生ARM64。稳定1.0及其它原门槛继续,历史记录不改。 > 当前交付为[preview.5](releases/v1.0.0-preview.5.md)。最新完整测试结果与剩余发布门槛见[当前交付与待办](release-readiness-current.md);历史时点测试不能代替后续终态。 diff --git a/docs/memory-high-recovery.zh.md b/docs/memory-high-recovery.zh.md new file mode 100644 index 0000000..f16e0e7 --- /dev/null +++ b/docs/memory-high-recovery.zh.md @@ -0,0 +1,45 @@ +# 自动恢复 memory.high + +每个容器通过自己的配置显式开启 `memory_high_recovery`。沿用 `interval_seconds`,设为 `60` 时每分钟检查一次。省略开关或设为 `false` 时沿用原冲突处理。采用原配置加载和热重载方式。 + +下例是 171 的 DBS 验收参数。HISDBS 的相应值为 `15GiB`。两个值都从配置读取。示例使用手动模式单独管理内存。如果容器已有 CPU 或 IO 策略,将恢复开关与间隔合并到现有配置。 + +```json +{ + "mode": "enforce", + "resource_mode": "manual", + "limits": {"memory_high": "30GiB"}, + "interval_seconds": 60, + "memory_high_recovery": true, + "memory_high_recovery_paused": false, + "events_enabled": true +} +``` + +维护前将 `memory_high_recovery_paused` 设为 `true`,原子替换配置并执行 `crg reload --config /etc/crg/config.json`。用 `crg status --config /etc/crg/config.json` 核对 reload 的请求 ID 和接受代次后再维护。正在进行的恢复需要等写入和回读结束后才会接受新配置。维护结束将暂停字段设回 `false` 并热重载。暂停时遇到原有限值漂移到 `max` 会保留暂停状态和原所有权,可以在恢复启用后继续处理。正常热重载仍可在所有权有效时应用新值。 + +使用自定义 `state_dir` 时,`reload` 需要传入相同目录的 `--state-dir`。恢复开启后的 journal 可包含新字段。旧版严格读取配置和 journal,回退前用目标程序做兼容性检查,保留原状态备份并按已有恢复流程处理受控迁移。详见 [安装与回退](installation.md)。 + +恢复只处理当前已校验策略中同一个、曾经由 CRG 应用并回读的有限值变成 `max`。新值须先经正常流程应用并回读,才成为可恢复目标。仅在现值仍匹配此前已完成且改变过内核值的所有权记录时,才能从旧 journal 建立验证记录。较严的外部有限值、无法验证的父级限制、身份变化和未决写入均触发保护。CRG 在现有 writer 锁保护下持久化 intent,复查身份、接受的配置来源、父级限制和内核实际值,随后只对锁定的本容器 cgroup 打开的 `memory.high` 写入并回读。 + +单次恢复在独立任务上运行。旧内核可能在写入时同步回收,任务未完成时检查循环仍更新状态并接收控制请求,同一 writer 的其它写入和接受配置变更等待该任务提交。新配置文件或停用标记可取消尚未开始的写入。内核读写接口没有原子比较交换,写后回读会识别该窗口中仍可观察到的覆盖。持久状态保留原值、有限目标和最近 16 条恢复事件。同一目标一次恢复尝试后 10 分钟内又漂移会保留冲突并停止自动写入,需按现有 journal 冲突流程人工核查。写入或回读失败也会保留故障和未决 intent。成功应用并验证一个新的配置目标后使用该目标的退避记录。 + +日文件和状态中的事件包括 `memory_high_recovery_started`、`memory_high_recovered`、`memory_high_recovery_paused`、`memory_high_recovery_backoff`、`memory_high_recovery_blocked` 和 `memory_high_recovery_failed`。开启 `events_enabled` 还会在 `state_dir/events.jsonl` 导出摘要。验收以 `crg status` 中 `actual` 的内核回读或本容器 `memory.high` 的直接读取为准。高于软阈值时还应核对 `memory.current`、`memory.events` 的 `high` 与 `oom_kill`、内存 PSI 和实际业务延迟。内核支持用量暂时高于软阈值。参考 [Linux cgroup v2 内存控制器](https://docs.kernel.org/admin-guide/cgroup-v2.html#memory-interface-files)。 + +隔离 Linux 验证入口为 [native-memory-high-recovery.py](../tests/native-memory-high-recovery.py)。覆盖 60 秒间隔、DBS 30 GiB、HISDBS 15 GiB、热重载、暂停、容器更换和 journal 隔离、重复覆盖、未开启时的旧冲突行为,以及恢复 96 MiB 阈值时的 PostgreSQL 查询延迟和内核压力。开发验证使用临时测试容器。 + +## 隔离 Linux 验证结果 + +2026-11-20,Linux AMD64 `7.0.0-1017-azure`、PostgreSQL 16.16。受测提交为 `5a3628a57d7545a6401a1367ff823f8f29f9bb3e`。原始报告包含内核回读、journal、事件日志和清理结果。[实测报告](test-results-memory-high-recovery.json) · [Linux 实测](https://github.com/cuipengdba/ContainerResourceGuard/actions/runs/44692261670) · [项目 CI](https://github.com/cuipengdba/ContainerResourceGuard/actions/runs/44692261480) + +| 测试 | 结果 | +| --- | --- | +| DBS,60 秒检查周期 | 在下一轮恢复为 32,212,254,720 字节(30 GiB),从测试写入到观测回读约 60.001 秒。journal 最初值 38 GiB,其他控制值核对一致。 | +| HISDBS,热重载与暂停 | 热重载从 12 GiB 改为 15 GiB。暂停后确保 `max` 持续 5 秒,恢复启用后回读为 16,106,127,360 字节。 | +| 重复覆盖 | 同一目标的再次覆盖写入 `max` 后进入退避冲突;经过后续检查仍回读为 `max`,journal 和日志记录 `memory_high_recovery_backoff`。 | +| 容器更换与旧配置 | 新容器的 ID、cgroup inode 和 journal 身份变更。旧 journal 归档。未配置开关的实例遇到 `max` 后保留原冲突行为。 | +| 写入和恢复保护 | Linux Go race 测试覆盖未决 intent、写入异常、身份或实际值变化、更新配置导致旧任务取消,以及阻塞写入期间检查仍可运行。 | + +压力用例在用量约 **226.8 MiB** 时恢复到 **96 MiB**,随后 `memory.current` 约 **189.5 MiB**。内核 `high` 事件增加 **326** 次,`pgscan` 增加 **11,119**,`oom_kill` 增量为 **0**。两次 6 秒 pgbench 查询均零失败,平均延迟分别为 **0.303 ms** 和 **0.284 ms**,吞吐分别为 **35.01 TPS** 和 **20.55 TPS**。用量和吞吐仍受压力影响,这组数据只覆盖隔离的短查询负载。早期同负载下新启动的容器内清理命令超过 30 秒,最终用例在记录内核与 SQL 结果后由测试宿主清理该临时文件,再等待 journal 确认回读后注入第二次覆盖。[清理超时记录](https://github.com/cuipengdba/ContainerResourceGuard/actions/runs/44681552990) · [重复漂移前等待回读的修正记录](https://github.com/cuipengdba/ContainerResourceGuard/actions/runs/44687972301) + +首次验证的 reload 命令漏传测试实例的自定义状态目录,后续按现有命令参数重试。项目 CI 中的旧厂商阶段自检改为读取与原摘要匹配的冻结夹具,保留原摘要和检查条件。所有临时测试容器及各自 cgroup 均已移除。本轮未在 171 部署。[首次验证记录](https://github.com/cuipengdba/ContainerResourceGuard/actions/runs/44680128956) diff --git a/docs/release-readiness-current.md b/docs/release-readiness-current.md index 2383eae..71fb71e 100644 --- a/docs/release-readiness-current.md +++ b/docs/release-readiness-current.md @@ -1,5 +1,7 @@ # 当前交付与待办:2026-11-16 +当前补丁版 `v1.0.1` 增加 `memory.high` 自动恢复。该功能已完成隔离 Linux 验证,171 业务部署和验收独立记录,下方 v1.0.0 的历史与剩余长期验收继续保留。[v1.0.1 发布说明](releases/v1.0.1.md) · [隔离验证](test-results-memory-high-recovery.json) + > 正式v1.0.0已发布:八项公开附件完整下载/摘要及两架构离线验包通过,[实际发布收据](publication-v1.0.0.zh.md)。长稳、老化后与真实回退验收继续,不因发布改为已通过。 > 2026-11-17用户明确要求现在正式发布v1.0.0,本次按此要求提前发布;该发布决策优先于下文此前“未达全部稳定条件仅预发布”的项目流程。已发布版本身份与完整稳定性资格分别记录,未完成的限制24h、新七天、老化后和真实回退不改为通过,52任务/18原完成声明保持,测试继续。[正式版说明](releases/v1.0.0.md)与[决策记录](release-decision-v1.0.0.json)。以下保留历史时点及原验收条件。 diff --git a/docs/releases/v1.0.1.md b/docs/releases/v1.0.1.md new file mode 100644 index 0000000..fc1220a --- /dev/null +++ b/docs/releases/v1.0.1.md @@ -0,0 +1,17 @@ +# ContainerResourceGuard v1.0.1 + +本次补丁加入按容器配置的 `memory.high` 自动恢复。沿用 `interval_seconds`,设为 `60` 时每分钟检查一次。旧配置保持原冲突处理。 + +```json +{ + "interval_seconds": 60, + "memory_high_recovery": true, + "memory_high_recovery_paused": false +} +``` + +将以上字段合并到现有配置。恢复目标取自当前已验证策略。CRG 只恢复同一 cgroup 中已经成功应用、回读的有限目标漂移到 `max` 的情况。写入前再次确认身份、配置和实际值,写入后回读。维护期间可热重载暂停。未决写入、外部较严限制、写入失败和重复覆盖保留冲突并告警。一次尝试后 10 分钟内再次覆盖同一目标会暂停该 journal 条目的自动写入。 + +隔离 Linux 测试验证了 DBS 示例 30 GiB、HISDBS 示例 15 GiB、检查周期、热重载、维护暂停、换容器和重复覆盖。96 MiB 软阈值压力下,`high` 事件增加,短 SQL 查询零失败,吞吐下降。测试在临时 PostgreSQL 容器完成。171 的部署与业务验收仍待单独执行。[配置和维护](../memory-high-recovery.zh.md) · [内核回读和事件日志](../test-results-memory-high-recovery.json) · [Linux 验收](https://github.com/cuipengdba/ContainerResourceGuard/actions/runs/44692261670) + +安装包提供 Linux AMD64、ARM64,以及 SHA256、SBOM 和构建信息。升级时保留各容器独立配置、状态和日志。旧版本可能拒绝读取新增的配置键和 journal 字段,回退前请核对目标版本的兼容性。详见 [GitHub Release](https://github.com/cuipengdba/ContainerResourceGuard/releases/tag/v1.0.1) 和 [安装与回退](../installation.md)。 diff --git a/docs/requirements.md b/docs/requirements.md index b702e12..4350982 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -1,5 +1,9 @@ # 开发需求档案 +## memory.high 漂移恢复 + +按容器显式开启,复用 `interval_seconds`,旧配置保留原冲突行为。恢复范围为已验证的本容器有限值漂移到 `max`。合法热重载可改变目标,维护可暂停。复用单写入者和 journal,写前重查身份、配置和实际值,写后以内核回读验收。外部更严限制、身份变化、未决写入、失败和重复覆盖保留冲突并告警。隔离 Linux 验证包括 30 GiB、15 GiB、容器更换及超阈值时的回收与 SQL 延迟。任务与操作见 [自动恢复 memory.high](memory-high-recovery.zh.md)。 + ## 2026-11-17:用户要求现在正式发布1.0 用户原话:“正式发布1.0版本啊”。在已告知长稳和真实回退未完成后,按此明确指令发布正式v1.0.0,保留全部功能范围、原验收标准、失败、unknown和后续任务;不重启原长测、不修改测试计时,不将提前发布写成全量稳定验收通过。两架构准确ELF沿用已验证的源37,当前提交文档重新打包,原preview.5不覆盖,服务器生产部署不属于本次发布。[说明](releases/v1.0.0.md)。 diff --git a/docs/test-results-memory-high-recovery.json b/docs/test-results-memory-high-recovery.json new file mode 100644 index 0000000..6185501 --- /dev/null +++ b/docs/test-results-memory-high-recovery.json @@ -0,0 +1,291 @@ +{ + "kernel": "7.0.0-1017-azure", + "binary_sha256": "0cffe4594672d609cc146884363cee22c7ee7689e2cb84247853911214dcdb4f", + "build": { + "arch": "amd64", + "go_version": "go1.27.3", + "io_percent_policy": "calibrated-read-write-bandwidth; IOPS manual only; external IOPS retained", + "io_profile_versions": [ + 1, + 2 + ], + "journal_versions": [ + 1 + ], + "lock_protocol": "cgroup-inode-flock+state-agent-lock-v1", + "memory_policy": "high-reclaim-throttle; percentages may be exceeded; external hard limits retained", + "os": "linux", + "revision": "5a3628a57d7545a6401a1367ff823f8f29f9bb3e", + "version": "dev", + "writer_controls": [ + "cpu.max", + "cpu.weight", + "io.max", + "io.weight", + "memory.max", + "memory.high", + "memory.swap.max", + "pids.max" + ] + }, + "checks": { + "dbs_30GiB_next_60s_check": { + "elapsed_seconds": 60.000566817000006, + "actual": "32212254720", + "original": "40802189312", + "other_controls_match": true + }, + "hisdbs_15GiB_reload_pause_resume": { + "actual": "16106127360", + "paused_for_seconds": 5 + }, + "above_high_reclaim_and_sql_latency": { + "actual": "100663296", + "before": { + "current": 237805568, + "high": 0, + "oom": 0, + "oom_kill": 0, + "pgscan": 0, + "pgsteal": 0, + "psi": "some avg10=0.00 avg60=0.00 avg300=0.00 total=0\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0" + }, + "after": { + "current": 198717440, + "high": 326, + "oom": 0, + "oom_kill": 0, + "pgscan": 11119, + "pgsteal": 9961, + "psi": "some avg10=44.03 avg60=9.24 avg300=1.98 total=6073915\nfull avg10=44.03 avg60=9.24 avg300=1.98 total=6066982" + }, + "sql_baseline": "pgbench (16.16 (Debian 16.16-1.pgdg12+1))\ntransaction type: /state/query.sql\nscaling factor: 1\nquery mode: simple\nnumber of clients: 2\nnumber of threads: 1\nmaximum number of tries: 1\nduration: 6 s\nnumber of transactions actually processed: 208\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.303 ms\nlatency stddev = 0.051 ms\nrate limit schedule lag: avg 0.102 (max 0.146) ms\ninitial connection time = 4.715 ms\ntps = 35.012184 (without initial connection time)", + "sql_during_recovery": "pgbench (16.16 (Debian 16.16-1.pgdg12+1))\ntransaction type: /state/query.sql\nscaling factor: 1\nquery mode: simple\nnumber of clients: 2\nnumber of threads: 1\nmaximum number of tries: 1\nduration: 6 s\nnumber of transactions actually processed: 142\nnumber of failed transactions: 0 (0.000%)\nlatency average = 0.284 ms\nlatency stddev = 0.056 ms\nrate limit schedule lag: avg 0.099 (max 0.130) ms\ninitial connection time = 3.725 ms\ntps = 20.554785 (without initial connection time)", + "other_controls_match": true + }, + "repeated_overwrite": { + "actual": "max", + "journal": { + "file": "memory.high", + "value": "100663296", + "original": "max", + "applied": "100663296", + "conflict": true, + "memory_high_recovery": { + "verified": "100663296", + "last_attempt": "2026-11-20T07:06:36.007769402Z", + "events": [ + { + "time_utc": "2026-11-20T07:06:27.008534043Z", + "generation": 4, + "expected": "16106127360", + "reason": "memory_high_recovery_intent" + }, + { + "time_utc": "2026-11-20T07:06:27.010256179Z", + "generation": 4, + "expected": "16106127360", + "reason": "memory_high_recovered" + }, + { + "time_utc": "2026-11-20T07:06:36.007770253Z", + "generation": 6, + "expected": "100663296", + "reason": "memory_high_recovery_intent" + }, + { + "time_utc": "2026-11-20T07:06:36.009923545Z", + "generation": 6, + "expected": "100663296", + "reason": "memory_high_recovered" + }, + { + "time_utc": "2026-11-20T07:06:44.186169944Z", + "generation": 6, + "expected": "100663296", + "reason": "memory_high_recovery_backoff" + } + ] + } + } + }, + "replacement_id_and_legacy_default": { + "new_identity": true, + "old_journal_retained": true + } + }, + "cleanup": [ + { + "name": "hisdbs-original", + "absent": true + }, + { + "name": "dbs", + "absent": true + }, + { + "name": "hisdbs", + "absent": true + } + ], + "postgres_image_id": "sha256:74b11758bfe1b381b55d2628584c663bac5d029c7e40b15ee00ec631134eb2bc", + "events": [ + { + "time": "2026-11-20T07:06:15.755389304Z", + "level": "INFO", + "event": "memory_high_recovery_started", + "fields": { + "controller": "memory.high", + "detail": "checking memory.high recovery conditions against the current cgroup and journal", + "device": "", + "reason_code": "memory_high_recovery_started", + "state": "pending", + "value": "32212254720" + } + }, + { + "time": "2026-11-20T07:06:15.757465712Z", + "level": "INFO", + "event": "memory_high_recovered", + "fields": { + "controller": "memory.high", + "detail": "restored from max and verified by kernel readback", + "device": "", + "reason_code": "memory_high_recovered", + "state": "applied", + "value": "32212254720" + } + }, + { + "time": "2026-11-20T07:06:21.007673292Z", + "level": "WARN", + "event": "memory_high_recovery_paused", + "fields": { + "controller": "memory.high", + "detail": "memory.high is max; automatic recovery is paused", + "device": "", + "reason_code": "memory_high_recovery_paused", + "state": "conflict", + "value": "16106127360" + } + }, + { + "time": "2026-11-20T07:06:27.008808855Z", + "level": "INFO", + "event": "memory_high_recovery_started", + "fields": { + "controller": "memory.high", + "detail": "checking memory.high recovery conditions against the current cgroup and journal", + "device": "", + "reason_code": "memory_high_recovery_started", + "state": "pending", + "value": "16106127360" + } + }, + { + "time": "2026-11-20T07:06:27.010286157Z", + "level": "INFO", + "event": "memory_high_recovery_started", + "fields": { + "controller": "memory.high", + "detail": "checking memory.high recovery conditions against the current cgroup and journal", + "device": "", + "reason_code": "memory_high_recovery_started", + "state": "pending", + "value": "16106127360" + } + }, + { + "time": "2026-11-20T07:06:27.012197056Z", + "level": "INFO", + "event": "memory_high_recovered", + "fields": { + "controller": "memory.high", + "detail": "restored from max and verified by kernel readback", + "device": "", + "reason_code": "memory_high_recovered", + "state": "applied", + "value": "16106127360" + } + }, + { + "time": "2026-11-20T07:06:29.008233576Z", + "level": "WARN", + "event": "memory_high_recovery_paused", + "fields": { + "controller": "memory.high", + "detail": "memory.high is max; automatic recovery is paused", + "device": "", + "reason_code": "memory_high_recovery_paused", + "state": "conflict", + "value": "100663296" + } + }, + { + "time": "2026-11-20T07:06:36.008210952Z", + "level": "INFO", + "event": "memory_high_recovery_started", + "fields": { + "controller": "memory.high", + "detail": "checking memory.high recovery conditions against the current cgroup and journal", + "device": "", + "reason_code": "memory_high_recovery_started", + "state": "pending", + "value": "100663296" + } + }, + { + "time": "2026-11-20T07:06:40.088191242Z", + "level": "INFO", + "event": "memory_high_recovered", + "fields": { + "controller": "memory.high", + "detail": "restored from max and verified by kernel readback", + "device": "", + "reason_code": "memory_high_recovered", + "state": "applied", + "value": "100663296" + } + }, + { + "time": "2026-11-20T07:06:44.187132724Z", + "level": "INFO", + "event": "memory_high_recovery_started", + "fields": { + "controller": "memory.high", + "detail": "checking memory.high recovery conditions against the current cgroup and journal", + "device": "", + "reason_code": "memory_high_recovery_started", + "state": "pending", + "value": "100663296" + } + }, + { + "time": "2026-11-20T07:06:44.188428519Z", + "level": "WARN", + "event": "memory_high_recovery_backoff", + "fields": { + "controller": "memory.high", + "detail": "memory.high drift repeated within 10 minutes; automatic writes suspended for this journal entry", + "device": "", + "reason_code": "memory_high_recovery_backoff", + "state": "conflict", + "value": "100663296" + } + }, + { + "time": "2026-11-20T07:06:45.007981631Z", + "level": "WARN", + "event": "memory_high_external_conflict", + "fields": { + "controller": "memory.high", + "detail": "external change detected previously; explicit restore/review required", + "device": "", + "reason_code": "external_conflict", + "state": "conflict", + "value": "100663296" + } + } + ], + "phase": "passed" +} diff --git a/internal/guard/config.go b/internal/guard/config.go index 16c04aa..01d206c 100644 --- a/internal/guard/config.go +++ b/internal/guard/config.go @@ -25,6 +25,8 @@ type Config struct { MemoryHigh string `json:"memory_high,omitempty"` MemorySwapMax string `json:"memory_swap_max,omitempty"` MemoryStableSeconds int `json:"memory_stable_seconds,omitempty"` + MemoryHighRecovery bool `json:"memory_high_recovery,omitempty"` + MemoryHighPaused bool `json:"memory_high_recovery_paused,omitempty"` MetricsEnabled bool `json:"metrics_enabled,omitempty"` EventsEnabled bool `json:"events_enabled,omitempty"` Mode string `json:"mode,omitempty"` diff --git a/internal/guard/engine.go b/internal/guard/engine.go index 920424d..d46a92f 100644 --- a/internal/guard/engine.go +++ b/internal/guard/engine.go @@ -25,6 +25,10 @@ func (RealFiles) Write(p, v string) error { if e != nil { return e } + return writeControlFile(f, v) +} + +func writeControlFile(f *os.File, v string) error { n, e := f.WriteString(v + "\n") closeErr := f.Close() if e != nil { @@ -38,10 +42,11 @@ func (RealFiles) Write(p, v string) error { type Mutation struct { Setting - Original string `json:"original"` - Applied string `json:"applied"` - Pending string `json:"pending,omitempty"` - Conflict bool `json:"conflict,omitempty"` + Original string `json:"original"` + Applied string `json:"applied"` + Pending string `json:"pending,omitempty"` + Conflict bool `json:"conflict,omitempty"` + HighRecovery *MemoryHighHistory `json:"memory_high_recovery,omitempty"` } type Journal struct { Version int `json:"version"` @@ -60,6 +65,9 @@ func validateJournal(j Journal) error { if m == nil || !allowed(m.Setting) || key != m.Key() || !validControl(m.Setting, m.Original) || !validControl(m.Setting, m.Applied) || (m.Pending != "" && !validControl(m.Setting, m.Pending)) || !validControl(m.Setting, m.Value) { return errors.New("journal contains an invalid mutation") } + if m.HighRecovery != nil && (m.File != "memory.high" || !m.HighRecovery.valid()) { + return errors.New("journal contains invalid memory.high recovery history") + } } return nil } @@ -83,15 +91,18 @@ type Status struct { AutomaticIO *AutomaticIOStatus `json:"automatic_io,omitempty"` } type Engine struct { - Config Config - Env Environment - Files Files - Journal Journal - Persist func(Journal) error - Pause func(time.Duration) - Now func() time.Time - memoryWindows map[string]memoryWindow - DeviceLookup func(string) (string, error) + Config Config + Env Environment + Files Files + Journal Journal + Persist func(Journal) error + Pause func(time.Duration) + Now func() time.Time + memoryWindows map[string]memoryWindow + DeviceLookup func(string) (string, error) + verifyHierarchy func(string) error + group *os.File + highJob *memoryHighJob } var ErrLocked = errors.New("one agent per container: lock unavailable") @@ -183,6 +194,7 @@ func OpenEngine(c Config, env Environment) (*Engine, *Locks, error) { group.Close() return nil, nil, e } + engine.group = group return engine, &Locks{group: group, state: state}, nil } @@ -284,6 +296,10 @@ func (e *Engine) Originals() map[string]string { func (e *Engine) save() error { return e.Persist(e.Journal) } func (e *Engine) Apply(p Plan) Status { + return e.apply(p, nil) +} + +func (e *Engine) apply(p Plan, highStatus *ItemStatus) Status { if e.Config.Mode == "observe" { e.memoryWindows = nil } @@ -298,7 +314,11 @@ func (e *Engine) Apply(p Plan) Status { status.Items = append(status.Items, item) continue } - item.State, item.Detail, item.ReasonCode = e.applyOne(s) + if highStatus != nil && s.File == "memory.high" { + item = *highStatus + } else { + item.State, item.Detail, item.ReasonCode = e.applyOne(s) + } if item.State != "applied" { status.State = "degraded" } @@ -334,6 +354,7 @@ func (e *Engine) applyOne(s Setting) (string, string, string) { if m.Conflict { return "conflict", "external change detected previously; explicit restore/review required", "external_conflict" } + hadPending := m.Pending != "" if m.Pending != "" { if current == m.Pending { m.Applied = m.Pending @@ -367,6 +388,16 @@ func (e *Engine) applyOne(s Setting) (string, string, string) { } } if current == s.Value { + // Adopt an existing, finalized ownership record only after a fresh + // kernel read. An untouched external value does not establish ownership. + if e.Config.MemoryHighRecovery && s.File == "memory.high" && current != "max" && + !hadPending && m.HighRecovery == nil && m.Original != m.Applied && s.Value == m.Value { + m.HighRecovery = &MemoryHighHistory{Verified: current} + if err := e.save(); err != nil { + m.HighRecovery = nil + return "degraded", "cannot persist memory.high ownership proof: " + err.Error(), "journal_finalize" + } + } return "applied", "already at desired value", "unchanged" } m.Setting = s @@ -418,7 +449,25 @@ func (e *Engine) applyOne(s Setting) (string, string, string) { } m.Applied = s.Value m.Pending = "" + previousProof := m.HighRecovery + if s.File == "memory.high" && s.Value != "max" && (e.Config.MemoryHighRecovery || previousProof != nil) { + history := MemoryHighHistory{Verified: s.Value} + if previousProof != nil { + history = *previousProof + if history.Verified != s.Value { + history.LastAttempt = "" + } + history.Verified = s.Value + } + m.HighRecovery = &history + } if err = e.save(); err != nil { + m.HighRecovery = previousProof + // The persisted intent can still be pending. Never allow async recovery + // to use a transaction whose final state was not durably committed. + if s.File == "memory.high" && (e.Config.MemoryHighRecovery || previousProof != nil) { + m.Pending = s.Value + } return "degraded", "limit written but journal finalization failed: " + err.Error(), "journal_finalize" } return "applied", "written and verified", "applied" @@ -570,6 +619,10 @@ func (e *Engine) restoreKeys(selected map[string]bool) Status { // Reconcile also handles dimensions removed by a new configuration. Restore // only unchanged values that CRG still owns. Observe never initiates writes. func (e *Engine) Reconcile(p Plan) Status { + return e.reconcile(p, nil) +} + +func (e *Engine) reconcile(p Plan, highStatus *ItemStatus) Status { wanted := map[string]bool{} for _, s := range p.Settings { wanted[s.Key()] = true @@ -593,7 +646,7 @@ func (e *Engine) Reconcile(p Plan) Status { return restored // A journal failure forbids additional kernel writes. } } - r := e.Apply(p) + r := e.apply(p, highStatus) if e.Config.Mode == "observe" { for key := range retained { removed[key] = true diff --git a/internal/guard/events.go b/internal/guard/events.go index a7c4a45..18b5a3f 100644 --- a/internal/guard/events.go +++ b/internal/guard/events.go @@ -66,6 +66,8 @@ func eventSummary(s Status) EventRecord { // contents cannot be copied into an event, including from an older state file. func eventReason(s string) string { switch s { + case "memory_high_recovery_started", "memory_high_recovery_slow", "memory_high_recovery_paused", "memory_high_recovery_intent", "memory_high_recovery_blocked", "memory_high_recovery_backoff", "memory_high_recovery_cancelled", "memory_high_recovery_failed", "memory_high_recovered": + return s case "observe", "applied", "unchanged", "invalid_request", "device_identity", "controller_read", "unrestorable_original", "external_conflict", "memory_safety", "memory_window", "task_safety", "swap_safety", "journal_intent", "controller_recheck", "controller_write", "controller_verify", "journal_finalize", "restored", "restore_incomplete", "observe_retained", "plan_unresolved": return s default: diff --git a/internal/guard/memory_high_recovery.go b/internal/guard/memory_high_recovery.go new file mode 100644 index 0000000..0f933bd --- /dev/null +++ b/internal/guard/memory_high_recovery.go @@ -0,0 +1,325 @@ +package guard + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" +) + +const memoryHighBackoff = 10 * time.Minute +const memoryHighHistoryLimit = 16 + +var errMemoryHighCancelled = errors.New("memory.high recovery cancelled") + +func CancelMemoryHighRecovery(err error) error { + if err == nil { + return nil + } + return fmt.Errorf("%w: %s", errMemoryHighCancelled, err) +} + +type MemoryHighEvent struct { + TimeUTC string `json:"time_utc"` + Generation uint64 `json:"generation"` + Expected string `json:"expected"` + Reason string `json:"reason"` +} + +type MemoryHighHistory struct { + Verified string `json:"verified"` + LastAttempt string `json:"last_attempt,omitempty"` + Events []MemoryHighEvent `json:"events,omitempty"` +} + +func (h MemoryHighHistory) valid() bool { + if _, err := strconv.ParseUint(h.Verified, 10, 64); err != nil || len(h.Events) > memoryHighHistoryLimit { + return false + } + if h.LastAttempt != "" { + if _, err := time.Parse(time.RFC3339Nano, h.LastAttempt); err != nil { + return false + } + } + for _, event := range h.Events { + _, timeErr := time.Parse(time.RFC3339Nano, event.TimeUTC) + _, valueErr := strconv.ParseUint(event.Expected, 10, 64) + if timeErr != nil || valueErr != nil || eventReason(event.Reason) != event.Reason || !strings.HasPrefix(event.Reason, "memory_high_") { + return false + } + } + return true +} + +type memoryHighJob struct { + done chan struct{} + initial Status + final ItemStatus + journal Journal + started time.Time +} + +func (e *Engine) MemoryHighRecoveryDone() <-chan struct{} { + if e.highJob == nil { + return nil + } + return e.highJob.done +} + +// While the job owns the journal, the check loop is free to publish status +// and receive control requests. Only this loop adopts the completed journal. +func (e *Engine) PollMemoryHighRecovery() (Status, bool) { + job := e.highJob + if job == nil { + return Status{}, false + } + status := job.initial + status.TimeUTC = time.Now().UTC().Format(time.RFC3339) + select { + case <-job.done: + e.Journal = job.journal + e.highJob = nil + status.Items[0] = job.final + status.State = job.final.State + if status.State == "applied" { + status.State = "managed" + } else { + status.State = "degraded" + } + default: + if time.Since(job.started) >= 5*time.Second { + status.Items[0] = highItem(status.Items[0].Setting, "conflict", "memory_high_recovery_slow", "recovery has not finished; journal and single writer remain reserved") + } + } + return status, true +} + +func highItem(setting Setting, state, reason, detail string) ItemStatus { + return ItemStatus{Setting: setting, State: state, ReasonCode: reason, Detail: detail} +} + +// ReconcileLive adds one narrowly scoped transaction to the regular loop. +// The proof, existing journal entry and current plan must all agree. +func (e *Engine) ReconcileLive(p Plan, generation uint64, recheck func() error) Status { + if status, busy := e.PollMemoryHighRecovery(); busy { + return status + } + if !e.Config.MemoryHighRecovery || e.Config.Mode != "enforce" { + return e.Reconcile(p) + } + for _, setting := range p.Settings { + if setting.File != "memory.high" { + continue + } + mutation := e.Journal.Mutations[setting.Key()] + if mutation == nil || mutation.Conflict || mutation.HighRecovery == nil { + break + } + history := mutation.HighRecovery + if mutation.Pending != "" && len(history.Events) > 0 && + history.Events[len(history.Events)-1].Reason == "memory_high_recovery_intent" { + // Restart after an interrupted recovery. Even an expected readback + // cannot prove the earlier attempt durably finished. + return e.startMemoryHighRecovery(p, setting, generation, recheck) + } + current, err := e.current(setting) + if err != nil || current != "max" { + break + } + if e.Config.MemoryHighPaused && mutation.Pending == "" && + history.Verified == mutation.Applied && mutation.Applied != "max" { + item := highItem(setting, "conflict", "memory_high_recovery_paused", "memory.high is max; automatic recovery is paused") + return e.reconcile(p, &item) + } + if mutation.Pending == "" && (history.Verified != mutation.Applied || mutation.Applied == "max") { + break + } + return e.startMemoryHighRecovery(p, setting, generation, recheck) + } + return e.Reconcile(p) +} + +func (e *Engine) startMemoryHighRecovery(p Plan, setting Setting, generation uint64, recheck func() error) Status { + worker := *e + worker.Journal.Mutations = make(map[string]*Mutation, len(e.Journal.Mutations)) + for key, mutation := range e.Journal.Mutations { + copyMutation := *mutation + if mutation.HighRecovery != nil { + history := *mutation.HighRecovery + history.Events = append([]MemoryHighEvent(nil), history.Events...) + copyMutation.HighRecovery = &history + } + worker.Journal.Mutations[key] = ©Mutation + } + status := Status{TimeUTC: time.Now().UTC().Format(time.RFC3339), Mode: e.Config.Mode, State: "degraded", Plan: p, + Items: []ItemStatus{highItem(setting, "pending", "memory_high_recovery_started", "checking memory.high recovery conditions against the current cgroup and journal")}} + job := &memoryHighJob{initial: status, done: make(chan struct{}), started: time.Now()} + e.highJob = job + go func() { + defer close(job.done) + job.final = worker.recoverMemoryHigh(setting, generation, recheck) + job.journal = worker.Journal + }() + // Polling mutates its own item slice, including the final result. + status.Items = append([]ItemStatus(nil), status.Items...) + return status +} + +func (e *Engine) recoverMemoryHigh(setting Setting, generation uint64, recheck func() error) ItemStatus { + mutation := e.Journal.Mutations[setting.Key()] + history := mutation.HighRecovery + now := time.Now + if e.Now != nil { + now = e.Now + } + expected := history.Verified + record := func(reason string) { + history.Events = append(history.Events, MemoryHighEvent{ + TimeUTC: now().UTC().Format(time.RFC3339Nano), Generation: generation, Expected: expected, Reason: reason, + }) + if len(history.Events) > memoryHighHistoryLimit { + history.Events = history.Events[len(history.Events)-memoryHighHistoryLimit:] + } + } + finish := func(state, reason, detail string) ItemStatus { + if state == "conflict" { + mutation.Conflict = true + } + record(reason) + if err := e.save(); err != nil { + mutation.Conflict = true + return highItem(setting, "conflict", "memory_high_recovery_failed", detail+"; cannot persist journal: "+err.Error()) + } + return highItem(setting, state, reason, detail) + } + for _, entry := range e.Journal.Mutations { + if entry.Pending != "" { + return finish("conflict", "memory_high_recovery_blocked", "unresolved journal intent; external value retained") + } + } + if last, err := time.Parse(time.RFC3339Nano, history.LastAttempt); err == nil && now().Sub(last) < memoryHighBackoff { + return finish("conflict", "memory_high_recovery_backoff", "memory.high drift repeated within 10 minutes; automatic writes suspended for this journal entry") + } + if mutation.Applied != expected || mutation.Value != expected || setting.Value != expected { + return finish("conflict", "memory_high_recovery_blocked", "current plan differs from the last verified value; external value retained") + } + if err := recheck(); err != nil { + if errors.Is(err, errMemoryHighCancelled) { + return finish("skipped", "memory_high_recovery_cancelled", err.Error()) + } + return finish("conflict", "memory_high_recovery_blocked", err.Error()) + } + if err := e.checkMemoryHighCaps(expected); err != nil { + return finish("conflict", "memory_high_recovery_blocked", err.Error()) + } + lastAttempt := history.LastAttempt + mutation.Pending = expected + history.LastAttempt = now().UTC().Format(time.RFC3339Nano) + record("memory_high_recovery_intent") + if err := e.save(); err != nil { + mutation.Conflict = true + return highItem(setting, "conflict", "memory_high_recovery_failed", "cannot save recovery intent: "+err.Error()) + } + beforeWrite := func() error { + if err := e.checkMemoryHighCaps(expected); err != nil { + return err + } + if err := recheck(); err != nil { + return err + } + actual, err := e.current(setting) + if err != nil { + return err + } + if actual != "max" { + return errors.New("memory.high changed while preparing recovery; external value retained") + } + return nil + } + attempted, err := e.writeRecoveredHigh(setting, beforeWrite) + if err != nil { + if !attempted { + mutation.Pending = "" + history.LastAttempt = lastAttempt + if errors.Is(err, errMemoryHighCancelled) { + return finish("skipped", "memory_high_recovery_cancelled", err.Error()) + } + return finish("conflict", "memory_high_recovery_blocked", err.Error()) + } + return finish("conflict", "memory_high_recovery_failed", "write failed; intent retained: "+err.Error()) + } + if e.group != nil { + if err := VerifyIdentity(e.Env); err != nil { + return finish("conflict", "memory_high_recovery_failed", err.Error()) + } + } + actual, err := e.current(setting) + if err != nil || actual != expected { + return finish("conflict", "memory_high_recovery_failed", "kernel readback differs or is unavailable; intent retained") + } + mutation.Pending = "" + result := finish("applied", "memory_high_recovered", "restored from max and verified by kernel readback") + if result.State != "applied" { + mutation.Pending = expected + } + return result +} + +func (e *Engine) writeRecoveredHigh(setting Setting, beforeWrite func() error) (bool, error) { + if e.group == nil { // In-memory Files used by engine tests. + if err := beforeWrite(); err != nil { + return false, err + } + return true, e.write(setting, setting.Value) + } + control, err := openLockedMemoryHigh(e.group) + if err != nil { + return true, err + } + if err := beforeWrite(); err != nil { + control.Close() + return false, err + } + return true, writeControlFile(control, setting.Value) +} + +// Read the visible v2 hierarchy, including the local hard cap. A cgroup +// namespace or bind mount that hides ancestors cannot establish safety. +func (e *Engine) checkMemoryHighCaps(expected string) error { + check := e.verifyHierarchy + if check == nil { + check = verifyCgroup + } + return checkVisibleMemoryCaps(e.Env.Target, expected, e.Files, check) +} + +func checkVisibleMemoryCaps(target, expected string, files Files, isCgroup func(string) error) error { + for dir := target; ; dir = filepath.Dir(dir) { + parent := filepath.Dir(dir) + if parent == dir || isCgroup(parent) != nil { + if dir == target { + return errors.New("cannot verify ancestor memory restrictions") + } + if _, err := files.Read(filepath.Join(dir, "memory.max")); !os.IsNotExist(err) { + return errors.New("cgroup mount hides ancestor memory restrictions") + } + return nil + } + controls := []string{"memory.max"} + if dir != target { + controls = append(controls, "memory.high") + } + for _, file := range controls { + value, err := files.Read(filepath.Join(dir, file)) + if err != nil || !validControl(Setting{File: file}, value) { + return fmt.Errorf("cannot check external %s", file) + } + if maxNumber(value) < maxNumber(expected) { + return fmt.Errorf("stricter external %s; value retained", file) + } + } + } +} diff --git a/internal/guard/memory_high_recovery_test.go b/internal/guard/memory_high_recovery_test.go new file mode 100644 index 0000000..40efe10 --- /dev/null +++ b/internal/guard/memory_high_recovery_test.go @@ -0,0 +1,178 @@ +package guard + +import ( + "errors" + "path/filepath" + "testing" + "time" +) + +func recoveryFixture(t *testing.T) (*Engine, *fakeFiles, Plan, string) { + t.Helper() + engine, files := fixture(t) + leaf := engine.Env.Target + root := filepath.Dir(leaf) + engine.verifyHierarchy = func(path string) error { + if path == root { + return nil + } + return errors.New("outside fixture cgroup filesystem") + } + engine.Config.MemoryHighRecovery = true + control := filepath.Join(leaf, "memory.high") + files.data[control] = "8388608" + plan := Plan{Settings: []Setting{{File: "memory.high", Value: "4194304"}}} + if status := engine.Reconcile(plan); status.State != "managed" { + t.Fatalf("initial application: %+v", status) + } + files.data[control] = "max" + return engine, files, plan, control +} + +func finishedHigh(t *testing.T, engine *Engine) ItemStatus { + t.Helper() + select { + case <-engine.MemoryHighRecoveryDone(): + case <-time.After(5 * time.Second): + t.Fatal("worker did not finish") + } + status, ok := engine.PollMemoryHighRecovery() + if !ok || len(status.Items) != 1 { + t.Fatalf("missing finished transaction: %+v", status) + } + if err := validateJournal(engine.Journal); err != nil { + t.Fatal(err) + } + return status.Items[0] +} + +func TestMemoryHighRecoveryProtectsExternalValuesAndWriteIntent(t *testing.T) { + const key = "memory.high:" + for _, test := range []struct { + name string + reason string + change func(*Engine, *fakeFiles, string) func() error + }{ + {"tighter hard cap", "memory_high_recovery_blocked", func(e *Engine, f *fakeFiles, _ string) func() error { + f.data[filepath.Join(e.Env.Target, "memory.max")] = "2097152" + return nil + }}, + {"pending mutation", "memory_high_recovery_blocked", func(e *Engine, _ *fakeFiles, _ string) func() error { + e.Journal.Mutations[key].Pending = "4194304" + return nil + }}, + {"identity change after intent", "memory_high_recovery_blocked", func(_ *Engine, _ *fakeFiles, _ string) func() error { + calls := 0 + return func() error { + calls++ + if calls == 1 { + return nil + } + return errors.New("identity changed") + } + }}, + {"write error", "memory_high_recovery_failed", func(_ *Engine, f *fakeFiles, _ string) func() error { + f.fail = errors.New("cgroup write rejected") + return nil + }}, + {"actual value changed after intent", "memory_high_recovery_blocked", func(e *Engine, f *fakeFiles, path string) func() error { + e.Persist = func(journal Journal) error { + if journal.Mutations[key].Pending != "" { + f.data[path] = "2097152" + } + return nil + } + return nil + }}, + } { + t.Run(test.name, func(t *testing.T) { + engine, files, plan, path := recoveryFixture(t) + check := test.change(engine, files, path) + if check == nil { + check = func() error { return nil } + } + engine.ReconcileLive(plan, 1, check) + item := finishedHigh(t, engine) + mutation := engine.Journal.Mutations[key] + if item.ReasonCode != test.reason || !mutation.Conflict || mutation.Original != "8388608" || len(files.writes) != 1 { + t.Fatalf("unexpected recovery outcome: %+v, journal %+v, writes %v", item, mutation, files.writes) + } + if test.name == "write error" && mutation.Pending != "4194304" { + t.Fatal("write failure lost the pending intent") + } + }) + } +} + +type blockedHighWrite struct { + *fakeFiles + entered chan struct{} + release chan struct{} +} + +func (f blockedHighWrite) Write(path, value string) error { + close(f.entered) + <-f.release + return f.fakeFiles.Write(path, value) +} + +func TestMemoryHighRecoveryDoesNotWaitForKernelWrite(t *testing.T) { + engine, files, plan, path := recoveryFixture(t) + entered, release := make(chan struct{}), make(chan struct{}) + engine.Files = blockedHighWrite{files, entered, release} + engine.ReconcileLive(plan, 3, func() error { return nil }) + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("the recovery did not reach the kernel write") + } + for range 3 { + status := engine.ReconcileLive(plan, 3, func() error { return errors.New("unexpected second job") }) + if status.Items[0].ReasonCode != "memory_high_recovery_started" { + t.Fatalf("unexpected status while worker owns writer: %+v", status) + } + } + close(release) + if item := finishedHigh(t, engine); item.ReasonCode != "memory_high_recovered" || files.data[path] != "4194304" || len(files.writes) != 2 { + t.Fatalf("unexpected recovery: %+v", item) + } + files.data[path] = "max" + engine.ReconcileLive(plan, 3, func() error { return nil }) + if item := finishedHigh(t, engine); item.ReasonCode != "memory_high_recovery_backoff" || files.data[path] != "max" || len(files.writes) != 2 { + t.Fatalf("recurring drift was not held: %+v", item) + } +} + +func TestMemoryHighRecoveryCancelsQueuedWriteForNewGeneration(t *testing.T) { + engine, files, plan, _ := recoveryFixture(t) + checks := 0 + engine.ReconcileLive(plan, 4, func() error { + checks++ + if checks == 2 { + return CancelMemoryHighRecovery(errors.New("configuration source changed")) + } + return nil + }) + item := finishedHigh(t, engine) + mutation := engine.Journal.Mutations["memory.high:"] + if item.ReasonCode != "memory_high_recovery_cancelled" || mutation.Pending != "" || mutation.Conflict || len(files.writes) != 1 { + t.Fatalf("stale generation was not cancelled: %+v, %+v", item, mutation) + } +} + +func TestMemoryHighRecoveryKeepsInterruptedIntentAfterRestart(t *testing.T) { + engine, files, plan, path := recoveryFixture(t) + mutation := engine.Journal.Mutations["memory.high:"] + mutation.Pending = "4194304" + mutation.HighRecovery.Events = []MemoryHighEvent{{ + TimeUTC: time.Now().UTC().Format(time.RFC3339Nano), Generation: 1, + Expected: "4194304", Reason: "memory_high_recovery_intent", + }} + files.data[path] = "4194304" + engine.ReconcileLive(plan, 1, func() error { return nil }) + item := finishedHigh(t, engine) + mutation = engine.Journal.Mutations["memory.high:"] + if item.ReasonCode != "memory_high_recovery_blocked" || mutation.Pending != "4194304" || !mutation.Conflict || len(files.writes) != 1 { + t.Fatalf("interrupted write was not preserved: %+v, %+v", item, mutation) + } +} diff --git a/internal/guard/platform_linux.go b/internal/guard/platform_linux.go index b0f9e01..835da7f 100644 --- a/internal/guard/platform_linux.go +++ b/internal/guard/platform_linux.go @@ -24,6 +24,14 @@ func openControlForWrite(path string) (*os.File, error) { return os.NewFile(uintptr(fd), path), nil } +func openLockedMemoryHigh(group *os.File) (*os.File, error) { + fd, err := syscall.Openat(int(group.Fd()), "memory.high", syscall.O_WRONLY|syscall.O_NONBLOCK|syscall.O_NOFOLLOW|syscall.O_CLOEXEC, 0) + if err != nil { + return nil, err + } + return os.NewFile(uintptr(fd), "memory.high"), nil +} + func verifyCgroup(p string) error { var s syscall.Statfs_t if e := syscall.Statfs(p, &s); e != nil { diff --git a/internal/guard/platform_other.go b/internal/guard/platform_other.go index 5a661af..3cf9e4c 100644 --- a/internal/guard/platform_other.go +++ b/internal/guard/platform_other.go @@ -17,6 +17,8 @@ func openConfigFile(path string) (*os.File, error) { return os.Open(path) } func openControlForWrite(path string) (*os.File, error) { return os.OpenFile(path, os.O_WRONLY, 0) } +func openLockedMemoryHigh(*os.File) (*os.File, error) { return nil, errors.New("Linux required") } + func openStateJSONFile(path string) (*os.File, error) { st, err := os.Lstat(path) if err != nil { diff --git a/internal/guard/reload.go b/internal/guard/reload.go index 2b4c89d..2711e60 100644 --- a/internal/guard/reload.go +++ b/internal/guard/reload.go @@ -109,6 +109,30 @@ func (w *ConfigWatcher) reject(err error) bool { return changed } +// RecoveryCheck pins the generation accepted by the loop. While the recovery +// owns the journal, the loop queues reloads. A changed source cancels a write +// that has not started yet, even before that queued reload is processed. +func (w *ConfigWatcher) RecoveryCheck() func() error { + path, seen, revision := w.Path, w.seen, w.Revision + return func() error { + if revision.State != "accepted" || revision.Generation == 0 { + return errors.New("memory.high recovery requires an accepted configuration") + } + if path == "" { + return nil + } + data, err := ReadBoundedFile(path) + if err != nil { + return err + } + digest := sha256.Sum256(data) + if hex.EncodeToString(digest[:]) != seen { + return errors.New("configuration source changed before memory.high recovery") + } + return nil + } +} + // Poll never discards Current on error. Validate and build the entire candidate // before accepting it. No cgroup mutation or journal write happens here. func (w *ConfigWatcher) Poll(env Environment, original map[string]string, force bool) bool { diff --git a/tests/native-memory-high-recovery.py b/tests/native-memory-high-recovery.py new file mode 100644 index 0000000..71f479b --- /dev/null +++ b/tests/native-memory-high-recovery.py @@ -0,0 +1,303 @@ +#!/usr/bin/env python3 +"""Exercise the actual CRG CLI and v2 controls in disposable PostgreSQL containers.""" +import argparse +from concurrent.futures import ThreadPoolExecutor +import hashlib +import json +import os +from pathlib import Path +import platform +import re +import subprocess +import tempfile +import time +import uuid + + +def command(*args, timeout=30): + proc = subprocess.run([str(arg) for arg in args], capture_output=True, text=True, timeout=timeout) + if proc.returncode: + raise RuntimeError(f"{args[:2]} failed ({proc.returncode}): {proc.stdout[-2000:]}\n{proc.stderr[-2000:]}") + return proc.stdout.strip() + + +def until(test, seconds, message): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if test(): + return + time.sleep(0.1) + raise AssertionError(message) + + +class Fixture: + def __init__(self, root, name, binary, nonce, memory): + self.folder = root + self.nonce = nonce + self.container = command( + "docker", "run", "-d", "--network", "none", "--cgroupns", "host", + "--privileged", "--label", f"crg.memory-test={nonce}", "--name", f"crg-recovery-{nonce}-{name}", + "--memory", memory, "--memory-swap", memory, "--shm-size", "256m", + "-e", "POSTGRES_HOST_AUTH_METHOD=trust", + "-v", "/sys/fs/cgroup:/sys/fs/cgroup:rw", + "-v", f"{binary}:/usr/local/bin/crg:ro", "-v", f"{root}:/state:rw", + "postgres:16-bookworm", "-c", "shared_buffers=32MB", + ) + + def inspect(self): + meta = json.loads(command("docker", "inspect", self.container))[0] + assert meta["Id"] == self.container and meta["Config"]["Labels"]["crg.memory-test"] == self.nonce + return meta + + def group(self): + pid = self.inspect()["State"]["Pid"] + membership = Path(f"/proc/{pid}/cgroup").read_text().strip() + assert membership.startswith("0::/") and "\n" not in membership + group = Path("/sys/fs/cgroup") / membership[4:] + assert group.resolve() == group and group.name in (self.container, f"docker-{self.container}.scope") + return group + + def exec(self, *args, timeout=30): + return command("docker", "exec", self.container, *args, timeout=timeout) + + def wait_pg(self): + until( + lambda: subprocess.run(["docker", "exec", self.container, "pg_isready", "-U", "postgres"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 + and Path(f"/proc/{self.inspect()['State']['Pid']}/comm").read_text().strip() == "postgres", + 45, "PostgreSQL PID 1 did not become ready", + ) + + def config(self, value, interval=2, enabled=True, paused=False): + config = {"mode": "enforce", "resource_mode": "manual", "limits": {"memory_high": value}, + "interval_seconds": interval, "state_dir": "/state/runtime", "log_dir": "/state/logs", + "events_enabled": True} + if enabled: + config.update(memory_high_recovery=True, memory_high_recovery_paused=paused) + candidate = self.folder / "config.next" + candidate.write_text(json.dumps(config)) + candidate.replace(self.folder / "config.json") + + def start(self): + command("docker", "exec", "-d", self.container, "crg", "run", "--config", "/state/config.json") + + def reload(self): + return json.loads(self.exec("crg", "reload", "--config", "/state/config.json", + "--state-dir", "/state/runtime"))["request_id"] + + def status(self): + file = self.folder / "runtime/status.json" + return json.loads(file.read_bytes()) if file.exists() else {} + + def journal(self): + return json.loads((self.folder / "runtime/journal.json").read_bytes()) + + def high(self): + return (self.group_path / "memory.high").read_text().strip() + + def external_high(self, value): + assert self.group() == self.group_path + (self.group_path / "memory.high").write_text(str(value)) + assert self.high() == str(value) + + def wait_high(self, value, timeout=10): + until(lambda: self.high() == str(value), timeout, f"kernel memory.high did not reach {value}") + + def wait_reload(self, identifier): + until(lambda: self.status().get("configuration", {}).get("request_id") == identifier, 10, "reload not observed") + + def wait_reason(self, reason): + until(lambda: any(item["reason_code"] == reason for item in self.status().get("items", [])), + 10, f"missing reason {reason}") + + def wait_recovery(self, value): + until(lambda: any(row["reason"] == "memory_high_recovered" and row["expected"] == str(value) + for row in self.history()["memory_high_recovery"].get("events", [])), + 15, f"recovery for {value} was not durably finalized") + + def controls(self): + fields = ["cpu.max", "cpu.weight", "io.max", "io.weight", "memory.max", "memory.swap.max", "pids.max"] + return {field: (self.group_path / field).read_text().strip() for field in fields} + + def history(self): + return self.journal()["mutations"]["memory.high:"] + + def logs(self): + return [row for path in (self.folder / "logs").glob("crg-*.log") + for line in path.read_text().splitlines() if (row := json.loads(line)).get("event", "").startswith("memory_high_")] + + def remove(self): + self.inspect() + command("docker", "rm", "-f", self.container) + until(lambda: not self.group_path.exists(), 15, "fixture cgroup survived removal") + + def remove_pressure_file(self): + # Remove the checked fixture's tmpfs allocation from the host without + # spawning a process that would itself be throttled in the container. + pid = self.inspect()["State"]["Pid"] + assert self.group() == self.group_path and pid == self.inspect()["State"]["Pid"] + Path(f"/proc/{pid}/root/dev/shm/crg-pressure").unlink() + + +def pressure(group): + result = {"current": int((group / "memory.current").read_text())} + for file, keys in [("memory.events", ("high", "oom", "oom_kill")), ("memory.stat", ("pgscan", "pgsteal"))]: + parsed = dict(row.split() for row in (group / file).read_text().splitlines()) + result.update({key: int(parsed[key]) for key in keys}) + result["psi"] = (group / "memory.pressure").read_text().strip() + return result + + +def query_latency(fixture): + output = fixture.exec("pgbench", "-n", "-c", "2", "-T", "6", "-R", "30", "-f", "/state/query.sql", + "-U", "postgres", "postgres", timeout=25) + assert re.search(r"number of failed transactions: 0\b", output) + assert int(re.search(r"number of transactions actually processed: (\d+)", output)[1]) >= 50 + return output + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + assert platform.system() == "Linux" and os.geteuid() == 0 + assert os.environ.get("CRG_NATIVE_MEMORY_TEST") == "ephemeral-github-vm-only" + endpoint = json.loads(command("docker", "context", "inspect", "--format", "{{json .Endpoints.docker.Host}}")) + assert endpoint in ("unix:///var/run/docker.sock", "unix:///run/docker.sock") + binary = args.binary.resolve() + report = {"kernel": platform.release(), "binary_sha256": hashlib.sha256(binary.read_bytes()).hexdigest(), + "build": json.loads(command(binary, "build-info")), "checks": {}, "cleanup": []} + args.output.parent.mkdir(parents=True, exist_ok=True) + fixtures = [] + nonce = uuid.uuid4().hex[:12] + gib = 1024 ** 3 + mib = 1024 ** 2 + + def launch(folder, name, memory="40g"): + item = Fixture(folder, name, binary, nonce, memory) + fixtures.append(item) + item.group_path = item.group() + item.wait_pg() + return item + + temporary = tempfile.TemporaryDirectory(prefix="crg-memory-recovery-") + try: + command("docker", "pull", "postgres:16-bookworm", timeout=180) + report["postgres_image_id"] = command("docker", "image", "inspect", "--format", "{{.Id}}", "postgres:16-bookworm") + directory = temporary.name + dbs_dir, his_dir = Path(directory) / "dbs", Path(directory) / "hisdbs" + dbs_dir.mkdir() + his_dir.mkdir() + dbs = launch(dbs_dir, "dbs") + dbs.external_high(38 * gib) + dbs.config("30GiB", interval=60) + dbs.start() + dbs.wait_high(30 * gib) + controls = dbs.controls() + before = time.monotonic() + dbs.external_high("max") + dbs.wait_high(30 * gib, 63) + elapsed = time.monotonic() - before + assert elapsed <= 62 and dbs.controls() == controls + dbs.wait_recovery(30 * gib) + assert dbs.history()["original"] == str(38 * gib) + report["checks"]["dbs_30GiB_next_60s_check"] = {"elapsed_seconds": elapsed, "actual": dbs.high(), + "original": dbs.history()["original"], "other_controls_match": True} + + his = launch(his_dir, "hisdbs") + his.config("12GiB") + his.start() + his.wait_high(12 * gib) + first_generation = his.status().get("configuration", {}).get("generation", 1) + his.config("15GiB") + his.wait_reload(his.reload()) + his.wait_high(15 * gib) + assert his.status()["configuration"]["generation"] > first_generation + his.config("15GiB", paused=True) + his.wait_reload(his.reload()) + his.external_high("max") + his.wait_reason("memory_high_recovery_paused") + time.sleep(5) + assert his.high() == "max" and not his.history().get("conflict") + his.config("15GiB") + his.wait_reload(his.reload()) + his.wait_high(15 * gib) + his.wait_recovery(15 * gib) + report["checks"]["hisdbs_15GiB_reload_pause_resume"] = {"actual": his.high(), "paused_for_seconds": 5} + + his.config("96MiB", paused=True) + his.wait_reload(his.reload()) + his.wait_high(96 * mib) + his.external_high("max") + his.wait_reason("memory_high_recovery_paused") + his.exec("dd", "if=/dev/zero", "of=/dev/shm/crg-pressure", "bs=1M", "count=160") + (his.folder / "query.sql").write_text("SELECT sum(i) FROM generate_series(1,100) AS i;\n") + baseline = query_latency(his) + before_pressure = pressure(his.group_path) + assert before_pressure["current"] > 96 * mib + other = his.controls() + with ThreadPoolExecutor(max_workers=1) as pool: + during = pool.submit(query_latency, his) + his.config("96MiB") + his.wait_reload(his.reload()) + his.wait_high(96 * mib, 12) + pressured = during.result() + after_pressure = pressure(his.group_path) + assert after_pressure["oom_kill"] == before_pressure["oom_kill"] and his.controls() == other + assert after_pressure["high"] > before_pressure["high"], "workload did not experience reclaim pressure" + report["checks"]["above_high_reclaim_and_sql_latency"] = { + "actual": his.high(), "before": before_pressure, "after": after_pressure, + "sql_baseline": baseline, "sql_during_recovery": pressured, "other_controls_match": True, + } + his.remove_pressure_file() + his.wait_recovery(96 * mib) + his.external_high("max") + until(lambda: any(row["reason"] == "memory_high_recovery_backoff" + for row in his.history()["memory_high_recovery"]["events"]), + 10, "repeated drift was not held in the journal") + time.sleep(5) + assert his.high() == "max" and his.history()["conflict"] + report["checks"]["repeated_overwrite"] = {"actual": his.high(), "journal": his.history()} + + old_id, old_inode = his.container, his.group_path.stat().st_ino + old_identity = his.journal()["identity"] + his.remove() + fixtures.remove(his) + report["cleanup"].append({"name": "hisdbs-original", "absent": True}) + replacement = launch(his_dir, "hisdbs-new") + replacement.config("128MiB", enabled=False) + replacement.start() + replacement.wait_high(128 * mib) + assert replacement.container != old_id and replacement.group_path.stat().st_ino != old_inode + until(lambda: replacement.journal()["identity"] != old_identity, 5, "stale journal was reused") + archived = json.loads((his_dir / "runtime/journal.previous.json").read_bytes()) + assert archived["identity"] == old_identity and archived["mutations"]["memory.high:"]["conflict"] + replacement.external_high("max") + replacement.wait_reason("external_conflict") + assert replacement.high() == "max" + report["checks"]["replacement_id_and_legacy_default"] = {"new_identity": True, "old_journal_retained": True} + report["events"] = dbs.logs() + replacement.logs() + assert any(row["event"] == "memory_high_recovered" for row in report["events"]) + assert any(row["event"] == "memory_high_recovery_backoff" for row in report["events"]) + report["phase"] = "passed" + except BaseException as error: + report.update(phase="failed", error=str(error)) + report["last_status"] = {item.folder.name: item.status() for item in fixtures} + report["events"] = [event for item in fixtures for event in item.logs()] + raise + finally: + for item in fixtures: + try: + item.remove() + report["cleanup"].append({"name": item.folder.name, "absent": True}) + except Exception as error: + report["cleanup"].append({"name": item.folder.name, "error": str(error), "absent": False}) + report["phase"] = "failed" + temporary.cleanup() + args.output.write_text(json.dumps(report, indent=2) + "\n") + assert all(row["absent"] for row in report["cleanup"]) + + +if __name__ == "__main__": + main() diff --git a/tests/vendor-enforce-stage-checks.py b/tests/vendor-enforce-stage-checks.py index 652af2a..31475e5 100644 --- a/tests/vendor-enforce-stage-checks.py +++ b/tests/vendor-enforce-stage-checks.py @@ -181,8 +181,11 @@ def check(): self.assertEqual(observed, [4*n for n in range(30)]) def test_source_hash_alone_does_not_prove_required_workload_interface(self): - self.assertTrue(stage.tool_interfaces(ROOT/'tests', smoke=True)) - self.assertEqual({name: stage.digest(ROOT/'tests'/name) for name in stage.SMOKE_TOOLS}, stage.SMOKE_TOOLS) + # This historical stage requires its pinned sources. The maintained + # drivers under tests/ can change independently of that stage. + frozen = ROOT/'tests/manual-reference-full600-frozen/tests' + self.assertTrue(stage.tool_interfaces(frozen, smoke=True)) + self.assertEqual({name: stage.digest(frozen/name) for name in stage.SMOKE_TOOLS}, stage.SMOKE_TOOLS) with tempfile.TemporaryDirectory() as folder: # A legacy-shaped source can support the formal phase while # lacking the managed smoke and selected-role interfaces.