Skip to content

Memory 1/4: write the inventory per collector and release its data - #41

Merged
stefoy merged 20 commits into
awslabs:mainfrom
pmorgenrood:upstream-pr/memory-inventory
Nov 12, 2026
Merged

stefoy merged 20 commits into
awslabs:mainfrom
pmorgenrood:upstream-pr/memory-inventory

Conversation

@pmorgenrood

@pmorgenrood pmorgenrood commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Part 1 of 4 of the memory series, tracked in #45.
Merge order: first. #42 needs it. Conflicts with other open PRs, and how to resolve them:

Problem

On a large estate with limited memory, a run can finish with exit code 0 and an empty inventory, or with an inventory but no HTML
report and no zip. The README lists Azure Cloud Shell's RAM as "~3.5 GB total, ~2.7 GB usable at idle".

  • ProcessResourceResult serialises the whole inventory with one ConvertTo-Json call and pipes the string to Out-File. When that
    string does not fit next to the collector objects already in memory, the inventory file is left at 0 bytes, the zip contains it,
    the HTML report says nothing was found and the Diagnostics log shows "Collector failures: 0". The OutOfMemoryException is written
    only to the local transcript, which is not in the zip.
  • After the inventory is written, the collector output ($Global:SmaResources) and the discovery rows ($Global:Resources) stay in
    memory although nothing reads them any more. The HTML report step that follows can then run out of memory: no HTML, no zip.
  • The script runs with $ErrorActionPreference = 'silentlycontinue', so on a direct run a failed step's error was not shown. A
    failed inventory write, a failed zip step (Write-Error is hidden by that preference) or an input Compress-Archive could not read
    ended with Reporting Data File: <zip> for a zip that was not there, or that was made without one of its files.

Change

  • New Write-InventoryJson in Functions/ResourceInventory.Functions.ps1 writes the inventory one property (collector) at a time
    through a single StreamWriter, so the largest string is one collector's JSON. ProcessResourceResult calls it instead of the
    pipeline. The file is byte-for-byte what the pipeline wrote: UTF-8 without BOM, a one-element collector still an array, Version
    last, trailing newline, same depth limit.
  • The file is written under a temporary name in the same folder and moved into place only when complete. On a failure the temporary
    file is removed and the error is thrown on, so no cut-off inventory is left behind. The temporary name is short and of its own,
    rda-write-<32 hex>.tmp (a new GUID per write, never ending in .json), so a long final file name (up to the file system's
    255) still works; a name built on the final one was 37 characters longer and failed above 218. Only the file this call created
    is removed, and a warning says when it cannot be.
  • ProcessResourceResult catches that error, frees the collector output and the discovery rows (the throw skips the release
    below), writes Inventory write FAILED: <inventory file> was not written: <error> to the console, the error log and the
    debug log, reads the Azure context and removes the provider-registration handler as the release does, and throws it on. Under the
    wrappers it still stops that subscription with the real cause, and the next subscription does not start with the failed
    one's data held by those globals. (A test checks that this path runs the same read and removal as the release; the freeing
    itself was measured for the release, not separately for this path.) On a direct run the script's silentlycontinue preference does not stop
    on the throw: the rest of the processing step is skipped, the report step is not run (No HTML report: the inventory <file> was not written, instead of Inventory JSON not found as a second fault) and the zip step is not tried (There is no report to zip).
  • The zip step runs only when the inventory is there and the report step finished, so it can never make a zip without the
    inventory, or with an HTML file a failed report step left. It
    calls Compress-Archive -ErrorAction Stop and logs its error with Write-Log, so a file it cannot read stops the zip instead of
    being left out without a word. It removes a zip it left unfinished (Compress-Archive normally does that itself; this is a
    backstop), and leaves alone one that was there before it ran. Please zip the output files manually: then names this run's files, and
    under -Obfuscate says to add only those (the dictionary, the transcript and the logs hold real names).
  • The run names the zip (Reporting Data File), says it is safe to share under -Obfuscate, and says the transcript was left out of
    it, only when its zip step finished and the file is there. Otherwise its last line is No report was written: <zip> was not created. See the errors above, fix the cause and re-run., the same words as Exit 2 from a direct run that wrote no report #52, and the run times are shown as Info
    (Reporting Time: not measured, ... when the processing step stopped, never an earlier run's time). Exit codes
    are unchanged: a direct run that wrote no report still exits 0; Exit 2 from a direct run that wrote no report #52 makes it exit 2.
  • ExecuteInventoryProcessing releases $Global:SmaResources and $Global:Resources right after ProcessResourceResult and runs a
    full garbage collection.
  • After the release, ExecuteInventoryProcessing reads the Azure context once
    ($null = Get-AzContext -ErrorAction Stop, in a try block that writes one debug-log line if it fails and lets the run go on).
    Az cmdlets keep their stream handlers in the shared Azure session after they return, so the VM or scale set size lookup, whose
    output is piped on to a filter,
    stayed referenced with the rows the collector was given until the next Az cmdlet. The read replaces those handlers, so the release
    frees them. Without it, on a live run with VMs or scale sets, the data was freed only at the cost step's sign-in check, and with
    -SkipConsumption not before the report step.
  • In the same try block, right after the read, the provider-registration handler that the size lookup adds to the shared client
    factory is removed by type (ClientFactory.RemoveHandler([...RPRegistrationDelegatingHandler])). That handler also keeps the
    lookup's cmdlet, and with it the rows, and the read does not always remove it: on live runs the read alone freed the rows in 3 of
    7 runs, the read and the removal in 3 of 3. The next resource-manager cmdlet adds its own handler again.
  • The discovered resource count is kept in a new $Global:ResourceCount, reset at the start of each run and set when discovery
    finishes, so an early exit never reports the previous subscription's count. Run-AllSubscriptions.ps1 (sequential and parallel
    paths) and Run-AllSubscriptions.Stream.ps1 read it instead of counting $Global:Resources. Those three reads were the only uses of
    either variable after the inventory is written.

