Skip to content

refactor(state,mpc,api): remove dead storage, planner and backup leftovers - #1456

Merged
frahlg merged 3 commits into
masterfrom
refactor/remove-dead-leftovers
Sep 27, 2026
Merged

frahlg merged 3 commits into
masterfrom
refactor/remove-dead-leftovers

Conversation

@frahlg

@frahlg frahlg commented Sep 27, 2026

Copy link
Copy Markdown
Member

Round 2 of the multi-agent hardening and refactor review. A skeptic confirmed each finding against the code, and a second reviewer checked this diff and ran its tests. Removals follow the owner decisions of 2026-09-26.

Changes

  • Docs: fix driver-catalog count and host-api header #49 handleDriverDraftKeep (go/internal/api/api_driver_draft.go) now blocks on driverUpdateMu, like expireDraft, and removes the record before the saved original. An expiry already in flight finishes first, and Keep then answers 409 instead of 200 "kept" for a draft that was reverted.
    • Test: TestKeepWaitsForAnExpiryAlreadyInFlight in go/internal/api/api_driver_draft_test.go. Checked that it fails without the fix ("keep answered 200 ... while an expiry held the update lock") and passes with it, including -race -count=3.
  • drivers: port Growatt hybrid inverter driver (read-only) #20 maintainHistory runs only the plain SQLite stages; the plain flag and MaintainHistory are gone. Removed: RolloffToParquet/rolloffSamples, RolloffDiagnosticsToParquet/writeParquetDiagDay, MaintainAggregateHistory and the archive-job files, CompactLegacyHistory, PruneHistorySamples/retainSampleHistory, PruneColdParquet, PruneDiagnosticsParquet, Store.Prune/pruneTier/pruneChunk, LoadSeriesFromParquet, historyArchiveTurn/archiveTurnKey/maintenanceBudgetSpent and the retention constants. rolloffLoop lost its unused retentionDays closure. Kept: the Parquet readers, walkBucketFile and the plain-path helpers. The retired state.cold_retention_days key already logs a warning at startup, so no stored setting is left steering a site.
    • Test: Tests moved to MaintainPlainHistory or to hand-written legacy Parquet day files: history_maintenance_pause_test.go, api_history_storage_test.go, api_series_test.go, diagnostics_test.go (TestDiagnosticsParquetReaders) and archive_test.go. Archive-only tests were deleted. go test ./internal/state …
  • mpc: discharge in self-consumption instead of holding SoC forever #40 Replaced s.hot/hotPath with s.history. Removed openHotHistory, closeOpenedHistory, the dead s.hot != s.history branches (store.go Close, cost.go history_hot query), hotWriteMu (RecordHistory now uses historyWriteMu), forceRotate, heldBytes, RotateHistory, hotFileInfo, loadHotHistory/loadHotSeries, internHot*, tickTimestamp, the merge/downsample helpers and historyWriter.maintainHistory. checkpointLiveHistory is now a direct call to CheckpointHistory.
    • Test: The existing writer, OOM and storage-recovery tests were updated and pass (go test ./internal/state).
  • control: slew from actual battery power, not stale command #41 Removed ImportedHistoryFiles and the importedHistory plumbing in backup.Create/collectSources, the unused coldDir parameter of legacyHistoryIdle, and the test-only backup.Restore. Fixed the RestoreContents comment that referred to Restore.
    • Test: All round-trip tests (archive, dashboard, aggregate, configuration, workspace, derived-files, price and cmd/ftw forecast_learning_backup) now use RestoreContents through a restoreFresh helper. go test ./internal/backup ./cmd/ftw passes.
  • Drivers: port Deye SUN-SG hybrid inverter to Lua v2.1 host #29 Removed RecourseOptimizer/MultistageOptimizer, OptimizeRecourse/OptimizeMultistage, MultistageOptimizerConfig, the scenario block, UnixTransport, AutoTransport, requiredOptimizerFeature, the Health methods on transport and ExternalOptimizer, shadow_evaluator.go, and Plan/Diagnostic RecourseShadow/ShadowEvaluation. ExternalOptimizerConfig is now Command, Timeout and IdleTimeout. The solver settings are constants with the same values (HIGHS, auto, gap 0.005, CVaR alpha 0.9, weight 0, scenario_policy shared), so the request sent to the worker does not change. Kept: the Energyplan process transport, EnergyplanOptimizer.Health and the Core DP shadow. Old stored diagnostics that contain the removed keys still decode.
    • Test: external_optimizer_test.go and optimizer_transport_test.go keep the process-transport cases. The shadow_evaluator and units/consistency tests for removed types were deleted. go test ./internal/mpc ./internal/units passes.
  • Fix 5 P1 bugs from Codex review #47 Removed: Service.PVNameplateW/LoadMaxW and the hard-coded zeros in main.go, clampForecastPV, capSlotsPVToNameplate, capPlanPVToNameplate, Plan.pv_nameplate_w/load_max_w, forecast.Service.ACLimitW, clampPVToNameplate, ClampForecasts, the uncalled forecast.Service.nameplateW, the load rain-check (rainCheckLoadSlots, recentDailyLoadWh, forecastLoadWh and constants), applyPVDownsideToSlots, selectPlannerPVW, lookupPV and UpdateCapacity. Also removed the no-op caps in web/plan.js. The NaN/negative-to-0 load floor is kept in one sanitizer, sanitizeLoadW.
    • Test: load_bounds_test.go covers sanitizeLoadW/sanitizeSlotLoads. Tests now call applyPVDownsidePerSlot, selectPlannerPVWithWeight and lookupPVInput. go test ./internal/mpc ./internal/forecast and npm test (639 pass) are green.
  • Test: add HA bridge nil-safety and diagnostic method tests #48 Both handshake mismatch errors now say "the bundled Energyplan worker does not match this Core; run ftw update or reinstall this release" instead of pointing to the Update Center. Dropped the ModuleDir/PYTHONPATH env for the compiled binaries (Energyplan and forecast_rust). Fixed stale comments: CVXPY, Python shadow, sidecar update controls, and the MaxExportW "Startup-only" note (a reload now refreshes it). Also rewrote two comments in mpc.go and service.go that still described scenarios being sent to the worker.
    • Test: TestHandshakeMismatchTellsOperatorWhatToDo (optimizer_transport_test.go) checks each error for "ftw update" and for no "Update Center"; it passes.

