Repository navigation
Memory 1b/4: write the merged recovery inventory with Write-InventoryJson - #70
Merged
stefoy merged 22 commits intoNov 25, 2026
Merged
Conversation
added 10 commits
November 4, 2026 00:33
Merge-RecoveryData wrote the merged inventory with one ConvertTo-Json | Out-File pipeline. On a large estate that one string can run out of memory, and Out-File has already created the file by then, so the merge leaves a 0-byte Inventory_*.json. Write-InventoryJson moves, unchanged, from ResourceInventory.Functions.ps1 to Common.Functions.ps1. ResourceInventory.ps1 already loads both files at startup. RecoveryMerge.Functions.ps1 now loads Common.Functions.ps1 itself, so it still works when dot-sourced on its own, and writes the merged inventory with Write-InventoryJson. The bytes written are the same as before.
Loading RecoveryMerge.Functions.ps1 dot-sourced all of Common.Functions.ps1 into the caller's session. That redefined Global:Write-Log and Write-RdaProgress there, and a helper variable was set and removed in the caller's scope. Write-InventoryJson now lives, unchanged, in Functions/InventoryJson.Functions.ps1, which holds only that function. RecoveryMerge.Functions.ps1 loads only that file, with no helper variable. ResourceInventory.ps1 loads it at startup next to Common.Functions.ps1, which is back to what it was before the writer moved there. The comment above the merged inventory write now says that a failed write leaves no new, empty or partial inventory, and that an inventory already in the output folder is left unchanged. New tests cover both, and that loading the file keeps the caller's functions and variables.
Write-InventoryJson writes $InputObject.PSObject.Properties one at a time. For a hashtable or [ordered] dictionary those are Keys, Values, Count and so on, not its entries, so the file got the wrong shape with no error. It now throws a clear error for any IDictionary before it writes anything, so no file is created and an existing file is left as it was. Both callers pass a [pscustomobject] (ResourceInventory.ps1) or ConvertFrom-Json output (Merge-RecoveryData), so their output is unchanged.
Write-InventoryJson checked for a dictionary before its try block. With $ErrorActionPreference = 'SilentlyContinue' and no try around the call, that throw was skipped and the dictionary's own properties were written. The check now sits inside the try, before the temporary file is created, so the write always stops and no file is created or changed. A test runs the writer in a child pwsh under SilentlyContinue and Ignore with no enclosing try.
…ssing A plain throw at load time, even re-thrown from a catch, is skipped when the caller runs with ErrorActionPreference SilentlyContinue or Ignore, so the header's '(throws if not)' was false. Throw from a child scope set to Stop, which stops the caller under any preference and leaves the caller's own preference and variables as they were. Test: a fresh pwsh dot-sources a lone copy of the file under SilentlyContinue, Ignore and Continue and must not get past the load.
…ionary write Adds a third case to the no-enclosing-try dictionary test: the caller keeps ErrorActionPreference Continue and passes -ErrorAction SilentlyContinue to Write-InventoryJson. The run goes on, the existing file is unchanged and no temporary file is left. The case fails with the guard outside the try (the b155d70 writer) and passes with the current writer.
…can comment The comment above Test-DictionaryMatchesInventory's token scan called the inventory ids flat tokens. They are ARM-shaped paths, and the pattern finds the subscription, resource-group and name tokens inside them. Comment only.
Under a caller's SilentlyContinue preference a serialiser error can return nothing instead of throwing. Write-InventoryJson then wrote the property name and a colon with no value, so the file was not empty but could not be parsed. - Write-InventoryJson throws when ConvertTo-Json returns nothing for a property name or value. The temporary file is removed and an existing inventory at the path is left unchanged, as for any other failure. - Output is unchanged for every value ConvertTo-Json serialises, including $null, an empty list and an empty string. - Tests: a value whose serialisation returns nothing stops the write under Continue and SilentlyContinue and leaves no file; null, empty and empty-string collectors still match the previous output byte for byte.
…ries The comment said consumption ResourceUris are masked with a scheme that is independent of the inventory dictionary. Build-ObfuscatedResourceUri takes tokens from the run's shared dictionaries for resources the inventory already masked and mints new ones only for the rest. Comment only.
added 7 commits
November 4, 2026 01:19
…d path The comment said consumption tokens come from the run's shared dictionaries for resources the inventory masked. In fact a ResourceUri that matches an inventory id exactly takes that resource's whole masked path from the ResourceIdMap, and any other ResourceUri gets tokens minted for that run's consumption file. Comment only. Test: the empty-serialisation case is also run from a child pwsh with SilentlyContinue and no enclosing try, and the in-process cases now say they run inside a try.
…ternally consistent A resource that is not in the inventory gets subscription and resource group tokens minted for the consumption file, so one real subscription can carry two tokens in the same file. The comment now says so. Comment only.
Write-InventoryJson wrote to '<final path>.<32 hex>.tmp' and then moved it into place. That name is 37 characters longer than the final one, so a final file name of more than 218 characters, which the file system takes, failed with "the path is too long" before anything was written. A merged recovery bundle names its inventory after the gap bundle, so the name can be long. The temporary file is now 'rda-write-<32 hex>.tmp' beside the final one: a new GUID for each write, 46 ASCII characters, never ending in .json. It is opened for this writer only and counts as this call's from the moment it exists, so a failure while building the writer still closes and removes it. On a failed write only that file is removed, and a warning says when it cannot be. No change to what the inventory holds. Tests: InventoryWrite writes a 255-character name and a 255-byte non-ASCII name (skipped on a file system that refuses one), checks the temporary name's shape, warns when removal fails and not on success, and leaves an earlier leftover and other files alone, and leaves nothing when the move into place fails (the first four fail without this).
…nto recovery-merge-stream awslabs#41's last commit edits Write-InventoryJson in Functions/ResourceInventory.Functions.ps1. This branch moved that function to Functions/InventoryJson.Functions.ps1, which already holds the same change plus this branch's own checks, so the conflict keeps this branch's side: the function stays out of ResourceInventory.Functions.ps1. awslabs#41 is merged into awslabs main, so this also clears the conflict with main.
…scustomobject] A string, an array or a number has PSObject properties such as Length or Count, not collectors, so it was written as the wrong shape with no error, as a dictionary was before it was refused. Also re-wrap one long comment.
…mments The dictionary check counts the name, subscription and resource-group map keys; ResourceIdMap keys are whole masked paths. A consumption part is looked up by the full ResourceUri first and minted only on a miss. The recovery write test file gets a BOM and analyzer-clean helper names.
4 tasks
added 4 commits
November 13, 2026 12:40
…y files in the debug log Write-InventoryJson: - Clean-up after a failed write never replaces the write's own error: closing the writer, the removal and its warning each drop a second error. Only a temporary file this call made is removed; a file already gone counts as removed. - The caller passes the temporary file NAME (-TempName), never a folder. It must be 'rda-write-<32 hex>.tmp' in that exact case and not the final file's name, so a later run can always find it again. - Each leftover of a stopped write is named before the write starts, never removed (another run may be writing it). ResourceInventory.ps1 picks that name and logs, with Write-Log to the debug log, the leftovers and the exact temporary path before the write, and the path again after a failed write when the file is still there or the folder cannot be read. It drops only the writer's own 'Write-InventoryJson:' warnings and logs every other one (a ConvertTo-Json "truncated" warning means lost data). Nothing is read from a PowerShell stream for this, so no preference can hide it.
…merge-stream Conflict in Functions/ResourceInventory.Functions.ps1: awslabs#44 adds Compress-RdaReportArchive after the Write-InventoryJson block that this PR moves to Functions/InventoryJson.Functions.ps1. Kept Compress-RdaReportArchive; dropped the old Write-InventoryJson block.
…s safely before setup Write-Log wrote the console line first, so under an information action of Stop its Write-Host threw before the error-log and debug-log lines and replaced the caller's error. It now writes the file sinks first and the console last, best effort. It reads $Global:ErrorLogFile and $Global:DebugLogFile with Get-Variable, as it already reads the subscription tag, so a call before setup (a start-up check) does not stop under a caller's Set-StrictMode -Version Latest.
…the writer file through Write-Log - The folder the run names its temporary file in is $DefaultPath by its provider path (a PowerShell drive name is not a folder to .NET), and a root such as / or D:\ keeps its separator. - The leftover filter also finds an older build's '<name>.json.<32 hex>.tmp' whose report name holds a line break. - The start-up checks read the functions files by literal path, so a copy in a folder whose name holds [ or ] starts; a missing InventoryJson.Functions.ps1 is reported through Write-Log (same lines, exit 1). - Recovery-merge comments describe the token count without one build's id shape. Tests: each case red before its change and green here.
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 17, 2026
pmorgenrood
pushed a commit
to pmorgenrood/resource-discovery-for-azure
that referenced
this pull request
Nov 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Merge after #44.
Built on #41, which is now merged into
main. This branch merges #41's head (the commitsmaintook from #41) and is clean withmain; only this PR's own files differ frommain.Problem
Raised in review of #41:
ResourceInventory.ps1writeInventory_*.jsonwithWrite-InventoryJson, one collector at a time.Merge-RecoveryDatainFunctions/RecoveryMerge.Functions.ps1still writes the merged inventory with the whole-document pipeline:Out-Filehas already created the file by then, so the merge stops and leaves a 0-byteInventory_*.json, or empties an inventory that was already there.ResourceInventory.ps1, which is no longer true after Memory 1/4: write the inventory per collector and release its data #41.Write-InventoryJsonlives inFunctions/ResourceInventory.Functions.ps1, whichRecoveryMerge.Functions.ps1does not load, and the docs (docs/consumption-data.md) tell users to dot-sourceRecoveryMerge.Functions.ps1on its own. So the merge cannot just call it.Change
Write-InventoryJsonmoves, unchanged, to its own file,Functions/InventoryJson.Functions.ps1. The file holds only that function and has no top-level code.It then writes under a short temporary name of its own,
rda-write-<32 hex>.tmp(a new GUID per write, never ending in.json), as Memory 1/4: write the inventory per collector and release its data #41's last commit does in its copy. A merged bundle names its inventory after the gap bundle, so a long gap name (up to the file system's 255) now works; a temporary name built on the final one was 37 characters longer and failed above 218. Only the file this call created is removed on failure, and a warning says when it cannot be.ResourceInventory.ps1loads it at start-up, right afterCommon.Functions.ps1, with the same missing-file check as the other functions files.Functions/RecoveryMerge.Functions.ps1loads it from its own folder when it is dot-sourced, so dot-sourcing it on its own keeps working. If the file is missing, loading stops the caller's script with a clear error under any$ErrorActionPreference, includingSilentlyContinueandIgnore, soMerge-RecoveryDatais never defined without its writer. Loading addsWrite-InventoryJsonandMerge-RecoveryDatato the caller's session and nothing else.Merge-RecoveryDatawrites the merged inventory withWrite-InventoryJson -InputObject $GapInventory -Path $OutInventoryFile, and the comment now names it.Write-InventoryJsonstops before writing anything when:[pscustomobject]: a hashtable or[ordered]dictionary, a string, an array or a number. Before, it wrote that value's own properties (Keys,Count,Lengthand so on) with no error. Both callers pass a[pscustomobject]orConvertFrom-Jsonoutput, so their output is unchanged.ConvertTo-Jsonreturns nothing for a property, which a serialiser error can do under a caller'sSilentlyContinue. Before, it wrote the property name with no value, a file that is not empty but cannot be parsed.$null, an empty list and an empty string are still written as before.Both checks sit inside the function's
try, so they stop the write even when the caller runs withSilentlyContinueand has notryof its own. No temporary or target file is created or changed.Two comments in
Functions/RecoveryMerge.Functions.ps1are corrected. Comments only:ResourceIdMapkeys are whole masked paths, so they never match a single token.Output is unchanged: the merged inventory is byte-for-byte what the old line wrote for the same input. A failed write stops the merge and leaves no new, empty or partial inventory and no temporary file; an inventory already in the output folder is left unchanged.
Tests
New
Tests/RecoveryMergeInventoryWrite.Tests.ps1, 9 tests, on a sample with nested objects, unicode, an empty list, a one-element list, numbers and null:pwshdot-sources onlyRecoveryMerge.Functions.ps1, runsMerge-RecoveryData, and the merged inventory is byte-for-byte the same as the old pipeline's output.Write-Log,Write-RdaProgressand variables, and definesWrite-InventoryJson.InventoryJson.Functions.ps1missing, loading stops the script underSilentlyContinue,IgnoreandContinue, with notry.ConvertTo-Jsoncall.Tests/InventoryWrite.Tests.ps1loadsWrite-InventoryJsonfrom its new file and gains 15 tests (70 in all):[ordered]dictionary and a dictionary over an existing file are refused with nothing written, also from a childpwshwith notryunderSilentlyContinue,Ignoreand a call-site-ErrorAction SilentlyContinue.ContinueandSilentlyContinue, also from a childpwshwith notry; it writes no file and leaves an existing one unchanged.[pscustomobject]built from an ordered dictionary, still match the previous output byte for byte.ResourceInventory.ps1, run in a freshpwsh, defineWrite-InventoryJson.Results (Linux, PowerShell 7, Pester 5.7.1), this PR merged into
mainagainstmain:mainmainInventoryWrite.Tests.ps1RecoveryMergeInventoryWrite.Tests.ps1RecoveryMerge.Tests.ps1./TestsThe 162 failures are the same tests by name on both. They come from test files that need a real
ResourcesReport_*.zip, which the repository does not ship.PSScriptAnalyzer, run file by file: the same findings as
main, none new.How to test
PowerShell 7 and Pester 5. Your own checkout is not touched.
On
mainthe new tests fail becauseWrite-InventoryJsonis not in its own file, the recovery merge does not load it, the whole inventory goes to oneConvertTo-Jsoncall, a failed write leaves a 0-byte file or empties the one already there, and a value that is not a[pscustomobject]is written as the wrong shape.Merge order
Measured with
git merge-treeof this PR against every open PR:main, and clean with every open PR that is clean withmain, except Stop ResourceInventory.ps1 on a misspelled parameter name #58.Functions/ResourceInventory.Functions.ps1, because Memory 4/4: stream the report zip instead of using Compress-Archive #44 addsCompress-RdaReportArchiveright afterWrite-InventoryJson, which this PR moves out of that file. Keep Memory 4/4: stream the report zip instead of using Compress-Archive #44'sCompress-RdaReportArchiveblock and drop theWrite-InventoryJsonblock (it lives inFunctions/InventoryJson.Functions.ps1). With that choice,InventoryWrite.Tests.ps1,ReportArchive.Tests.ps1,RecoveryMergeInventoryWrite.Tests.ps1andRecoveryMerge.Tests.ps1all pass on the combined tree.ResourceInventory.ps1. This PR adds theInventoryJson.Functions.ps1load block just aboveif ($Debug.IsPresent), and Stop ResourceInventory.ps1 on a misspelled parameter name #58 replaces that line: keep this PR's load block, then Stop ResourceInventory.ps1 on a misspelled parameter name #58's$DebugModelines, and drop the oldif ($Debug.IsPresent)line.Limitations
ResourceInventory.ps1run, the rest ofExecuteInventoryProcessingis skipped (the release, the Azure context read and the cost step). With the script'sSilentlyContinuepreference the run then prints no error, builds the HTML report and a zip without an inventory, and a direct run exits 0; the wrappers record the subscription as failed. That comes with Memory 1/4: write the inventory per collector and release its data #41's writer and is not changed here.*.jsonin its output folder, so a reused folder can add a secondInventory_*.json. That is the same onmain; Zip only this run's files when -OutputDirectory is reused #57 addresses it.Write-InventoryJsonhas it replaced when it loadsRecoveryMerge.Functions.ps1.