Testing

Linux, PowerShell 7.6, Pester 5.7.1.

  • Tests/InventoryWrite.Tests.ps1, 55 tests: byte equality with the previous output, array and encoding details, no whole-document
    ConvertTo-Json call, relative path, replacing an existing file, a failed write leaving neither the inventory nor the temporary
    file, the count after a normal run, an early exit and a run that stopped after discovery, the data released before the report
    step, and each wrapper call site. Twenty-one tests run the script's end as a direct run (pwsh -File, no caller catching errors)
    or as the wrappers call it: with the inventory write failing (a collector ConvertTo-Json rejects, and out of memory) the real
    cause is logged once, the report step is not run, no Reporting Data File line, no inventory, temporary file or zip is left, the
    collector data is freed, and a wrapper run stops with that cause, even when the Azure session read after it fails too; the next two runs in the same process are normal; an HTML file
    with no inventory next to it, or one a failed report step left, is never zipped; a zip step that throws, leaves a cut-off zip, cannot remove it, meets a
    zip already at the path, or reports a file it cannot read only as a non-terminating error never names a zip, and its manual-zip
    advice names only this run's files; safe to share and
    the run times follow the zip and never show an earlier run's time; a normal direct run names its zip and exits 0. Three tests cover the provider-registration handler
    removal, one of them on the failed-write path. Six tests cover the Azure context read: it comes after the release and before its first
    collection and the cost step; there is exactly one; a non-terminating error, a terminating error and a missing cmdlet are each
    written once to the debug log only and the run goes on; and, in a separate pwsh process with no Azure sign-in and no network,
    the shipped block frees rows that a collector-shaped scope kept through a piped Az call, where a plain statement does not (three
    rounds). That test and the one for a provider-registration handler the read leaves in place are skipped where Az.Accounts is
    not installed, and on Windows, where the separate process cannot be kept
    away from the user's Azure profile. The run harness stubs Get-AzContext, and a test checks it
    never loads Az.Accounts. On awslabs main 52 of the 55 fail (run with Az.Accounts installed; the 3 that pass check a normal run's
    last lines); on this branch all pass. On this branch
    without the read, the new tests fail with Expected $true, because the release frees nothing until an Az cmdlet replaces the stream handlers the last collector left in the Azure session, but got $false., Expected 1, but got 0., and (read removed or replaced by
    a plain statement) Expected $false, because round 1: the session read after the release frees them, but got $true. With
    -ErrorAction SilentlyContinue on the read, the non-terminating case fails with Expected 1, because one debug-log line per failed read, but got 0.

  • Az.Accounts 5.5.3 and 5.5.4: in a standalone check with the collector's shape (2,000 rows), the rows stay held after the release
    without the read and are freed with it, with the size lookup succeeding or failing, on both versions.

  • Full suite: no failure added, compared test by test with the previous head of this PR (8afde1e): the same failing and skipped
    tests, plus the new ones, which pass.
    PSScriptAnalyzer per file with the repository settings reports nothing on the changed files, before or after.

  • The memory figures below for generated estates were measured on an earlier head of this branch, before the Azure context read
    was added, with disk records replayed in place of the Resource Graph query (no VMs, so no size lookup and nothing for the read to
    free). Live figures for the Azure context read are further down.

  • Generated disks-only estates (disk records copied from a test subscription and replayed in place of the Resource Graph query by a
    test-only change), memory limit set with a cgroup. Every one of these runs skipped the cost step (-SkipConsumption). With metrics
    on, the metrics step was stopped once it had built its request list (test-only change; generated resources have no metrics), so no
    Azure Monitor calls were made. No run was killed by the system; each failure below is an OutOfMemoryException inside PowerShell.

    With memory limited to 2.7 GB (2,600 MiB), about the usable memory the README gives for Cloud Shell:

    Generated estate awslabs main this PR
    60,000 disks, metrics on, 3 runs each 2 of 3 complete; 1 ran out of memory in the HTML step: no HTML, no zip, exit 0 3 of 3 complete
    80,000 disks, metrics off 0-byte inventory, HTML "nothing found", zip, exit 0 80,000 records from 57 collectors, HTML, zip, exit 0; cgroup peak 2,045 MiB
    80,000 disks, metrics on out of memory while building the metric request list: no inventory, no zip, exit 0 same as main (see Memory 2/4: build metric request definitions as a compact class #42)

    Managed heap at the start of the report step at 60,000 disks (read without forcing a collection): 1,117 to 1,329 MB on main,
    61 MB with this PR.
    Each commit alone was also measured, which is why they come as one PR: the writer alone completed 0 of 3 runs at 60,000 disks (the
    inventory was written, then the HTML step ran out of memory), and the release alone still left a 0-byte inventory at 80,000 disks
    with metrics off.

    With memory limited to 3.4 GB (3,242 MiB), 80,000 disks, metrics on: main wrote the inventory, then the HTML step ran out of memory (no zip, exit 0);
    this PR completed (inventory, HTML, zip, exit 0), peak about 2,585 MB. Wherever both sides completed, the inventory content was
    identical record for record.

  • Live, on a test subscription, before the Azure context read was added (earlier head of this branch against main), all defaults
    including the cost step and real Azure Monitor calls, as a single run and through Run-AllSubscriptions.ps1 (sequential and
    -ParallelStreams 2): inventory identical record for record, every metric record
    identical in every field (metrics time window pinned to the same moment for both runs), the same consumption rows, the zip with
    the same entries and sizes, and the same exit code as main. With -Obfuscate (replayed rows): identical apart from the obfuscated
    fields, which are random per run by design.

  • Live, Azure context read: Az.Accounts 5.5.4, a test subscription of about 11,000 resources (3 VMs, 132 scale sets, 454 inventory records), the
    discovery query as on main (network rows included), managed heap after a full collection, three alternating runs of each
    side. These runs used this branch merged on Run with Az PowerShell only: drop the Azure CLI #66 (PowerShell-only sign-in), with and without the read, because the test
    host has no Azure CLI, which this branch's base needs; the diff between the two trees was only the read and its tests.

    Run Point without the read with the read
    single run, cost step on heap at the cost step start 557-560 MB 129-130 MB
    single run, cost step on heap at the report step start 131-135 MB 130-131 MB
    single run, cost step on release step 676-678 ms 366-367 ms
    single run, cost step on whole run 162, 173, 165 s 161, 176, 159 s
    single run, -SkipConsumption heap at the report step start 556-560 MB 128-129 MB
    Run-AllSubscriptions.ps1, two runs in one session heap at the cost step start, largest subscription, first / second run 567-576 / 581-589 MB 140 / 153-158 MB
    Run-AllSubscriptions.ps1, two runs in one session heap left after each run 144-165 MB 144-159 MB
    Run-AllSubscriptions.ps1 -ParallelStreams 2 worker heap at the cost step start 563-564 MB 135-136 MB

    With the cost step on, the cost step's sign-in check already freed the data before the report step; the read moves that to
    the release, so the cost step and the report step both start without it, and with -SkipConsumption the report step now
    does too. No consistent whole-run slowdown in three alternating runs. Compared with and without the read in every pair:

    • single runs: the inventory record for record and the cost rows were the same; the diagnostics log was the same apart from
      lines with times, durations or memory; the HTML text was the same apart from phase durations; the zip held the same entry
      names (sizes and metric files not compared);
    • wrapper runs: every per-subscription inventory, cost file and diagnostics log, the metric records and the run summary
      were the same, apart from a few metric records with a different number of points with data (the newest point can arrive
      between runs; values are not compared), and one pair that ran either side of midnight UTC, whose cost rows and the run summary's cost record count differ because each day asks for a different 31 days. Both
      sides exit 4 on this subscription through the wrapper, from the scale set collector date error that Fix VMSS collector failing on Flexible scale sets #39 fixes.

How to test

1. Quick check, no Azure needed (PowerShell 7, Pester 5, from the repository root; your own checkout is not touched):

git fetch origin pull/41/head:pr-41
git worktree add ../rdfa-pr41 pr-41
git worktree add ../rdfa-main origin/main

# This PR: 55 tests; all pass with Az.Accounts installed (without it, 53 pass and 2 are skipped)
Invoke-Pester -Path ../rdfa-pr41/Tests/InventoryWrite.Tests.ps1 -Output Detailed

# main with only the new test file: 52 of 55 fail
Copy-Item ../rdfa-pr41/Tests/InventoryWrite.Tests.ps1 ../rdfa-main/Tests/
Invoke-Pester -Path ../rdfa-main/Tests/InventoryWrite.Tests.ps1 -Output Detailed

On awslabs main 52 of the 55 fail (run with Az.Accounts installed). The key messages: Expected function 'Write-InventoryJson' to be defined by <repo>/Functions/ResourceInventory.Functions.ps1, but it was not., Expected ConvertTo-Json to be called 0 times exactly, because the inventory is written one collector at a time, but was called 1 times, Expected 1, but got 0. and Expected $true, because the report step must not have to share memory with the discovery rows, but got $false. On this branch all 55 pass. (Run on Linux, PowerShell 7.6,
Pester 5.7.1.)

2. Live check of the release on a test subscription (read-only):

  • Use a subscription with at least one VM or scale set and a few thousand resources. The memory is held through the VM or scale
    set size lookup, so a subscription with neither shows no difference.
  • Sign in once in the same PowerShell window: az login, then Connect-AzAccount, same tenant (main and this PR still use the
    Azure CLI).
  • Add a temporary memory line at the start of the report step in both folders:
foreach ($dir in '../rdfa-main', '../rdfa-pr41') {
    $f = Join-Path $dir 'ResourceInventory.ps1'
    $lines = [Collections.Generic.List[string]](Get-Content $f)
    $i = $lines.IndexOf('function FinalizeOutputs')
    $lines.Insert($i + 2, '    Write-Host ("MEMCHECK report start: {0:N0} MB" -f ([GC]::GetTotalMemory($true) / 1MB))')
    Set-Content $f $lines
}
  • Run with the wrapper, as customers do. With -ParallelStreams 1 it runs ResourceInventory.ps1 in the same window, so one MEMCHECK line prints per
    subscription:
pwsh -NoProfile -File ../rdfa-main/Run-AllSubscriptions.ps1 -TenantID <tenant-id> -ParallelStreams 1 -SkipConsumption
pwsh -NoProfile -File ../rdfa-pr41/Run-AllSubscriptions.ps1 -TenantID <tenant-id> -ParallelStreams 1 -SkipConsumption

The wrapper runs every subscription in the tenant. For a big tenant, the faster choice is a direct run on one subscription:
pwsh -NoProfile -File ../rdfa-<main|pr41>/ResourceInventory.ps1 -TenantID <tenant-id> -SubscriptionID <subscription-id> -SkipConsumption.

  • Why -SkipConsumption: with the cost step on, the cost step's own Azure context check frees the rows a few seconds later, so
    the report step looks the same on both. To see the gap with the cost step on, put the same line at the start of
    function GetResorceConsumption instead ($lines.IndexOf(' function GetResorceConsumption()'), then the same insert);
    measured at that point: 557-560 MB without the read vs 129-130 MB with it (three runs each).
  • What to look for: the MEMCHECK line is lower on this PR for subscriptions with VMs or scale sets. Measured on a test subscription of about
    11,000 resources (454 inventory records), three runs each: report start with -SkipConsumption 556-560 MB without the read
    vs 128-129 MB with it; through the wrapper (two runs in one session), heap at the cost step start for that subscription
    567-589 vs 140-158 MB, and in a
    -ParallelStreams 2 worker 563-564 vs 135-136 MB. These were measured with this PR merged on Run with Az PowerShell only: drop the Azure CLI #66 (PowerShell-only sign-in),
    because the test host has no Azure CLI. The figure depends on the subscription's size. Inventory records are the same in
    both runs.
  • Exit code: a scale set with an empty creation time can make the wrapper exit 4 on main and on this PR; that is the collector
    bug Fix VMSS collector failing on Flexible scale sets #39 fixes, not this PR.
  • Clean up:
git worktree remove --force ../rdfa-main
git worktree remove --force ../rdfa-pr41
git branch -D pr-41

3. Reproduce the memory problem (Linux with a systemd user session; not run exactly as written: the runs above fed generated
disk records in place of the Resource Graph query). Against a subscription with tens of thousands of managed disks, on awslabs main
and then on this branch:

systemd-run --user --scope -p MemoryMax=2600M -p MemorySwapMax=0 \
  pwsh -NoProfile -File ./ResourceInventory.ps1 -TenantID <tenant-id> -SubscriptionID <subscription-id> -SkipConsumption -SkipMetrics

Leave out -SkipMetrics for the HTML-step failure (seen at 60,000 disks); at 80,000 disks that run fails earlier, see
#42.

4. What to look for, in ~/InventoryReports/ResourcesReport<timestamp>/:

  • awslabs main: Inventory_ResourcesReport_<timestamp>.json is 0 bytes, the HTML report shows no resources, and
    Diagnostics_ResourcesReport_<timestamp>.log says Collector failures: 0; the OutOfMemoryException is only in
    Transcript_Log_ResourcesReport_<timestamp>.txt; exit code 0. Or, when the inventory fits: the console shows HTML report generation FAILED: ... OutOfMemoryException ... and there is no HTML file and no ResourcesReport_<timestamp>.zip.
  • this branch: the inventory holds every collector's records, and the HTML report and the zip are written.

Limitations

  • With metrics on, 80,000 generated disks with memory limited to 2.7 GB still run out of memory at an earlier step, while the metric request list is
    built. Memory 2/4: build metric request definitions as a compact class #42 addresses that step.
  • The HTML report is the next limit: with metrics off, 100,000 generated disks with memory limited to 2.7 GB write the inventory (about 51 MB) and
    then the HTML step runs out of memory: no HTML, no zip, exit 0. Not addressed by this series.
  • Exit codes are unchanged: when a later step still runs out of memory, or the inventory write fails, a direct run still ends
    with exit 0 (related to Collector errors are silently swallowed by global SilentlyContinue + missing try/catch #22); Exit 2 from a direct run that wrote no report #52 makes a direct run that wrote no report exit 2. When the inventory write fails in a direct
    run, the rest of the processing step is skipped (the release and the cost step; the failure path frees the collector data and
    does the Azure context read and handler removal itself); the run prints the cause, writes no HTML report and no zip, and ends
    with No report was written. The wrappers record that subscription as failed.
  • Under -RunAllSubs, a subscription whose zip step fails returns normally, so Run-AllSubscriptions.ps1 records it as completed
    and a later -Resume skips it, as on main. Carry earlier reports into the -Resume bundle #48 fixes that (a run that left no zip is not completed).
  • With a reused -OutputDirectory, the zip's *.json input still takes earlier runs' JSON files too, as on main (under
    -Obfuscate that can include an earlier plain run's inventory, with real names). Zip only this run's files when -OutputDirectory is reused #57 fixes that by taking only this run's
    files; until it is merged, do not share a zip from a reused folder. The manual-zip advice added here names only this run's
    files.
  • Steps after FinalizeOutputs run after the transcript has stopped, as on main, so the report and zip errors are on the console and
    in the error log, not in the transcript; the Inventory write FAILED line is in all three.
  • A VM or scale set size lookup stopped by a terminating error may keep its rows in memory until the process ends, as on main;
    the read does not cover that case, and it was not measured here.
  • The Azure context read was tested with Az.Accounts 5.5.3 and 5.5.4 only.
  • A failed inventory write now leaves no inventory file instead of a 0-byte one. If the process is killed during the write, a
    <inventory>.<id>.tmp file can be left next to it.
  • 60,000 disks is at the edge for main at this limit (2 of 3 runs completed). Not tested: estates mixing many VMs and disks, the cost
    step at these sizes, Windows, macOS, and Cloud Shell itself.

Peter-John Morgenrood added 2 commits October 22, 2026 23:05
ProcessResourceResult serialised the whole inventory with one
ConvertTo-Json call and piped the string to Out-File. On a large estate
that string, built on top of the collector objects already in memory,
can run out of memory.

- Add Write-InventoryJson, which writes the inventory object one
  property (collector) at a time through a single StreamWriter, and
  call it from ProcessResourceResult instead of the pipeline.
- The output is unchanged: the file is byte-for-byte what the previous
  pipeline wrote (UTF-8 without BOM, a one-element collector still
  written as an array, Version last, trailing newline, same depth
  limit).
- The whole inventory is no longer built as one JSON string; the
  largest string is now one collector's JSON.
- The file is written to a temporary file in the same folder and moved
  into place only when complete, so a failed write leaves no cut-off
  inventory; the temporary file is removed and the error re-thrown.
- Add Tests/InventoryWrite.Tests.ps1: byte equality with the previous
  output, array and encoding details, no whole-document ConvertTo-Json
  call, relative path, replacing an existing file, and that a failed
  write throws and leaves neither the inventory nor the temporary file.
On a large estate the HTML report step ran out of memory while the
collector output ($Global:SmaResources) and the raw discovery rows
($Global:Resources) were still held, although nothing reads either
once the inventory is written.

- Release both after ProcessResourceResult and run a full collection.
- Keep the discovered resource count in $Global:ResourceCount. It is
  reset with $Global:Resources at the start of each run and set when
  discovery finishes, so an early exit never reports the previous
  subscription's count.
- Run-AllSubscriptions.ps1 and Run-AllSubscriptions.Stream.ps1 read the
  per-subscription count from $Global:ResourceCount instead of counting
  $Global:Resources.
- Tests: the count after a normal run, after an early exit and after a
  run that stopped once discovery had finished; the data is released
  before the report step; each wrapper call site records the count.
@bradwebber

Copy link
Copy Markdown
Collaborator

Functions/RecoveryMerge.Functions.ps1 still writes the merged inventory with the whole-document pipeline that this PR replaces. Line 337 on main reads:

$GapInventory | ConvertTo-Json -Depth 100 -Compress | Out-File -FilePath $OutInventoryFile

A merged inventory is at least as large as the gap run's inventory. Recovering a large estate can therefore hit the same out-of-memory failure and 0-byte file that this PR fixes for the main run. The comment above that line also says the output matches the serialization in ResourceInventory.ps1, and that serialization is now Write-InventoryJson.

Calling Write-InventoryJson -InputObject $GapInventory -Path $OutInventoryFile there would fix it. Users dot-source RecoveryMerge.Functions.ps1 on its own (see docs/consumption-data.md), so Write-InventoryJson would need to move somewhere that file can load, such as Common.Functions.ps1. This change could also go in a later PR in the series if that fits the plan better.

… the data

Setting $Global:SmaResources and $Global:Resources to $null did not free
the data on a live run with virtual machines or scale sets. Az cmdlets
leave their stream handlers in the shared Azure session when they
return. The VM size lookup pipes its output into Where-Object, so its
handlers kept the collector, and the rows it was given, referenced
until the next Az cmdlet ran. With billing on, the billing step's sign-in
check freed them a few seconds later; with -SkipConsumption nothing did
before the report step.

- Right after the release, and before it collects, read the Azure
  context once ($null = Get-AzContext -ErrorAction SilentlyContinue).
  That call replaces the handlers from a scope that holds no rows.
- The read sits in a try block. If it fails, the run goes on and one
  line goes to the debug log.
- Output is unchanged. No Azure resource is called.
- Tests in Tests/InventoryWrite.Tests.ps1: the read comes after the
  release and before its first collect and the billing step; there is
  exactly one; and, in a separate offline pwsh process, the shipped
  block frees rows that a collector-shaped scope kept through a piped
  Az call, where a plain statement does not (three rounds). The last
  test is skipped when Az.Accounts is not installed. The run harness
  now stubs Get-AzContext, and a test checks it never loads Az.Accounts.
@pmorgenrood

pmorgenrood commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks, good catch. Agreed on all three points: Merge-RecoveryData still writes the merged inventory with the whole-document pipeline, a merged inventory is at least as large as the gap run's, and the comment above it is out of date.

To keep #41 to the main run, the fix is in #70, which is built on this branch:

  • Write-InventoryJson moves, unchanged, to its own file, Functions/InventoryJson.Functions.ps1. Later commits in Memory 1b/4: write the merged recovery inventory with Write-InventoryJson #70 make it stop before writing when it is given a dictionary or when ConvertTo-Json returns nothing for a property; the output for valid input is unchanged.
  • ResourceInventory.ps1 and RecoveryMerge.Functions.ps1 both load it, so dot-sourcing RecoveryMerge.Functions.ps1 on its own keeps working. It stops with a clear error if the file is missing.
  • Merge-RecoveryData writes the merged inventory with Write-InventoryJson, and the comment now names it.
  • A new test checks that the merged inventory is byte-for-byte the same as the old pipeline's output, including when only RecoveryMerge.Functions.ps1 is loaded.

#70 should merge after #41.

The read after the release used -ErrorAction SilentlyContinue, so a
non-terminating error from Get-AzContext never reached the catch and no
debug-log line was written. The comment also named only the VM size lookup,
while the scale set collector makes the same piped call later.

- Read with -ErrorAction Stop inside the existing try, so every failure is
  logged to the debug log and the run goes on. With no Azure context the read
  returns nothing and raises no error.
- The comment names the VM or scale set size lookup.
- Tests: a non-terminating error, a terminating error and a missing cmdlet are
  each logged once to the debug log only, and the code after the block runs.
  The memory test is skipped on Windows, where the child process cannot be
  kept away from the user's Azure profile. Its comment says why it pipes
  Get-AzContext rather than the size lookup.
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 4, 2026
Peter-John Morgenrood added 15 commits November 4, 2026 02:33
…he release

The Azure context read after the release does not always free the collector
data. The VM or scale set size lookup also adds a provider-registration handler
to the shared Azure client factory, and that handler keeps the lookup cmdlet,
and through it the rows the collector was given, referenced. On some live runs
the read left that handler in place, so with -SkipConsumption the rows were
still held when the report step started.

- In the same try block, right after the read, remove that handler by type.
  The next resource-manager cmdlet adds its own again, so later Azure calls
  work as before. If the removal fails, the catch writes one line to the debug
  log and the run goes on.
- Output is unchanged. No Azure resource is called.
- Tests in Tests/InventoryWrite.Tests.ps1: the removal follows the read in the
  guarded block; and, in a separate offline pwsh process, the shipped block
  frees rows that a provider-registration handler kept while the read did
  nothing, where a plain statement does not, and leaves no such handler in the
  client factory (three rounds). The last test is skipped where the other
  memory test is.
…ing zip

Write-InventoryJson removes its temporary file and throws when the write
fails. ResourceInventory.ps1 runs with ErrorActionPreference
'silentlycontinue', and a direct run has no caller that catches the throw,
so the error was never shown: the report step then failed with
'Inventory JSON not found' and the run still printed 'Reporting Data File'
for a zip that was never made.

ProcessResourceResult now logs the real cause as an error (console, error
log and debug log), naming the inventory file and the exception, and then
throws it on, so a wrapper run still stops with that cause. The last line
of the run names the zip only when it exists, and otherwise says that no
report zip was written. Exit codes are unchanged.
Also word the last-line comment and the no-zip check so they hold when a direct run's exit-code check comes first.
… was written

The zip step's catch used Write-Error, which the script's 'silentlycontinue'
preference hides, so a failed Compress-Archive left no message on the
console or in the error log. It now uses Write-Log with the exception.

When the HTML report step fails, the run no longer says the inventory,
metrics and consumption files were still written: after a failed inventory
write that is not true. It says the files the run did write are still in
the output folder.
- A zip the failed zip step left behind is removed, so the last line
  cannot name a cut-off file; a zip that was already there is left alone.
- Under -Obfuscate, 'The ZIP file is safe to share' is printed after the
  zip step and only when the zip exists.
- The no-zip line uses the same words as the exit-code check for a direct
  run that wrote no report: 'No report was written: ...'.
A file at the zip path is not proof that this run wrote it: Compress-Archive
refuses to overwrite a zip that was already there, and a zip cut off
part-way may not be removable. The zip step now keeps a flag, cleared in
its catch, and the 'Reporting Data File' and 'safe to share' lines need it.

- A failed removal of the unfinished zip is logged with advice.
- 'Please zip the output files manually' is shown only when the inventory
  and the HTML report are there; otherwise the run says there is no
  report to zip.
- The run times are shown as Info, not Success, when no zip was written.
After a failed inventory write the run no longer prints 'Compressing Resources Output', and 'Reporting Time' says it was not measured instead of printing an empty value. The zip-step comment says the partial-zip removal is a backstop: Compress-Archive removes its own unfinished zip.
…hout a file

Under 'silentlycontinue' an input Compress-Archive cannot read was only a
hidden error: the zip was made without it and named as the report. The
call now uses -ErrorAction Stop, so that zip goes to the catch and is
removed, and the run says no report was written.

- The 'transcript log excluded from zip' line is printed only when the
  zip was written.
- The zip is this run's report only when the step finished and the file is
  there; the 'safe to share' and 'Reporting Data File' lines use the same
  check.
- The raw error record dump next to the error line is gone.
…led write

- A failed inventory write now frees the collector output and the
  discovery rows before it throws on: the throw skips the release, so the
  report step, and under the wrappers the next subscription, kept them.
- The report step is not run without the inventory: the run says
  'No HTML report: the inventory ... was not written' instead of failing
  with 'Inventory JSON not found' as if it were a second fault.
- The zip step is not tried without the inventory and the HTML report, so a
  zip can never be made without the inventory.
- The manual-zip advice names the files, and under -Obfuscate says to add
  only those: the dictionary, the transcript and the logs hold real names.
- The context-read tests find the release from the ProcessResourceResult
  call, so the new failure-path release is not taken for it.
Without the inventory the report step now stops before its 'Creating Summary Report' lines, and without the inventory and the HTML report the zip step is not called, so the run prints no 'Error Compressing Output File' for a call it did not make; it says once that there is no report to zip.
…er a failed write

- The zip step needs the report step to have finished, not only an HTML
  file at the path: a report step that failed after writing part of its
  file no longer has that file zipped and named as the report.
- After a failed inventory write the run also reads the Azure context and
  removes the provider-registration handler, as the release does, so the
  Azure session lets go of the rows too.
$Global:ReportingRunTime is reset before the processing step, so a run in the same session whose processing step stops says the time was not measured instead of printing the previous run's time.
…r the call

The flag that keeps a failed report step's HTML file out of the zip is now set in the catch, so the Summary.ps1 call line is left as it was and open PRs that change that call merge without a conflict there.
The catch frees the collector output and the discovery rows first, so the error line has the memory it needs. A test checks that a failing Azure session read after the failed write does not replace the write error the wrapper sees.
In a reused output folder the zip's '*.json' input also matches earlier runs' files, which may hold real names. The advice now lists only files with this run's stamp.
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.

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).
@stefoy
stefoy merged commit 64f3da4 into awslabs:main Nov 12, 2026
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 12, 2026
…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.
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 12, 2026
awslabs#41 is now in main, and both PRs add a function at the end of
Functions/ResourceInventory.Functions.ps1 and touch the same zip call,
so awslabs#44 no longer merged cleanly.

- Functions: keep both, Write-InventoryJson (awslabs#41) then
  Compress-RdaReportArchive (awslabs#44).
- Zip step: keep every awslabs#41 rule (zip only when the inventory and the
  HTML report were written, -ErrorAction Stop, no zip named or shared
  that this call did not finish, remove a cut-off one) and call
  Compress-RdaReportArchive instead of Compress-Archive. The comments
  now name the function that runs.
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 12, 2026
After the merge with awslabs#41 the run zips with Compress-RdaReportArchive, so
awslabs#41's zip-step tests stubbed a function the run no longer calls and 7
of them failed. They now stub Compress-RdaReportArchive; the stand-ins
that take parameters are advanced functions, so they accept the
call's -ErrorAction Stop as the real one does. The packaging test now
expects the call with -ErrorAction Stop.
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.

3 participants