Evidence

All commands run from go/ with GOTMPDIR=/home/fredde/.cache/go-tmp and the scratchpad Go toolchain (absolute path, since PATH exports were refused by the worktree guard).

  • gofmt -l on the changed non-test Go files: clean. Seven untouched test files show up as unformatted, but that predates this change.
  • go build ./...: PASS
  • go vet ./cmd/ftw ./internal/api ./internal/backup ./internal/energyforecast ./internal/forecast ./internal/mpc ./internal/state ./internal/units: PASS
  • go test -count=1 for those same packages: all PASS except one test in internal/api, TestNewHistoryBlocksImageOnlyDowngrade, which failed with "github releases list 403: API rate limit exceeded". Its helper newCheckerAgainstOptions leaves selfupdate ReleasesURL on the real api.github.com, so it depends on the network and is unrelated to this change (selfupdate is untouched).
  • go test -count=1 -skip TestNewHistoryBlocksImageOnlyDowngrade ./internal/api: PASS
  • go test -count=1 ./cmd/ftw: PASS
  • go test -race -count=3 -run 'Draft|Keep|Expiry' ./internal/api: PASS
  • Checked the regression test fails without the fix: removing the lock and restoring the old remove order makes TestKeepWaitsForAnExpiryAlreadyInFlight fail as expected. The fix was then restored.
  • FTW_E2E=1 go test ./test/e2e -count=1 -timeout 300s: PASS (28s)
  • LANG=C LC_ALL=C npm test: PASS (639 tests, 0 fail)

