Skip to content

feat(iac): IaCPlan schema + plan-stale diagnostic (W-1 of 12) - #523

Merged
intel352 merged 29 commits into
mainfrom
feat/iac-plan-schema-diagnostic
May 4, 2026
Merged

intel352 merged 29 commits into
mainfrom
feat/iac-plan-schema-diagnostic

Conversation

@intel352

@intel352 intel352 commented May 3, 2026

Copy link
Copy Markdown
Contributor

Summary

W-1 of the 12-PR IaC root-cause + provider conformance plan series. Adds the IaCPlan.SchemaVersion + IaCPlan.InputSnapshot + PlanAction.ResolvedConfigHash + standalone DriftEntry type. Wires per-key plan-stale diagnostic into the persisted---plan apply path. Adds iac/inputsnapshot/ package (Compute + Snapshot + NewTolerantEnvProvider + preservedFingerprint sentinel + ComputeDrift + FormatStaleError + ErrEnvVarChanged sentinel). Warns when plan.json is not in .gitignore.

Plan reference: docs/plans/2026-05-03-iac-conformance-and-replace.md rev10 (commit on design/iac-conformance-and-replace branch). 9 adversarial-review cycles; user ratified Option C (W-9 includes ProviderPlanner; ADR 007).

What ships

6 commits in dependency order:

  • 324d856 — schema fields + DriftEntry type (T1.1)
  • 7c8c3ac — inputsnapshot.Compute / Snapshot / NewTolerantEnvProvider with preservedFingerprint sentinel (T1.2)
  • 4774c3b — wfctl infra plan writes InputSnapshot to plan.json (T1.3)
  • 295d354 — ComputePlan sets ResolvedConfigHash on create + update actions (T1.4)
  • b442dae — wfctl infra plan warns on missing .gitignore entry for plan.json (T1.6)
  • 43c8ced — typed ErrEnvVarChanged + ComputeDrift sentinel-honoring + persisted-plan diagnostic wiring (T1.5)

Out of scope (deferred to later PRs)

  • ApplyResult fields (InitialInputSnapshot, InputDriftReport, ReplaceIDMap) ship in W-3a/T3.0.4
  • In-process apply path postcondition wiring ships in W-3a/T3.1.5
  • wfctlhelpers.ApplyPlan body ships in W-3a/T3.1
  • Refresh-outputs (W-2), Replace action (W-3a/W-3b), JIT secret resolution (W-5), conformance suite (W-7)

Critical design constraints (rev1-rev10 history)

  • preservedFingerprint is UNEXPORTED; NewTolerantEnvProvider is the only sanctioned sentinel injector
  • ComputeDrift honors the sentinel via in-package access; tests reference unsetFingerprintPlaceholder constant (not the literal "(unset)" string) — closes cycle-7 brittle-test fix
  • Persisted-plan path uses OSEnvProvider (drift detection desired); in-process path will use NewTolerantEnvProvider in W-3a (preservation desired for sub-action env-cleanup case)
  • No ghost-stub of wfctlhelpers.ApplyPlan ships in this PR — the helper package lands in W-3a/T3.1

Test plan

  • GOWORK=off go test ./interfaces/... ./iac/inputsnapshot/... ./platform/... ./cmd/wfctl/... PASS
  • Manual: wfctl infra plan -o plan.json against a config with ${VAR} references; inspect plan.json contains input_snapshot map; .gitignore warning surfaces if entry absent
  • CI: standard test + lint pipeline green

🤖 Generated with Claude Code

Copilot AI review requested due to automatic review settings May 3, 2026 23:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds plan-format schema fields and input-fingerprint drift diagnostics to strengthen IaC plan/apply conformance, especially for the persisted wfctl infra apply --plan path.

Changes:

  • Extend interfaces.IaCPlan / interfaces.PlanAction with SchemaVersion, InputSnapshot, ResolvedConfigHash, and a shared DriftEntry type.
  • Introduce iac/inputsnapshot to compute env-var fingerprints, drift reports, and canonical “plan stale” diagnostics (including a typed sentinel error).
  • Wire snapshot capture into wfctl infra plan, drift checking into wfctl infra apply --plan, and add a heuristic warning when plan.json isn’t gitignored.

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
platform/differ.go Populate per-action ResolvedConfigHash on create/update plan actions.
platform/differ_test.go Add coverage asserting ResolvedConfigHash is set correctly per action.
interfaces/iac_state.go Add SchemaVersion, InputSnapshot, ResolvedConfigHash, and DriftEntry to public plan/state interfaces.
interfaces/iac_state_test.go JSON round-trip tests for the newly added schema fields.
iac/inputsnapshot/snapshot.go Implement fingerprint computation, OS/env providers, and tolerant sentinel handling.
iac/inputsnapshot/snapshot_test.go Tests for fingerprint format, determinism, unset handling, and sentinel pass-through.
iac/inputsnapshot/compute_drift.go Compute drift entries from plan/apply snapshots, honoring preservation sentinel.
iac/inputsnapshot/compute_drift_test.go Tests for drift detection and sentinel suppression behavior.
iac/inputsnapshot/diagnostic.go Canonical formatting for plan-stale drift diagnostics.
iac/inputsnapshot/errors.go Typed sentinel error for env-var drift (plan-stale) detection.
cmd/wfctl/infra_inputsnapshot.go Scan config for ${VAR}/$VAR refs and compute InputSnapshot for infra plans.
cmd/wfctl/infra.go Write snapshot/schema to plan output; warn on missing gitignore; enforce drift check during apply --plan.
cmd/wfctl/infra_plan_inputsnapshot_test.go Ensure wfctl infra plan -o persists InputSnapshot and SchemaVersion.
cmd/wfctl/infra_plan_gitignore.go Heuristic .gitignore coverage check for plan output warnings.
cmd/wfctl/infra_plan_gitignore_test.go Tests for warning emission/suppression based on .gitignore contents.
cmd/wfctl/infra_apply_plan_test.go Persisted-plan path test ensuring drift triggers typed error + per-key diagnostic and blocks provider.Apply.
Comments suppressed due to low confidence (1)

