Skip to content

Memory 1b/4: write the merged recovery inventory with Write-InventoryJson - #70

Merged
stefoy merged 22 commits into
awslabs:mainfrom
pmorgenrood:upstream-pr/recovery-merge-stream
Nov 25, 2026
Merged

stefoy merged 22 commits into
awslabs:mainfrom
pmorgenrood:upstream-pr/recovery-merge-stream

Conversation

@pmorgenrood

@pmorgenrood pmorgenrood commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Merge after #44.

Built on #41, which is now merged into main. This branch merges #41's head (the commits main took from #41) and is clean with main; only this PR's own files differ from main.

Problem

Raised in review of #41:

  • Memory 1/4: write the inventory per collector and release its data #41 makes ResourceInventory.ps1 write Inventory_*.json with Write-InventoryJson, one collector at a time. Merge-RecoveryData in Functions/RecoveryMerge.Functions.ps1 still writes the merged inventory with the whole-document pipeline:
    $GapInventory | ConvertTo-Json -Depth 100 -Compress | Out-File -FilePath $OutInventoryFile
    
  • A merged inventory is at least as large as the gap run's, so a recovery merge can hit the same out-of-memory failure. Out-File has already created the file by then, so the merge stops and leaves a 0-byte Inventory_*.json, or empties an inventory that was already there.
  • The comment above the line says it matches ResourceInventory.ps1, which is no longer true after Memory 1/4: write the inventory per collector and release its data #41.
  • Write-InventoryJson lives in Functions/ResourceInventory.Functions.ps1, which RecoveryMerge.Functions.ps1 does not load, and the docs (docs/consumption-data.md) tell users to dot-source RecoveryMerge.Functions.ps1 on its own. So the merge cannot just call it.

Change

  • Write-InventoryJson moves, 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.ps1 loads it at start-up, right after Common.Functions.ps1, with the same missing-file check as the other functions files.

  • Functions/RecoveryMerge.Functions.ps1 loads 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, including SilentlyContinue and Ignore, so Merge-RecoveryData is never defined without its writer. Loading adds Write-InventoryJson and Merge-RecoveryData to the caller's session and nothing else.

  • Merge-RecoveryData writes the merged inventory with Write-InventoryJson -InputObject $GapInventory -Path $OutInventoryFile, and the comment now names it.

  • Write-InventoryJson stops before writing anything when:

    • it is given anything but a [pscustomobject]: a hashtable or [ordered] dictionary, a string, an array or a number. Before, it wrote that value's own properties (Keys, Count, Length and so on) with no error. Both callers pass a [pscustomobject] or ConvertFrom-Json output, so their output is unchanged.
    • ConvertTo-Json returns nothing for a property, which a serialiser error can do under a caller's SilentlyContinue. 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 with SilentlyContinue and has no try of its own. No temporary or target file is created or changed.

  • Two comments in Functions/RecoveryMerge.Functions.ps1 are corrected. Comments only:

    • Consumption tokens: a consumption id that matches an inventory id exactly takes that resource's whole masked path. For any other id, each subscription, resource group and name part is looked up by the full id, then by its real value in the consumption file's own cache, and gets a new token only on a miss. So a resource not in the inventory can carry subscription and resource group tokens different from the inventory's.
    • The dictionary check counts the keys of the name, subscription and resource group maps. ResourceIdMap keys 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:

    • A fresh pwsh dot-sources only RecoveryMerge.Functions.ps1, runs Merge-RecoveryData, and the merged inventory is byte-for-byte the same as the old pipeline's output.
    • Loading the file keeps the caller's own Write-Log, Write-RdaProgress and variables, and defines Write-InventoryJson.
    • With InventoryJson.Functions.ps1 missing, loading stops the script under SilentlyContinue, Ignore and Continue, with no try.
    • The merge never passes the whole merged inventory to one ConvertTo-Json call.
    • A write that fails part-way leaves no 0-byte inventory and no temporary file.
    • A write that fails over an existing inventory leaves its bytes unchanged.
  • Tests/InventoryWrite.Tests.ps1 loads Write-InventoryJson from its new file and gains 15 tests (70 in all):

    • A string, an array and a number are refused with nothing written.
    • A hashtable, an [ordered] dictionary and a dictionary over an existing file are refused with nothing written, also from a child pwsh with no try under SilentlyContinue, Ignore and a call-site -ErrorAction SilentlyContinue.
    • A value whose serialisation returns nothing stops the write under Continue and SilentlyContinue, also from a child pwsh with no try; it writes no file and leaves an existing one unchanged.
    • Null, empty and empty-string collectors, and a [pscustomobject] built from an ordered dictionary, still match the previous output byte for byte.
    • The start-up lines of ResourceInventory.ps1, run in a fresh pwsh, define Write-InventoryJson.
  • Results (Linux, PowerShell 7, Pester 5.7.1), this PR merged into main against main:

    Run main This PR merged into main
    InventoryWrite.Tests.ps1 55 passed 70 passed
    RecoveryMergeInventoryWrite.Tests.ps1 not present 9 passed
    RecoveryMerge.Tests.ps1 29 passed 29 passed
    Full ./Tests 523 total, 339 passed, 162 failed, 22 skipped 547 total, 363 passed, 162 failed, 22 skipped

    The 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.

git fetch origin pull/70/head:pr-70 main
git worktree add ../rdfa-recovery pr-70
git worktree add ../rdfa-main main

# This PR: all pass
Invoke-Pester -Path ../rdfa-recovery/Tests/RecoveryMergeInventoryWrite.Tests.ps1, ../rdfa-recovery/Tests/InventoryWrite.Tests.ps1, ../rdfa-recovery/Tests/RecoveryMerge.Tests.ps1 -Output Detailed

# main with only this PR's two test files: the new tests fail
Copy-Item ../rdfa-recovery/Tests/RecoveryMergeInventoryWrite.Tests.ps1, ../rdfa-recovery/Tests/InventoryWrite.Tests.ps1 ../rdfa-main/Tests/
Invoke-Pester -Path ../rdfa-main/Tests/RecoveryMergeInventoryWrite.Tests.ps1, ../rdfa-main/Tests/InventoryWrite.Tests.ps1 -Output Detailed

git worktree remove --force ../rdfa-recovery
git worktree remove --force ../rdfa-main
git branch -D pr-70

On main the new tests fail because Write-InventoryJson is not in its own file, the recovery merge does not load it, the whole inventory goes to one ConvertTo-Json call, 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-tree of this PR against every open PR:

Limitations

  • When the inventory write fails in a normal ResourceInventory.ps1 run, the rest of ExecuteInventoryProcessing is skipped (the release, the Azure context read and the cost step). With the script's SilentlyContinue preference 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.
  • The merge zips every *.json in its output folder, so a reused folder can add a second Inventory_*.json. That is the same on main; Zip only this run's files when -OutputDirectory is reused #57 addresses it.
  • A caller that already has its own function named Write-InventoryJson has it replaced when it loads RecoveryMerge.Functions.ps1.
  • Tested on Linux only.

Peter-John Morgenrood 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.
Peter-John Morgenrood 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.
Peter-John Morgenrood 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
@stefoy
stefoy merged commit 1ccef4d into awslabs:main Nov 25, 2026
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