Review

I found no blocker or should-fix; the three nits are optional. Each removal is unreachable in production and every reference to it is gone. #49 fixes the root cause.

#49 (hardening): Keep now takes driverUpdateMu with a blocking Lock, the same way expireDraft does, and removes the record before the original. An expiry already in flight therefore finishes first, and Keep then answers 409 instead of a false 200 "kept". The new test fails without the fix and passes with it, including under -race. There is no deadlock: Keep is only an HTTP handler, and every other holder of the lock is either TryLock or expireDraft.

#20/#40/#41 (storage): In production rolloffLoop still calls only MaintainPlainHistory. The stage list, the per-stage budget and the pending/failed classification match the old plain branch exactly: maintenanceBudgetSpent reduced to stageErr != nil for these stages. s.hot was always an alias of s.history, so the removed branches in cost.go and store.go were dead. checkpointLiveHistory was a direct call to CheckpointHistory. RecordHistory, now under historyWriteMu, is test-only. ImportedHistoryFiles always returned an empty map. ftw-backup already used RestoreContents. …

🤖 Generated with Claude Code

https://claude.ai/code/session_01MuerPFZFG88kgu8sWVHeq7

…overs

- #49 Keep on a driver draft now takes the driver update lock and removes
  the record before the saved original, so an expiry already in flight
  finishes first and Keep answers 409 instead of "kept" for a reverted draft.
- #20 History maintenance runs only the plain SQLite stages. Remove the
  Parquet archive pipeline (rolloff, aggregate/sample archive, legacy
  compaction, cold/diagnostic Parquet pruning, Store.Prune) and the unused
  retentionDays closure of rolloffLoop; keep the Parquet readers.
- #40 Drop the hot-history alias (s.hot, hotPath, hotWriteMu), dead
  hot-only branches and readers, forceRotate, heldBytes, RotateHistory and
  the test-only historyWriter.maintainHistory.
- #41 Remove the always-empty ImportedHistoryFiles filter, the unused
  coldDir parameter of legacyHistoryIdle and the test-only backup.Restore;
  round-trip tests now use RestoreContents.
- #29 Remove the recourse/multistage challenger, unix and auto transports,
  transport Health and the stateful shadow evaluator. The worker request
  keeps the same solver settings as constants; the Energyplan process
  transport and Core DP shadow are unchanged.
- #47 Remove the always-zero PV nameplate and load caps (Service fields,
  Plan.pv_nameplate_w/load_max_w, forecast ACLimitW/ClampForecasts and
  their web chart caps), the load rain-check and test-only wrappers. A
  single sanitiser still maps NaN or negative load to 0 W.
- #48 Handshake errors now say the bundled Energyplan worker does not match
  Core and to run `ftw update` or reinstall. Drop PYTHONPATH and fix stale
  Update Center, CVXPY, Python shadow and scenario comments.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MuerPFZFG88kgu8sWVHeq7
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-27T06:37:08.773056Z 6afdc8e PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

frahlg and others added 2 commits September 27, 2026 08:39
The shared PV scenarios in buildRequest were reachable only by calling
ExternalOptimizer directly with a risk margin; production runs through
EnergyplanOptimizer, which applies the margin to the slots and zeroes it
before the request. Removing that dead block left the native contract
test asking for three scenarios. It now checks that a margin never
builds a scenario model.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MuerPFZFG88kgu8sWVHeq7
…d-leftovers

# Conflicts:
#	go/internal/mpc/service.go
@frahlg
frahlg merged commit 3ffe9ac into master Sep 27, 2026
16 checks passed
@frahlg
frahlg deleted the refactor/remove-dead-leftovers branch September 27, 2026 07:08
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.

1 participant