cmd/wfctl/infra.go:1104

  • SchemaVersion is written to plan.json, but the --plan apply path never validates it. To avoid older wfctl binaries accidentally applying a future/incompatible plan format, add a check after loading the plan (e.g., reject SchemaVersion > supported) before proceeding with drift/hash validation.
	if planFile != "" {
		plan, err := loadPlanFromFile(planFile)
		if err != nil {
			return err
		}
		// Validate that the plan is still current relative to the config.
		desired, err := parseInfraResourceSpecsForEnv(cfgFile, envName)
		if err != nil {
			return fmt.Errorf("parse infra resource specs: %w", err)
		}
		if plan.DesiredHash == "" {
			return fmt.Errorf("plan file has no hash — regenerate with: wfctl infra plan -o plan.json")
		}
		// Check the input-fingerprint drift first so the operator gets a
		// per-key diagnostic instead of the generic config-hash mismatch.
		// (Env-var changes are a strict subset of config-hash differences;
		// flagging them here yields the actionable message.) Names list is
		// derived from plan.InputSnapshot keys — no separate InputNames field.
		if len(plan.InputSnapshot) > 0 {
			names := make([]string, 0, len(plan.InputSnapshot))
			for k := range plan.InputSnapshot {
				names = append(names, k)
			}
			applySnap := inputsnapshot.Compute(names, inputsnapshot.OSEnvProvider)
			if drift := inputsnapshot.ComputeDrift(plan.InputSnapshot, applySnap); len(drift) > 0 {
				return fmt.Errorf("%w\n%s", inputsnapshot.ErrEnvVarChanged, inputsnapshot.FormatStaleError(drift))
			}
		}
		currentHash := desiredStateHash(desired)
		if plan.DesiredHash != currentHash {
			return fmt.Errorf("plan stale: config hash mismatch (run wfctl infra plan again)")
		}

Comment on lines +20 to +34
// Drift entries are sorted by Name for deterministic output. An empty drift
// report yields the singular line "plan stale: 0 input(s) changed since plan"
// — callers should avoid invoking the formatter when no drift exists.
func FormatStaleError(drift []interfaces.DriftEntry) string {
sorted := make([]interfaces.DriftEntry, len(drift))
copy(sorted, drift)
sort.Slice(sorted, func(i, j int) bool { return sorted[i].Name < sorted[j].Name })

var b strings.Builder
fmt.Fprintf(&b, "plan stale: %d input(s) changed since plan\n", len(sorted))
for _, d := range sorted {
fmt.Fprintf(&b, " %s: fingerprint %s (plan) → %s (apply)\n", d.Name, d.PlanFingerprint, d.ApplyFingerprint)
}
b.WriteString(" hint: ensure all env vars referenced by infra.yaml are exported to both Plan and Apply steps")
return b.String()
Comment thread iac/inputsnapshot/errors.go Outdated
// has a different fingerprint at apply time. Callers can match with
// errors.Is(err, ErrEnvVarChanged) to detect the plan-stale case
// independently of the human-readable per-key drift message.
var ErrEnvVarChanged = errors.New("plan stale: env-var changed since plan")
Comment on lines +44 to +70
// preservedFingerprint is a sentinel value indicating an env-var was set at
// plan time but is unset at apply time (sub-action cleanup is the canonical
// case). ComputeDrift (T1.5) skips drift detection for keys whose applySnap
// value is this sentinel. UNEXPORTED (rev6 — addresses cycle-5 Important on
// external-bypass channel): NewTolerantEnvProvider is the only sanctioned
// way to inject the sentinel; external callers cannot defeat drift detection.
//
// Cross-function contract:
// - Compute (this file, in-package) passes the sentinel through unhashed.
// - NewTolerantEnvProvider (this file) returns the sentinel for plan-time-set
// but apply-time-unset vars (in-package access to the constant).
// - ComputeDrift (compute_drift.go, T1.5, same package) honors the sentinel
// by skipping drift detection for that key.
const preservedFingerprint = "__plan_time_preserved__"

// NewTolerantEnvProvider returns an EnvProvider closure used by the
// in-process apply postcondition (T3.1.5). When a var was set at plan time
// (present in planSnapshot) but is now unset (sub-action cleanup), the
// closure returns the in-package preservedFingerprint sentinel so
// ComputeDrift suppresses the (false-positive) drift entry. For vars
// genuinely unset at both times, returns ("", false) → Compute drops the
// key from the resulting map.
//
// This is the ONLY sanctioned way to inject the preservation sentinel.
// Direct callers of Compute with a custom env-provider cannot construct
// the sentinel value because it is unexported.
func NewTolerantEnvProvider(planSnapshot map[string]string) func(name string) (string, bool) {
Comment thread cmd/wfctl/infra_plan_gitignore.go Outdated
Comment on lines +63 to +66
func gitignoreCovers(data []byte, base, planAbs, gitignoreDir string) bool {
ext := filepath.Ext(base)
scanner := bufio.NewScanner(strings.NewReader(string(data)))
for scanner.Scan() {
Comment thread interfaces/iac_state.go Outdated
Comment on lines +58 to +60
// InputSnapshot records every env var name read during ${VAR} substitution
// at plan time, mapped to a 16-hex-char (64-bit) sha256 prefix of the value.
// Apply re-computes inputs and prints diagnostic on mismatch.
@github-actions

ghost commented May 3, 2026 •

Copy link
Copy Markdown

⏱ Benchmark Results

✅ No significant performance regressions detected.

benchstat comparison (baseline → PR)
## benchstat: baseline → PR
baseline-bench.txt:245: parsing iteration count: invalid syntax
baseline-bench.txt:290613: parsing iteration count: invalid syntax
baseline-bench.txt:644485: parsing iteration count: invalid syntax
baseline-bench.txt:968099: parsing iteration count: invalid syntax
baseline-bench.txt:1277031: parsing iteration count: invalid syntax
baseline-bench.txt:1592872: parsing iteration count: invalid syntax
benchmark-results.txt:247: parsing iteration count: invalid syntax
benchmark-results.txt:324578: parsing iteration count: invalid syntax
benchmark-results.txt:614589: parsing iteration count: invalid syntax
benchmark-results.txt:936970: parsing iteration count: invalid syntax
benchmark-results.txt:1212041: parsing iteration count: invalid syntax
benchmark-results.txt:1501269: parsing iteration count: invalid syntax
goos: linux
goarch: amd64
pkg: github.com/GoCodeAlone/workflow/dynamic
cpu: AMD EPYC 7763 64-Core Processor                
                            │ baseline-bench.txt │        benchmark-results.txt        │
                            │       sec/op       │    sec/op      vs base              │
InterpreterCreation-4              3.779m ± 172%   3.353m ± 213%       ~ (p=0.485 n=6)
ComponentLoad-4                    3.707m ±   1%   3.609m ±   1%  -2.66% (p=0.002 n=6)
ComponentExecute-4                 1.952µ ±   1%   1.935µ ±   3%       ~ (p=0.288 n=6)
PoolContention/workers-1-4         1.103µ ±   4%   1.085µ ±   2%       ~ (p=0.087 n=6)
PoolContention/workers-2-4         1.099µ ±   5%   1.098µ ±   3%       ~ (p=0.853 n=6)
PoolContention/workers-4-4         1.101µ ±   1%   1.085µ ±   1%  -1.45% (p=0.006 n=6)
PoolContention/workers-8-4         1.101µ ±   1%   1.088µ ±   1%  -1.18% (p=0.002 n=6)
PoolContention/workers-16-4        1.120µ ±   3%   1.093µ ±   7%       ~ (p=0.065 n=6)
ComponentLifecycle-4               3.825m ±   1%   3.630m ±   1%  -5.12% (p=0.002 n=6)
SourceValidation-4                 2.431µ ±   0%   2.257µ ±   1%  -7.18% (p=0.002 n=6)
RegistryConcurrent-4               900.1n ±   3%   831.1n ±   3%  -7.67% (p=0.002 n=6)
LoaderLoadFromString-4             3.855m ±   1%   3.640m ±   1%  -5.57% (p=0.002 n=6)
geomean                            18.34µ          17.61µ         -3.98%

                            │ baseline-bench.txt │        benchmark-results.txt         │
                            │        B/op        │     B/op      vs base                │
InterpreterCreation-4               2.027Mi ± 0%   2.027Mi ± 0%       ~ (p=0.853 n=6)
ComponentLoad-4                     2.180Mi ± 0%   2.180Mi ± 0%       ~ (p=0.896 n=6)
ComponentExecute-4                  1.203Ki ± 0%   1.203Ki ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-1-4          1.203Ki ± 0%   1.203Ki ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-2-4          1.203Ki ± 0%   1.203Ki ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-4-4          1.203Ki ± 0%   1.203Ki ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-8-4          1.203Ki ± 0%   1.203Ki ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-16-4         1.203Ki ± 0%   1.203Ki ± 0%       ~ (p=1.000 n=6) ¹
ComponentLifecycle-4                2.183Mi ± 0%   2.183Mi ± 0%       ~ (p=0.331 n=6)
SourceValidation-4                  1.984Ki ± 0%   1.984Ki ± 0%       ~ (p=1.000 n=6) ¹
RegistryConcurrent-4                1.133Ki ± 0%   1.133Ki ± 0%       ~ (p=1.000 n=6) ¹
LoaderLoadFromString-4              2.182Mi ± 0%   2.182Mi ± 0%       ~ (p=0.907 n=6)
geomean                             15.25Ki        15.25Ki       -0.00%
¹ all samples are equal

                            │ baseline-bench.txt │        benchmark-results.txt        │
                            │     allocs/op      │  allocs/op   vs base                │
InterpreterCreation-4                15.68k ± 0%   15.68k ± 0%       ~ (p=1.000 n=6)
ComponentLoad-4                      18.02k ± 0%   18.02k ± 0%       ~ (p=1.000 n=6)
ComponentExecute-4                    25.00 ± 0%    25.00 ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-1-4            25.00 ± 0%    25.00 ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-2-4            25.00 ± 0%    25.00 ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-4-4            25.00 ± 0%    25.00 ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-8-4            25.00 ± 0%    25.00 ± 0%       ~ (p=1.000 n=6) ¹
PoolContention/workers-16-4           25.00 ± 0%    25.00 ± 0%       ~ (p=1.000 n=6) ¹
ComponentLifecycle-4                 18.07k ± 0%   18.07k ± 0%       ~ (p=1.000 n=6) ¹
SourceValidation-4                    32.00 ± 0%    32.00 ± 0%       ~ (p=1.000 n=6) ¹
RegistryConcurrent-4                  2.000 ± 0%    2.000 ± 0%       ~ (p=1.000 n=6) ¹
LoaderLoadFromString-4               18.06k ± 0%   18.06k ± 0%       ~ (p=1.000 n=6) ¹
geomean                               183.3         183.3       +0.00%
¹ all samples are equal

pkg: github.com/GoCodeAlone/workflow/middleware
                                  │ baseline-bench.txt │       benchmark-results.txt       │
                                  │       sec/op       │   sec/op     vs base              │
CircuitBreakerDetection-4                 287.2n ± 17%   285.4n ± 4%  -0.64% (p=0.022 n=6)
CircuitBreakerExecution_Success-4         21.52n ±  0%   21.52n ± 0%       ~ (p=0.974 n=6)
CircuitBreakerExecution_Failure-4         65.88n ±  1%   65.30n ± 0%  -0.87% (p=0.002 n=6)
geomean                                   74.12n         73.74n       -0.50%

                                  │ baseline-bench.txt │       benchmark-results.txt        │
                                  │        B/op        │    B/op     vs base                │
CircuitBreakerDetection-4                 144.0 ± 0%     144.0 ± 0%       ~ (p=1.000 n=6) ¹
CircuitBreakerExecution_Success-4         0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
CircuitBreakerExecution_Failure-4         0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
geomean                                              ²               +0.00%               ²
¹ all samples are equal
² summaries must be >0 to compute geomean

                                  │ baseline-bench.txt │       benchmark-results.txt        │
                                  │     allocs/op      │ allocs/op   vs base                │
CircuitBreakerDetection-4                 1.000 ± 0%     1.000 ± 0%       ~ (p=1.000 n=6) ¹
CircuitBreakerExecution_Success-4         0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
CircuitBreakerExecution_Failure-4         0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
geomean                                              ²               +0.00%               ²
¹ all samples are equal
² summaries must be >0 to compute geomean

pkg: github.com/GoCodeAlone/workflow/module
                                 │ baseline-bench.txt │       benchmark-results.txt        │
                                 │       sec/op       │    sec/op     vs base              │
JQTransform_Simple-4                     881.2n ± 26%   875.9n ± 33%       ~ (p=0.699 n=6)
JQTransform_ObjectConstruction-4         1.465µ ±  0%   1.444µ ±  1%  -1.40% (p=0.002 n=6)
JQTransform_ArraySelect-4                3.451µ ±  3%   3.329µ ±  1%  -3.52% (p=0.002 n=6)
JQTransform_Complex-4                    39.73µ ±  0%   38.76µ ±  0%  -2.43% (p=0.002 n=6)
JQTransform_Throughput-4                 1.819µ ±  2%   1.774µ ±  1%  -2.50% (p=0.002 n=6)
SSEPublishDelivery-4                     69.89n ±  5%   73.41n ±  1%  +5.04% (p=0.002 n=6)
geomean                                  1.680µ         1.664µ        -0.94%

                                 │ baseline-bench.txt │        benchmark-results.txt         │
                                 │        B/op        │     B/op      vs base                │
JQTransform_Simple-4                   1.273Ki ± 0%     1.273Ki ± 0%       ~ (p=1.000 n=6) ¹
JQTransform_ObjectConstruction-4       1.773Ki ± 0%     1.773Ki ± 0%       ~ (p=1.000 n=6) ¹
JQTransform_ArraySelect-4              2.625Ki ± 0%     2.625Ki ± 0%       ~ (p=1.000 n=6) ¹
JQTransform_Complex-4                  16.22Ki ± 0%     16.22Ki ± 0%       ~ (p=1.000 n=6) ¹
JQTransform_Throughput-4               1.984Ki ± 0%     1.984Ki ± 0%       ~ (p=1.000 n=6) ¹
SSEPublishDelivery-4                     0.000 ± 0%       0.000 ± 0%       ~ (p=1.000 n=6) ¹
geomean                                             ²                 +0.00%               ²
¹ all samples are equal
² summaries must be >0 to compute geomean

                                 │ baseline-bench.txt │       benchmark-results.txt        │
                                 │     allocs/op      │ allocs/op   vs base                │
JQTransform_Simple-4                     10.00 ± 0%     10.00 ± 0%       ~ (p=1.000 n=6) ¹
JQTransform_ObjectConstruction-4         15.00 ± 0%     15.00 ± 0%       ~ (p=1.000 n=6) ¹
JQTransform_ArraySelect-4                30.00 ± 0%     30.00 ± 0%       ~ (p=1.000 n=6) ¹
JQTransform_Complex-4                    324.0 ± 0%     324.0 ± 0%       ~ (p=1.000 n=6) ¹
JQTransform_Throughput-4                 17.00 ± 0%     17.00 ± 0%       ~ (p=1.000 n=6) ¹
SSEPublishDelivery-4                     0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
geomean                                             ²               +0.00%               ²
¹ all samples are equal
² summaries must be >0 to compute geomean

pkg: github.com/GoCodeAlone/workflow/schema
                                    │ baseline-bench.txt │       benchmark-results.txt       │
                                    │       sec/op       │   sec/op     vs base              │
SchemaValidation_Simple-4                   1.103µ ± 21%   1.113µ ± 1%       ~ (p=0.394 n=6)
SchemaValidation_AllFields-4                1.659µ ±  2%   1.661µ ± 2%       ~ (p=0.485 n=6)
SchemaValidation_FormatValidation-4         1.587µ ±  2%   1.576µ ± 2%       ~ (p=0.851 n=6)
SchemaValidation_ManySchemas-4              1.796µ ±  1%   1.825µ ± 3%       ~ (p=0.240 n=6)
geomean                                     1.511µ         1.518µ       +0.50%

                                    │ baseline-bench.txt │       benchmark-results.txt        │
                                    │        B/op        │    B/op     vs base                │
SchemaValidation_Simple-4                   0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
SchemaValidation_AllFields-4                0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
SchemaValidation_FormatValidation-4         0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
SchemaValidation_ManySchemas-4              0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
geomean                                                ²               +0.00%               ²
¹ all samples are equal
² summaries must be >0 to compute geomean

                                    │ baseline-bench.txt │       benchmark-results.txt        │
                                    │     allocs/op      │ allocs/op   vs base                │
SchemaValidation_Simple-4                   0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
SchemaValidation_AllFields-4                0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
SchemaValidation_FormatValidation-4         0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
SchemaValidation_ManySchemas-4              0.000 ± 0%     0.000 ± 0%       ~ (p=1.000 n=6) ¹
geomean                                                ²               +0.00%               ²
¹ all samples are equal
² summaries must be >0 to compute geomean

pkg: github.com/GoCodeAlone/workflow/store
                                   │ baseline-bench.txt │        benchmark-results.txt        │
                                   │       sec/op       │    sec/op     vs base               │
EventStoreAppend_InMemory-4                1.197µ ± 13%   1.216µ ± 14%        ~ (p=0.818 n=6)
EventStoreAppend_SQLite-4                  1.399m ±  4%   1.371m ±  8%        ~ (p=0.310 n=6)
GetTimeline_InMemory/events-10-4           13.66µ ±  4%   14.63µ ±  4%   +7.09% (p=0.004 n=6)
GetTimeline_InMemory/events-50-4           75.64µ ±  1%   63.40µ ± 10%  -16.18% (p=0.002 n=6)
GetTimeline_InMemory/events-100-4          133.1µ ± 17%   126.9µ ±  2%        ~ (p=1.000 n=6)
GetTimeline_InMemory/events-500-4          626.0µ ±  1%   655.7µ ±  1%   +4.74% (p=0.002 n=6)
GetTimeline_InMemory/events-1000-4         1.274m ±  0%   1.368m ±  1%   +7.37% (p=0.002 n=6)
GetTimeline_SQLite/events-10-4             108.5µ ±  1%   120.3µ ±  1%  +10.89% (p=0.002 n=6)
GetTimeline_SQLite/events-50-4             249.4µ ±  0%   270.4µ ±  1%   +8.41% (p=0.002 n=6)
GetTimeline_SQLite/events-100-4            419.4µ ±  1%   440.1µ ±  1%   +4.93% (p=0.002 n=6)
GetTimeline_SQLite/events-500-4            1.789m ±  1%   1.881m ±  1%   +5.16% (p=0.002 n=6)
GetTimeline_SQLite/events-1000-4           3.479m ±  1%   3.633m ±  1%   +4.42% (p=0.002 n=6)
geomean                                    220.2µ         225.4µ         +2.39%

                                   │ baseline-bench.txt │        benchmark-results.txt         │
                                   │        B/op        │     B/op      vs base                │
EventStoreAppend_InMemory-4                  800.5 ± 7%     778.0 ± 7%       ~ (p=0.677 n=6)
EventStoreAppend_SQLite-4                  1.982Ki ± 3%   1.986Ki ± 2%       ~ (p=0.197 n=6)
GetTimeline_InMemory/events-10-4           7.953Ki ± 0%   7.953Ki ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_InMemory/events-50-4           46.62Ki ± 0%   46.62Ki ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_InMemory/events-100-4          94.48Ki ± 0%   94.48Ki ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_InMemory/events-500-4          472.8Ki ± 0%   472.8Ki ± 0%       ~ (p=0.242 n=6)
GetTimeline_InMemory/events-1000-4         944.3Ki ± 0%   944.3Ki ± 0%       ~ (p=0.273 n=6)
GetTimeline_SQLite/events-10-4             16.74Ki ± 0%   16.74Ki ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_SQLite/events-50-4             87.14Ki ± 0%   87.14Ki ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_SQLite/events-100-4            175.4Ki ± 0%   175.4Ki ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_SQLite/events-500-4            846.1Ki ± 0%   846.1Ki ± 0%  +0.00% (p=0.002 n=6)
GetTimeline_SQLite/events-1000-4           1.639Mi ± 0%   1.639Mi ± 0%       ~ (p=0.485 n=6)
geomean                                    67.41Ki        67.26Ki       -0.22%
¹ all samples are equal

                                   │ baseline-bench.txt │        benchmark-results.txt        │
                                   │     allocs/op      │  allocs/op   vs base                │
EventStoreAppend_InMemory-4                  7.000 ± 0%    7.000 ± 0%       ~ (p=1.000 n=6) ¹
EventStoreAppend_SQLite-4                    53.00 ± 0%    53.00 ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_InMemory/events-10-4             125.0 ± 0%    125.0 ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_InMemory/events-50-4             653.0 ± 0%    653.0 ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_InMemory/events-100-4           1.306k ± 0%   1.306k ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_InMemory/events-500-4           6.514k ± 0%   6.514k ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_InMemory/events-1000-4          13.02k ± 0%   13.02k ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_SQLite/events-10-4               382.0 ± 0%    382.0 ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_SQLite/events-50-4              1.852k ± 0%   1.852k ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_SQLite/events-100-4             3.681k ± 0%   3.681k ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_SQLite/events-500-4             18.54k ± 0%   18.54k ± 0%       ~ (p=1.000 n=6) ¹
GetTimeline_SQLite/events-1000-4            37.29k ± 0%   37.29k ± 0%       ~ (p=1.000 n=6) ¹
geomean                                     1.162k        1.162k       +0.00%
¹ all samples are equal

Benchmarks run with go test -bench=. -benchmem -count=6.
Regressions ≥ 20% are flagged. Results compared via benchstat.

Jon Langevin and others added 5 commits May 3, 2026 19:58
…view)

Empty drift report previously rendered as a 2-line message (header + hint),
contradicting the doc comment that promised a singular header line. Gate
the hint on len(drift) > 0 so the empty case stays minimal as documented.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…r-facing prefix (Copilot review)

The sentinel was wrapped via fmt.Errorf("%w\n%s", ErrEnvVarChanged,
FormatStaleError(...)), so its "plan stale:" prefix duplicated the
formatter's own "plan stale: %d input(s)..." header. Reduce the sentinel
to a short machine-only marker; FormatStaleError remains the sole owner
of the human-facing prefix. Existing test assertions match
strings.Contains(err.Error(), "plan stale") via the formatter portion of
the wrapped error and continue to pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…boundary not security (Copilot review)

Previous comment claimed external callers "cannot defeat drift detection"
because the sentinel is unexported, but any caller can return the literal
string "__plan_time_preserved__" from a custom env-provider closure.
Update both the constant doc and NewTolerantEnvProvider doc to be honest:
the unexported boundary is API hygiene, not a security guarantee. Sentinel
value unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…Copilot review)

bufio.NewScanner over strings.NewReader(string(data)) made an extra copy
of the .gitignore contents; switch to bytes.NewReader(data) to scan the
slice directly. Also check scanner.Err() after the loop — oversized lines
(over bufio.MaxScanTokenSize) previously fell through silently as
"not covered". Conservative behavior: scan errors return false so an
operator-visible warning is emitted rather than silently letting plan.json
land in source control.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…ot review)

Comment said "every env var name read" but inputsnapshot.Compute and
OSEnvProvider intentionally omit unset vars from the resulting map. Make
the contract explicit: only set vars are fingerprinted; unset-at-plan +
unset-at-apply yields no drift entry by design.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.

Comment on lines +72 to +74
if strings.HasPrefix(line, "!") {
continue // negation rules — skip; conservative (warn even if a later rule re-includes)
}
Comment on lines +21 to +26
if val == preservedFingerprint {
// Sentinel from NewTolerantEnvProvider — pass through unhashed
// so ComputeDrift recognizes the preservation signal. (rev6 —
// unexported per cycle-5; in-package access only.)
out[name] = preservedFingerprint
continue
Comment thread iac/inputsnapshot/snapshot_test.go Outdated
Comment on lines +45 to +46
func TestNewTolerantEnvProvider_UnsetButPlanned_ReturnsSentinel(t *testing.T) {
os.Unsetenv("STAGING_PG_PASSWORD")
Comment thread interfaces/iac_state.go Outdated
Comment on lines +73 to +74
// ResolvedConfigHash is the SHA-256 of POST-substitution Resource.Config.
// Apply re-computes per-action and surfaces per-resource diagnostic on mismatch.
Jon Langevin and others added 4 commits May 3, 2026 20:08
…(Copilot review)

Heuristic skips !-prefixed negation rules and returns on first positive
match, so a "*.json" then "!plan.json" pattern silently passes. Acceptable
for a nudge-not-enforce warning; document the limitation in the negation
branch comment so future maintainers know the boundary. Full
last-matching-rule-wins semantics or git check-ignore shell-out are out
of scope for W-1.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…n impossible (Copilot review)

Previously a real env var whose value happened to equal
"__plan_time_preserved__" would be treated as a preservation sentinel and
silently suppress drift detection. Embed a NUL byte: POSIX exec(3) and
Windows CreateProcess both reject NUL inside env values, so no var the OS
delivers to a Go process can collide with the constant. In-package call
sites (Compute, NewTolerantEnvProvider, ComputeDrift) compare by string
equality against the constant — value change is transparent to them.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…v (Copilot review)

Previous test called os.Unsetenv("STAGING_PG_PASSWORD") without restoring
the prior value, leaking state across the test process and creating
order-dependence with any other test that reads STAGING_PG_PASSWORD.
Switch to a test-unique env var name (WFCTL_TEST_INPUTSNAPSHOT_UNSET_KEY)
the test never sets, so no cleanup is needed and there is no cross-test
state leak.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Comment said "SHA-256 of POST-substitution Resource.Config" but didn't
specify lower-case-hex encoding (no "sha256:" prefix) or the empty-string
short-circuit when the config map is empty (platform.ConfigHash behavior).
Make the contract explicit so downstream consumers don't guess.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 16 out of 16 changed files in this pull request and generated 5 comments.

Comment thread interfaces/iac_state_test.go Outdated
Comment on lines +38 to +49
func TestPlanAction_ResolvedConfigHashField(t *testing.T) {
a := PlanAction{Action: "create", ResolvedConfigHash: "sha256:abc"}
data, err := json.Marshal(a)
if err != nil {
t.Fatal(err)
}
var got PlanAction
if err := json.Unmarshal(data, &got); err != nil {
t.Fatal(err)
}
if got.ResolvedConfigHash != "sha256:abc" {
t.Errorf("ResolvedConfigHash: got %q", got.ResolvedConfigHash)
Comment thread cmd/wfctl/infra.go
Comment on lines +1086 to +1090
// Check the input-fingerprint drift first so the operator gets a
// per-key diagnostic instead of the generic config-hash mismatch.
// (Env-var changes are a strict subset of config-hash differences;
// flagging them here yields the actionable message.) Names list is
// derived from plan.InputSnapshot keys — no separate InputNames field.
Comment thread cmd/wfctl/infra_apply_plan_test.go Outdated
Comment on lines +20 to +26
// fingerprintForTest matches inputsnapshot.Compute's fingerprint format
// (16-hex-char sha256 prefix) so tests can construct expected plan-time
// snapshots without depending on the concrete env-provider closure.
func fingerprintForTest(value string) string {
sum := sha256.Sum256([]byte(value))
return hex.EncodeToString(sum[:])[:16]
}
Comment thread cmd/wfctl/infra_plan_gitignore.go Outdated
Comment on lines +105 to +111
// Scanner errors (e.g. line longer than bufio.MaxScanTokenSize) cause
// silent fall-through if not checked. Conservative: treat scan failure
// as not-covered, which surfaces a warning the operator can investigate
// rather than silently letting plan.json land in source control.
if err := scanner.Err(); err != nil {
return false
}
Comment on lines +44 to +54
func TestNewTolerantEnvProvider_UnsetButPlanned_ReturnsSentinel(t *testing.T) {
// Use a test-unique env-var name to avoid colliding with anything the
// process or other tests might rely on; we never set or unset it, so
// no cleanup is required and there is no cross-test state leak.
const key = "WFCTL_TEST_INPUTSNAPSHOT_UNSET_KEY"
plan := map[string]string{key: "deadbeef00000000"}
provider := NewTolerantEnvProvider(plan)
val, ok := provider(key)
if !ok || val != preservedFingerprint {
t.Errorf("expected (preservedFingerprint, true) for plan-time-set unset-now var; got (%q, %v)", val, ok)
}
Jon Langevin and others added 4 commits May 3, 2026 20:20
…ip (Copilot review)

Test fixture used "sha256:abc" but the actual format produced by
platform.ConfigHash is a lower-case 64-hex sha256 digest with no prefix.
Replace with a realistic 64-hex value so the test mirrors on-disk shape
and won't mislead a future validator/refactor.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
… (Copilot review)

runInfraPlan stamps SchemaVersion=1 on every emitted plan, but
runInfraApply was not validating it — a future bump (e.g. W-5 JIT plans)
would be silently mis-read by an older binary. Add an infraPlanSchemaVersion
constant + guard that rejects plans with schema_version > supported,
returning a clear "newer than this wfctl supports" message. Plans with
SchemaVersion=0 (predating the field) remain accepted for back-compat.
Test: TestInfraApplyConsumesPlan_FutureSchemaRejected.

Also reuse inputsnapshot.Compute in fingerprintForTest so the test always
exercises the production fingerprint algorithm — re-implementing
sha256+16-hex inline would silently drift if the scheme changed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…parse failure (Copilot review)

Previous round added a scanner.Err() check that returned false either way,
making the branch a no-op. Change the helper signature to (bool, error)
and have warnIfPlanNotGitignored emit a "could not scan ... for plan.json
coverage" stderr warning when the underlying bufio.Scanner fails (e.g. a
line over bufio.MaxScanTokenSize). The "not covered" warning is suppressed
on scan failure so the operator sees the parse error rather than a
potentially-misleading coverage warning. Test: TestGitignoreCovers_ScanError_Propagates.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…with cleanup (Copilot review)

Previous round used a unique env-var name and assumed it was unset, but a
hostile CI environment could pre-set it and silently flip the test result.
Explicitly Unsetenv at start, restore prior value (if any) via t.Cleanup
so the test cannot leak state across the process.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@intel352
intel352 requested a review from Copilot May 4, 2026 00:20

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated 2 comments.

Comment on lines +40 to +62
for {
gitignore := filepath.Join(dir, ".gitignore")
if data, err := os.ReadFile(gitignore); err == nil {
foundAny = true
ok, scanErr := gitignoreCovers(data, base, abs, dir)
if scanErr != nil {
// Surface parse failure to the operator (line over
// bufio.MaxScanTokenSize, etc.) rather than silently
// pretending the file is/isn't covered.
fmt.Fprintf(w, "warning: could not scan %s for %s coverage: %v\n", gitignore, base, scanErr)
scanFailed = true
}
if ok {
covered = true
break
}
}
parent := filepath.Dir(dir)
if parent == dir {
break // reached filesystem root
}
dir = parent
}
Comment thread interfaces/iac_state.go Outdated
Comment on lines +58 to +62
// InputSnapshot records every env var name read during ${VAR} substitution
// at plan time, fingerprinting only those that were SET (16-hex-char sha256
// prefix of the value). Unset vars are omitted from the map; their absence
// at apply time is therefore not flagged as drift. Apply re-computes inputs
// and prints diagnostic on mismatch.
Jon Langevin and others added 2 commits May 3, 2026 20:52
…iew)

Previous heuristic walked .gitignore files from the plan dir up to the
filesystem root, so an unrelated /tmp/.gitignore or $HOME/.gitignore
could shadow the real coverage check (or flake the not-covered tests).
Add findGitWorktreeRoot — pure stat-based discovery that walks up
looking for a .git entry (handles both git directories and git-worktree
pointer files). The walk now terminates at the worktree root so unrelated
ancestor .gitignore files are ignored, and outside any git worktree the
warning stays silent entirely. Tests updated to mark t.TempDir() as a
worktree (mkdir .git) where they expect the heuristic to activate;
TestPlan_NoGitWorktree_NoWarning added to cover the silent-when-untracked
path.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
… gap (Copilot review)

The InputSnapshot field comment claimed completeness ("env var names read
during ${VAR} substitution"), but the cmd/wfctl scanner that populates
the map intentionally does not apply top-level environments[env].envVars
defaults — that limitation was already documented at
collectInfraEnvVarRefs but not surfaced in the public interface
contract. Add a "Completeness caveat" note pointing at the scanner's
limitation so consumers don't assume the snapshot is exhaustive.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated 1 comment.

Comment on lines +22 to +30
func ComputeDrift(planSnap, applySnap map[string]string) []interfaces.DriftEntry {
var drift []interfaces.DriftEntry
for name, planFP := range planSnap {
applyFP, present := applySnap[name]
if !present {
drift = append(drift, interfaces.DriftEntry{
Name: name,
PlanFingerprint: planFP,
ApplyFingerprint: unsetFingerprintPlaceholder,
…rder (Copilot review)

Map iteration order in Go is randomized, so consumers that marshal /
log / compare the returned drift slice (now exposed via *StaleError.Drift)
would see non-deterministic output across runs. FormatStaleError already
sorts independently for its printed output; sort the structured slice
once at the source so all downstream consumers benefit. Test:
TestComputeDrift_ResultIsSortedByName.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated 1 comment.

Comment thread interfaces/iac_state.go
Comment on lines +80 to +90
// ResolvedConfigHash is the SHA-256 of POST-substitution Resource.Config,
// computed via platform.ConfigHash. Encoded as lower-case hex (no
// "sha256:" prefix); empty string when the config map is empty
// (platform.ConfigHash short-circuit).
//
// Currently populated by ComputePlan and persisted in plan.json so apply
// has the per-action hash available; the apply-time consumer that surfaces
// a per-resource diagnostic on mismatch is wired in a follow-up PR (W-3a/
// T3.1.5). Until then the field is observable via plan.json inspection but
// not yet enforced at apply.
ResolvedConfigHash string `json:"resolved_config_hash,omitempty"`
…pilot review)

Field is tagged json:",omitempty" so the empty-string case is dropped
from plan.json entirely rather than persisted as ""; consumers should
treat "key missing" and "value == empty string" as the same condition.
Comment now states this explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated 2 comments.

Comment thread iac/inputsnapshot/snapshot.go Outdated
// Compute returns a map of env-var name → 16-hex-char sha256 prefix of the value.
// Variables that aren't set (lookup returns ok=false) are omitted from the snapshot.
func Compute(varNames []string, lookup func(string) (string, bool)) map[string]string {
out := make(map[string]string)
Comment thread cmd/wfctl/infra_plan_gitignore.go Outdated
Comment on lines +144 to +148
// Relative path from .gitignore dir, e.g. "cmd/wfctl/plan.json".
if rel, err := filepath.Rel(gitignoreDir, planAbs); err == nil {
if anchored == rel || anchored == filepath.ToSlash(rel) {
return true, nil
}
…stants (Copilot review)

Two micro-optimizations:
- inputsnapshot.Compute now allocates with len(varNames) capacity hint
  to avoid grow-resize cycles when many env vars are referenced.
- gitignoreCovers hoists filepath.Rel/ToSlash and the base-derived
  pattern strings (starExt, doubleStarExt, doubleStarBase) out of the
  per-line scan loop — they're constant for the whole .gitignore file.
  No behavior change; less per-line allocation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

ghost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 17 out of 17 changed files in this pull request and generated no new comments.

@intel352
intel352 merged commit 48f7a0c into main May 4, 2026
@intel352
intel352 deleted the feat/iac-plan-schema-diagnostic branch May 4, 2026 01:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants