Repository navigation
Record each upgrade run in the store (#9432) - #9493
Conversation
| # LocalSystem already has full control through the root. Any other account gets Modify on this one file, so the service can | ||
| # delete it. The grant goes on the temp file because a move keeps a file's own DACL. | ||
| if (-not [string]::IsNullOrWhiteSpace($serviceAccount) -and $serviceAccount -notmatch '^(NT AUTHORITY\\SYSTEM|LocalSystem)$') { | ||
| $grantOutput = & icacls.exe $temp /grant:r "${serviceAccount}:(M)" 2>&1 |
There was a problem hiding this comment.
upgrade-run.json's permissions do not fit this script's install-tree rules. Depending on where the run stops, the file either blocks the documented re-run or can never be removed by the service.
The service runs as NT SERVICE\<name> and never as LocalSystem (install-darling.ps1:38), so this /grant:r (M) fires on every real run. upgrade-run.json is not on Get-DarlingServiceWrittenNames (:400). The pre-lock walk (Get-UntrustedWriteGrantees, :251) trusts the service SID as a write grantee only on paths Test-DarlingServiceWrittenPath accepts. Lock-DarlingInstallTree resets explicit grants on any other root file (:2730–2745 region, the /reset branch).
Two outcomes follow:
- A Fail before the lock blocks the re-run. Take the stop-guard refusal at
:4764or the stop timeout at:4735. Both happen after the in_progress write (:4698) and before the lock (:4792). The first write here is aMove, so the explicit Modify ACE stays. Thefinallyrewrite goes throughFile.Replace, which keeps the replaced file's DACL, so the ACE survives that too. The service is now stopped and cannot delete the failed file. The operator follows the message ("close these and re-run (safe…)"). The pre-lock check at:4340then listsNT SERVICE\<name> on …\upgrade-run.jsonand refuses with "This install directory is already writable by ordinary users… Nothing was stopped or copied." The only way past it is-AcceptWritableExtraction. install-darling.ps1's step-1a check has the same shape. - A run that reaches the lock leaves a file the service cannot remove. The lock
/resets the in_progress file and strips the grant. Every later write (:4986, thefinally,-MarkVerified) goes throughFile.Replace. Win32ReplaceFilekeeps the replaced file's DACL, so the grant on the temp file is dropped. The comment above says "a move keeps a file's own DACL", which is true only for the firstMove. After that the service has RX on the root and no DELETE on the file. Every verified or failed pickup becomesRecordedNotRemoved, and the file stays for good. That contradicts the PR's "the file is removed once the run is verified or failed".
A possible fix: put upgrade-run.json on the shared Get-DarlingServiceWrittenNames.Files list. It must stay byte-identical in install-darling.ps1. Then the lock grants it and the pre-lock walk trusts it. Or drop the service-side delete and let the next run overwrite the file. No test exercises this: DarlingUpgradeRunRecordTests always passes $serviceAccount = '', so the icacls branch and the Replace-keeps-DACL behaviour never run.
| INSERT INTO collect.upgrade_runs | ||
| (run_id, state, tool_version, target_build, started_at, ended_at, exit_code, stop_check, rollback_folder, first_error, verified_at, recorded_at, updated_at) | ||
| VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $12) | ||
| ON CONFLICT (run_id) DO UPDATE SET |
There was a problem hiding this comment.
Non-blocking: the upsert overwrites state with no ordering guard, so an older copy of the same run's file can move the row backwards, for example failed or verified back to in_progress.
One way it happens: the backup at upgrade-darling.ps1:4823 copies every root file, and that includes this run's in_progress upgrade-run.json (written at :4698, before the backup). A manual restore from _rollback_* puts that file back. The next pickup then records the run as in_progress again, and the file stays for up to 7 days. Two possible fixes: a WHERE on the DO UPDATE that refuses to step back from a terminal state, or leaving upgrade-run.json out of the backup.
There was a problem hiding this comment.
Verdict: CHANGES REQUESTED
Claims
- VERIFIED — The script never opens a PostgreSQL connection and writes
upgrade-run.jsonbeside the install — upgrade-darling.ps1:4008-4154; no driver is referenced. - VERIFIED — The in_progress write happens before the service is stopped — upgrade-darling.ps1:4698 precedes
Stop-Serviceat :4733. - VERIFIED — The
finallyrewrites the file with end time, exit code, stop check, rollback folder, first error and state — upgrade-darling.ps1finallyhunk →Close-DarlingUpgradeRun;Failcaptures the first error at :196. - VERIFIED —
-MarkVerifiedcannot be combined with-Check/-PruneOnly/-ListRollbacksand leaves a failed or unfinished run alone — :4165 andSet-DarlingUpgradeRunVerified; covered byMarkVerified_RewritesASucceededRun_ButNotAFailedOrUnfinishedOne_AndHoldsNoSecret. - VERIFIED — Every write goes to a temp file and then moves over the old file, and leaves no temp file behind —
Write-DarlingUpgradeRunFile:4066-4096;AWriteThatFails_LeavesNoTempFile_AndTheOldFileUntouched. - VERIFIED — The pickup runs at start after the migrations and on the five-minute pass on its own stamp, with the alert engine off too — DarlingWorker.Collection.cs:157; DarlingWorker.Passes.cs:463 sits outside the
_selfAlertsgate; DarlingWorker.UpgradeRun.cs:96. - VERIFIED — One row per run id —
ON CONFLICT (run_id) DO UPDATEat UpgradeRuns.cs:91;ThreePickups_InProgressSucceededVerified_GiveOneRowWithEachStateSeen_AndTheFileGoesAtVerified. - VERIFIED — A malformed file warns once per content and stays; a file over 64 KB is not read; a store failure never fails a start —
WarnOnce/HashandMaxFileBytesin UpgradeRuns.cs; the catch inTryRecordUpgradeRunAsync;AMalformedFile_WarnsOncePerContent_AndStaysInPlace_AndAnOldInProgressFileGoes. - VERIFIED — Rows are kept 400 days, the same as the other store self-metric series —
RetentionDays = StoreSelfMetrics.RetentionDays(StoreSelfMetrics.cs:158 = 400). - VERIFIED — Store version 312 is wired through a new table, a csv row, a probe sentinel, a top rung, the GetBoolean list, the gate test and a rewind artifact — StorageVersion.cs, PgMigrations.cs:4098, ViewerDataService.cs:1678/1697/1725/1958, store-tables.csv, RungRewindArtifacts.cs:1012, ViewerDataServiceTests.
- VERIFIED — The fix sets the timestamp Kind to Unspecified for
recorded_at/updated_at/the retention cutoff — UpgradeRuns.csRecordAsyncSpecifyKind(nowUtc, Unspecified). - VERIFIED — Lite has no upgrade tool of this kind — no Lite counterpart of upgrade-darling.ps1 or
collect.upgrade_runsexists. - REFUTED — "The file is removed once the run is
verifiedorfailed" — on a run that reachesLock-DarlingInstallTree(:4792), the lock/resets the file's explicit grant. Every later write goes throughFile.Replace, which keeps the replaced file's DACL. The service (NT SERVICE\<name>, RX on the root) therefore cannot delete the file, and each pickup endsRecordedNotRemoved. See the inline comment on :4080. - REFUTED — "A file that cannot be written is a warning. The upgrade goes on." (taken as a claim that the record never gets in the upgrade's way) — a Fail before the lock leaves the file with an explicit Modify ACE for the service account. That account is not trusted on this path by
Get-UntrustedWriteGrantees(:251, viaTest-DarlingServiceWrittenPath). The documented "close these and re-run" is then refused at :4340 as "already writable by ordinary users". - UNVERIFIED — Revert proof (a plain insert fails only the three-pickup test) — needs a live Postgres and a rebuild.
- UNVERIFIED — 285 tests passed, the Release build succeeded, and the gate Guard lines were green — needs a build and a live store.
Riskiest lines
- Darling/tools/upgrade-darling.ps1:4080 — the icacls Modify grant on a root file that the lock and the pre-lock walk do not know about: it either blocks a re-run or is silently stripped — UNCOVERED (every
DarlingUpgradeRunRecordTestscall passes$serviceAccount = '') - Darling/tools/upgrade-darling.ps1:4085 —
File.Replacekeeps the destination's DACL, so the temp file's grant never reaches the final file after the first write — UNCOVERED - Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs:91 — an unconditional state overwrite, so an older file (for example one restored from a
_rollback_*backup) moves a terminal row back toin_progress— UNCOVERED (ThreePickups_…only tests forward transitions)
Traps near this diff
- "Lite and Darling ship in parity (CONTRIBUTING's two-store rule): a fix to one SKU's reader, tool, alert or description without the counterpart's is a finding, not a nit" — does not apply — this is a Darling-only store table and a Darling-only upgrade script; Lite has no counterpart of Darling/tools/upgrade-darling.ps1 or of the PG store's
collect.*schema. - "A test that reads the clock twice measures the CI scheduler" — does not apply — UpgradeRunPickupTests.cs passes one
nowanchor to each pickup, and the 7-day staleness case is offset by 8 days (AddDays(-8)), far from the boundary. - "A test that encodes the lie … Ask what defect a test would fail ON." — does not apply —
DarlingUpgradeRunRecordTestsruns the extracted functions and asserts the file's contents, so it fails on a wrong state or field. It does not reach the ACL defect above, which is why those lines are listed as UNCOVERED, not as covered. - "Ruling (#5833): tests are load-bearing … never answer a trap with a test that reads source text" — does not apply — the new tests extract the functions and run them under PowerShell (DarlingUpgradeRunRecordTests.cs
Run); they assert behaviour, not spelling.
Divergence (blind read vs PR body)
- The body says the service removes the file at verified or failed, and the script comment says "a move keeps a file's own DACL". The diff grants Modify only on the temp file, and every write after the first goes through
File.Replace, which keeps the old file's DACL. The lock at :4792 also strips the first grant, becauseupgrade-run.jsonis not onGet-DarlingServiceWrittenNames. In the normal flow the removal the body describes cannot happen. In the early-Fail flow the surviving grant makes the next run's pre-lock check refuse. The body does not mention how the file interacts with the install-tree lock or the pre-lock walk. - The body does not say that the rollback backup (:4823) copies this run's in_progress file. A restore from that backup moves the row back (non-blocking; inline comment on UpgradeRuns.cs:91).
Reviewer checklist
- On Windows with the default
NT SERVICE\<name>account: start an upgrade, hold a process under the install tree so the stop guard refuses, then re-run the upgrade. Confirm whether the pre-lock check listsupgrade-run.json. - On Windows: complete an upgrade, run
-MarkVerified, and wait one pass. Checkicacls upgrade-run.jsonand whether the service log shows the "could not be removed" warning. - Run
UpgradeRunPickupTestsagainst a liveDARLING_TEST_PGandDarlingUpgradeRunRecordTestson a Windows runner.
There was a problem hiding this comment.
Verdict: LGTM
Claims
- VERIFIED — The upsert never steps a run row back —
UpgradeRuns.UpsertSqlnow hasWHERE rank(EXCLUDED.state) >= rank(r.state) RETURNING r.state, with in_progress=0, succeeded/failed=1 and verified=2;RecordAsyncreturnsExecuteScalarAsync(...) is not null. - VERIFIED — A file behind the stored row is treated as stale and removed —
UpgradeRunPickup.PickUpAsyncsetsfinished = !recorded || ..., and the outcome doc comment was updated to match. - VERIFIED —
upgrade-run.jsonis on the service-written list in both scripts —Files = @('darling.json','upgrade-run.json')ininstall-darling.ps1:365andupgrade-darling.ps1:405. The two copies are identical. - VERIFIED — The
Get-DarlingBackupFileFindingNameschange keepsupgrade-run.jsonfrom being read as a config backup — it now testsBackupPrefixinstead of-eq 'darling.json'in both scripts. - UNVERIFIED — The service keeps Modify on the run file through the lock and a later rewrite — this needs a Windows NTFS ACL run.
AfterTheInstallTreeLock_AndARewrite_TheServiceStillHoldsModifyOnTheRunFileandTheServicesGrantOnTheRunFile_IsNotAStrangersGrant_ToThePreLockWalkskip off Windows. - UNVERIFIED — The pickup tests need a live PostgreSQL (
AnOlderCopyOfTheRunFile_NeverMovesAFinishedRowBack_AndIsRemovedskips withoutBaseConnectionString).
Riskiest lines
- Darling/PerformanceMonitor.Darling.Storage/UpgradeRuns.cs:105 — the state-rank guard in the upsert's
WHEREclause — covered byAnOlderCopyOfTheRunFile_NeverMovesAFinishedRowBack_AndIsRemoved, which covers verified→in_progress, failed→in_progress, and a forward in_progress→succeeded. - Darling/tools/upgrade-darling.ps1:405 and Darling/tools/install-darling.ps1:365 — the run file is added to the service-written list, so the lock now makes the service its owner — covered by
AfterTheInstallTreeLock_AndARewrite_TheServiceStillHoldsModifyOnTheRunFile(Windows only) andTheServicesGrantOnTheRunFile_IsNotAStrangersGrant_ToThePreLockWalk(Windows only). - Darling/tools/upgrade-darling.ps1:1384 — the backup-name filter changed from an exact
darling.jsonmatch to a prefix test — UNCOVERED. A newupgrade-run.jsonfinding must not be handled as a config backup, and no test targets that path.
Traps near this diff
- "Our wrong test is a bug we introduced, never a flake" — does not apply. The new tests are behaviour tests and add no quarantine line. The follow-up commits c725b87 and 4ffb333 fix a broken comment and unescaped backslashes in the C# test strings, which would have been a build or pwsh error.
- "Two copies of one definition pinned EQUAL to each other fail only after BOTH have drifted" — does not apply. The two scripts' lists are edited in the same commit, and the comment says they are kept identical.
- "Lite and Darling ship in parity" — does not apply. All of the change is in Darling, because the upgrade run record has no Lite counterpart.
Divergence (blind read vs PR body)
None found on the claims graded above. This follow-up covers three commits (e2773b7, c725b87, 4ffb333). The merge commit 12364ae is not the author's change, and I did not review it.
Reviewer checklist
- Run the two Windows ACL tests on a real Windows host.
- Run the pickup test against a live PostgreSQL.
- Confirm that an older install whose
install-darling.ps1does not listupgrade-run.jsonstill lets the service delete the file. The Write-DarlingUpgradeRunFile comment says the explicit grant covers this.
Superseded by claude[bot]'s LGTM on 4ffb333: #9493 (review)
…a PowerShell 7 parent's module path no longer stops Get-Acl loading (#9432)
Claude posting for Erik Darling.
The work is on branch
fix/9432-upgrade-run-rows.What was wrong
The upgrade tool's own result was only in the operator's terminal: its exit code, the result of its stop check, the rollback folder, its version. When a service start looked wrong afterwards, the store could not say how the upgrade before it went.
What changed
Darling/tools/upgrade-darling.ps1writesupgrade-run.jsonbeside the install. It never opens a PostgreSQL connection, because it has no driver and the store can be down in the middle of an upgrade.in_progress, tool version, target build and start time. This happens before the service is stopped, so a read of the newest upgrade row shows an upgrade that is under way.finallyblock it rewrites the file with the end time, exit code, stop check result, rollback folder and first error, and statesucceededorfailed.-MarkVerifiedswitch sets the newest run toverifiedonce the operator's checks pass. It does no upgrade and cannot be combined with-Check,-PruneOnlyor-ListRollbacks. It leaves a failed or unfinished run alone.UpgradeRunPickupruns at service start after the migrations, and again on the existing five-minute store-side pass, on its own stamp so it also runs with the alert engine off. The upgrade restarts the service before the script ends, so the result and the verified state are only seen by a pass.in_progress, the result andverifiedland on the same row.verifiedorfailed, or is older than 7 days, or when the stored row is already further along than the file (an older copy put back from a rollback backup). Asucceededrun stays until it is verified.collect.upgrade_runs, store version 312, keyed on the run id. No existing table changes and no data moves, and an older build never names it. It has a row indocs/darling/store-tables.csv, a sentinel in the Viewer's schema probe, and a top rung inMapProbedSchemaVersion. 312 is its final number: it is stacked on the rung object table branch (311) and merges after it.The defect this pass found and fixed
The three
UpgradeRunPickupTestsfailed at the first row write. The one read in full showedCould not bind parameter of CLR type System.DateTime to PostgreSQL type timestamp without time zone ... Cannot write DateTime with Kind=UTC.Cause, in the code and not the tests: the pickup read the file's times as
Unspecifiedkind, but bound the caller'sDateTime.UtcNow(kind UTC) forrecorded_at,updated_atand the retention cutoff. Npgsql refuses a UTC-kind value for atimestampcolumn. The service passesDateTime.UtcNowtoo, so in the field every pickup would have logged a warning and recorded nothing, and the file would have stayed forever.Fix:
RecordAsyncinDarling/PerformanceMonitor.Darling.Storage/UpgradeRuns.csnow sets the kind toUnspecifiedonce, the wayCollectionCaveatStoreandAlertDismissStoredo, and binds that value for both the upsert and the retention delete.Tests
UpgradeRunPickupTests(live, each test mints its own scratch database): three pickups (in progress, succeeded, verified) give ONE row and each state is seen, with the file removed only at verified. A run written while the store was down is recorded at the next pickup and a failed run's file goes. A malformed file warns once per content and stays, and an old in-progress file is recorded and removed.DarlingUpgradeRunRecordTests(6 tests, run under PowerShell against a temp folder): the start file, the end rewrite on success, the end rewrite on failure,-MarkVerifiedon a succeeded run and its refusal on a failed or unfinished one,-MarkVerifiedwith no file, and a failed write that leaves no temp file and the old file untouched.UpgradeRunPickupTests,DarlingUpgradeRunRecordTests,StorageCommandTimeoutTests,StoreTableInventoryLiveTests,AlertReadFailureSurfaceTests,ViewerSchemaVersionGateTests,ViewerDataServiceTests,MigrationLadderPins,MigrationProbeLadderTests,MigrationUpgradeLadderLiveTestsandQuietServerWatermarkLadderLiveTests.[guard-darling] Total: 4997, Errors: 0, Failed: 0and[guard-lite] Total: 1248, Errors: 0, Failed: 0. Theclasses:line wasdarling 3358, lite 1083, which is the whole suite, so the gate stopped (GATE STOP) and ran no selected class. The classes listed above were run by hand instead. CI runs the rest.Not covered by a behaviour test
finallyblock ofupgrade-darling.ps1that callsClose-DarlingUpgradeRun, and the order of the start write beforeStop-Service. The script needs an elevated shell and a registered service, so the tests run the functions it calls (includingClose-DarlingUpgradeRunitself) and not the script's main body.RecordedNotRemovedoutcome, where the row is written but the file cannot be deleted.Handoff: the start-history read
The issue's item 3 (show the upgrade row next to the start that followed it, plus the current install state in a block) is not in this change. The start-history read from #9444 is not on dev yet, so there is nothing to attach to. Once it merges, the read joins
collect.upgrade_runsto the first start after each run'sstarted_atand adds acurrent_installblock from the newest row. A client that wants to skip its run during an install can already read the newest row's state:in_progressmeans an upgrade is under way, andsucceededmeans it is not verified yet.Considered, not added
Brought onto dev
GetBooleanlist, the version gate test and the rewind artifact all moved with it.DarlingUpgradeRunRecordTests,UpgradeRunPickupTests,ViewerSchemaVersionGate*,ViewerDataServiceTests,ViewerSchemaSkew*,*Migration*(377 tests),ReadToolRegistration*. The gate's Guard lines were green for both suites (Darling 5001, Lite 1248, no failures). The gate then stopped because the selection was the whole suite, so CI runs the rest.Fixes #9432
Release note: each upgrade run is now recorded in the store, from start to result to verified, including a run made while the store was down.
Round 1 fixes
upgrade-run.jsonand the install-tree rules. The file is now onGet-DarlingServiceWrittenNamesin bothinstall-darling.ps1andupgrade-darling.ps1(the two copies stay byte-identical). The lock keeps the service's explicit Modify grant on it and makes the service its owner,File.Replacekeeps the replaced file's grant, and the pre-lock walk of a re-run no longer lists the service as a stranger on it, so a run that stops before the lock no longer blocks the documented re-run. The grant on the temp file inWrite-DarlingUpgradeRunFilestays, because nothing else gives the service Modify on the file for a run that stops before the lock, or on an install whose olderinstall-darling.ps1did not list the file. Its comment now says what a move andFile.Replacedo with the DACL.Get-DarlingBackupFileFindingNamesnow tests the backup prefix instead of "listed and not darling.json", so a finding onupgrade-run.jsonis not described as adarling.json.bak-*backup.UpgradeRuns.csupdates only when the file's state ranks at least as high as the stored one (in_progress 0, succeeded and failed 1, verified 2) and returns the state. When the update is skipped the pickup treats the file as stale and removes it. The rollback backup copies every root file with no way to skip one, so it is unchanged.Round 1 fix tests
DarlingUpgradeRunRecordTestsruns the extracted functions under PowerShell with a real SID that is not the current user (Network Service) as the service account. One test writes the file the way the script does and checks that the pre-lock walk lists the grant with no service SID passed (control) and does not list it with the service SID passed. The other runsLock-DarlingInstallTreeon a temp root, then aClose-DarlingUpgradeRunrewrite, and checks the service still holds Modify on the file after each. The lock test ran on a machine with an elevated token, so the owner step ran too.UpgradeRunPickupTests(live): a verified row and a failed row each stay put when an in_progress file of the same run id is picked up, and the stale file is removed. A run moving forward (in_progress, then succeeded) is still recorded and its file kept.upgrade-run.jsontaken off the list, both new PowerShell tests fail. With the list restored they pass.Round 1 fix runs
DarlingUpgradeRunRecord,UpgradeRunPickup,UpgradeDarling,InstallDarling,ServiceWritten,InstallTree,DarlingInstallLocationTests(this one holds the byte-identical comparison test),DarlingUpgradePreflight,DarlingDeployStaleFile,RungRewindArtifacts,ViewerDataServiceTests,DarlingStoreUpgradeTests,DarlingStoreUpgradeRevertTests,MigrationUpgradeLadderLiveTests,ServiceVersionLiveTests,ServiceVersionRungTests,StoreSelfMetricsTests,MigrationRungObjectsLiveTests. All new and changed tests pass.DarlingInstallLocationTestsandDarlingUpgradePreflightTestsfail on that machine (an elevated SSH logon whose temp folder inherits a broad write grant). The same 19 fail on the previous head of this branch without these changes, so they are that machine's, not these changes'. CI decides.GATE STOPbecause the selection is the whole suite. About 277 selected classes were not run one by one: the 18 above were chosen as the ones that name the changed text most directly.Lock-DarlingInstallTree, the pre-lock walk and the rewrite are covered by the two PowerShell tests. The finally block that callsClose-DarlingUpgradeRunstill has no behaviour test.