Skip to content

Check read access and usage values up front for every subscription - #38

Open
pmorgenrood wants to merge 77 commits into
awslabs:mainfrom
pmorgenrood:upstream-pr/access-and-usage-check
Open

pmorgenrood wants to merge 77 commits into
awslabs:mainfrom
pmorgenrood:upstream-pr/access-and-usage-check

Conversation

@pmorgenrood

@pmorgenrood pmorgenrood commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Two kinds of missing access go unnoticed today and produce a report that looks complete but is not:

  • Usage (consumption) data. It shows whether a machine ran for 4 hours or 400.
    Azure's usage API (Get-UsageAggregates) does not reject an identity that lacks Microsoft.Commerce/UsageAggregates/read; it
    answers successfully with zero rows. The existing up-front check only stops on a permission error, probes only the first
    subscription for a single day, and treats "no error" as access. The run then finishes with an empty consumption sheet and no
    message. Direct runs of ResourceInventory.ps1 have no check at all.
  • Read access to resources. The existing check in Run-AllSubscriptions.ps1 lists the subscription's resource groups and treats
    any successful answer as access. Azure filters that list to what the caller may see instead of refusing, so an identity that can see
    a subscription but read none of its resources gets an empty list, passes, and ends with an empty report labelled "GENUINELY EMPTY -
    access confirmed". Direct runs have no check.

Change

Before any inventory or metrics work, Run-AllSubscriptions.ps1 and direct runs of ResourceInventory.ps1 now run two checks on
every subscription the run will process (on -Resume only those still to do; under -RunAllSubs the inner script does not repeat
them).

  1. Role check. The run reads the signed-in identity's own role assignments that apply to the subscription (including those given
    through a group, and those at a management group or the tenant root) and the permissions of each role, and separately asks Azure
    for the caller's effective permissions on the subscription. It needs one role that reads every resource type: an action such as
    */read or *, and no notActions in that same role that remove reads of some resource types (a not-action that, with *
    standing for any characters, can match an action ending in /read, for example Microsoft.Compute/*/read or Microsoft.Comp*),
    because Resource Graph leaves out the resources of a type the caller cannot read without an error. Not-actions confined to
    Microsoft.Authorization, Microsoft.Commerce, Microsoft.Consumption or Microsoft.Billing are allowed: the inventory reads no
    resources of those namespaces. Each role is judged on its own, as Azure
    does, so Reader next to a narrower custom role passes. Both answers must agree:
    • both say read access: passes, and prints which role grants it and where (for example "Reader at subscription");
    • both say no: not readable, listing the roles it could see, or naming the role and the not-action that leaves out some resource types
      (for example role 'Custom reader' at subscription excludes 'Microsoft.Compute/*/read'; the inventory would miss those resources);
    • the identity may not read role assignments, so none are visible: Azure's answer decides, and the output says so;
    • the two disagree, or an answer is still missing after retries: not readable, showing both answers.
      A subscription that is not readable is skipped (new in this revision): it is listed with its reason right after the check
      and again at the end of the run, and the other subscriptions are collected. When no checked subscription is readable the run
      stops with exit 1 (on -Resume, only when no subscription in the run is recorded as completed; see the latest update
      below). The list gives the fix for each cause: grant Reader (no read access, or a resource group that is not found), re-run (an
      answer still missing after retries), or wait about 5 minutes and re-run (the answers disagree, usually because roles were just
      changed and take a few minutes to apply). The role assignment list is followed for at most 1000 pages; past that the answer
      counts as missing. Each role definition is read once per run, and one whose read is refused (HTTP 401, 403 or 404) is not read
      again for later subscriptions; after throttling, a server error or a timeout it is read again.
      For a direct run with -ResourceGroup, a role on that resource group is enough. When consumption is requested, the check also
      reports whether the roles on the subscription allow reading usage (Microsoft.Commerce/UsageAggregates/read, counted only at the
      subscription or above). The usage check below uses that answer for subscriptions that return no usage, and adds it to the fix
      text when it refuses.
    • New in this revision: the role check follows only the path and query of a next-page link (nextLink), on the Resource
      Manager endpoint of the signed-in context, so no request goes to a host the answer names. A nextLink that is not an
      http(s) URL, or has no path (or one starting with //), counts as a missing answer, so the subscription is not readable and
      is skipped with that reason.
  2. Usage values check (when consumption is requested, no -SkipConsumption), for the readable subscriptions. Same usage API,
    options and 31-day window as the billing phase: the API that the billing phase's Get-UsageAggregates wraps
    (Microsoft.Commerce/UsageAggregates, api-version 2015-06-01-preview), called through Invoke-AzRestMethod with the
    subscription in the request path (new in this revision, see below). The window is worked out once per run and the billing phase collects that same window: a direct run computes it
    before the check; Run-AllSubscriptions.ps1 computes it before its check and passes it to every ResourceInventory.ps1 it starts
    (internal parameters -ConsumptionWindowStart and -ConsumptionWindowEnd, as yyyy-MM-dd), so a subscription collected after
    midnight still collects the window that was checked. A subscription passes when at least one usage row has a quantity above zero;
    pages are followed until one is found, for at most 50 pages. Reaching 50 pages without one counts as only zero quantities, and the
    output says only the first 50 pages were read.
    A direct run with -ResourceGroup checks that resource group: only usage rows whose resource is in it count (the same test the
    billing phase uses to keep rows for such a run), the resource count is of that resource group, and the messages name it.
    That test now compares the name after /subscriptions/<id>/resourceGroups/ (new in this revision). Before, it looked for
    /<name>/ anywhere in the resource URI, so for resource group web a usage row of
    /subscriptions/<id>/resourceGroups/prod/providers/Microsoft.Web/sites/web/slots/staging counted: the check could pass on another
    resource group's usage, and the billing phase put that row in the web sheet. Main's billing phase has the same expression.
    Under -ResourceGroup the billing phase now skips a usage row without a resource URI, instead of stopping that subscription's
    consumption collection with an error.
    A subscription that holds resources but returns no usage above zero (a new subscription, only free resources, paused resources)
    passes with a yellow warning (outcome NoUsage) when the role check found the usage permission at the subscription or above
    in both answers. The warning names the role and scope, the window, the typical causes, and that the subscription's
    consumption sheet will be empty; both scripts list these subscriptions again at the end of the run. The exit code is unchanged.
    When the 50-page limit was reached, the warning and the end-of-run list say only that no usage above zero was found in the first
    50 pages, not that the sheet will be empty (the billing phase reads every page).
    Otherwise zero rows, only zero quantities, a permission error, or an error that persists after bounded retries (throttling,
    timeouts, 5xx; backoff 2, 4, 8 s; a 400 is not retried) stops the run. Subscriptions with no resources are not checked (no usage
    to read); the role check has already confirmed they are readable.

8 subscriptions at a time

Both checks now run up to 8 subscriptions at a time (ForEach-Object -Parallel -ThrottleLimit 8, the pattern
Extension/Metrics.ps1 uses) and print their lines in subscription order, as before. Nothing in the parallel part reads or changes
the Azure context: every request names its subscription. The role check already did. The usage check used to switch the process
context to each subscription for Get-UsageAggregates, which reads the subscription of the current context, and Az has no supported
way to build a context for another subscription without selecting it for the whole process. It now calls the API the cmdlet wraps,
with the same parameters, and asks for the next page with the continuation token from nextLink, as the cmdlet does. Retries
(backoff 2, 4, 8 s), the 50-page limit and the verdicts are unchanged; the billing phase still uses the cmdlet. Each role definition
is still read once per run (a definition not yet read is read under a lock). A subscription whose check fails unexpectedly gets a
failing record (not readable, or Error for the usage check) instead of being left out. Neither check changes the saved default
subscription.

Stops, and the stop this revision removes

Removed in this revision: a subscription the identity cannot read no longer stops the run. It is skipped: listed with its reason
and the fix right after the check, and again at the end of the run, because the report does not contain it; the other subscriptions
are collected. This was Run-AllSubscriptions.ps1 -AllowPartialAccess; it is now the default in the wrapper and in a direct run of
ResourceInventory.ps1 over every visible subscription (a direct run also leaves the skipped subscription out of its subscription
list and out of the resources Resource Graph returned for it). Skipping does not change the exit code: as with -AllowPartialAccess
before, a run whose collected subscriptions all succeed exits 0. I decided this.

The remaining stops end the run with exit code 1, before any inventory or metrics work, listing every failing subscription with its
reason and the fix. A report without read access or without usage values is incomplete. A run stops when:

  • Role check (with or without -SkipConsumption): no checked subscription is readable. Not readable means the two answers do
    not both show read access - both say no; role assignments are not visible and Azure says no; the two answers disagree; an answer is
    still missing after retries; or, for a direct -ResourceGroup run, the resource group is not found. A direct run with
    -SubscriptionID checks only that subscription, so it stops when that one is not readable. An identity with Reader on only part
    of a subscription therefore gets that subscription skipped (or a direct run of it stopped) instead of a partial report. On
    -Resume only the subscriptions still to do are checked; when none of them is readable, -Resume stops only if no subscription
    in the run is recorded as completed (latest update, see below). A run without -Resume stops whenever none of the subscriptions
    it checks is readable.
  • Role check, a role that leaves out some resource types (new in this revision): no single role at the subscription or above
    (or, for a direct -ResourceGroup run, at that resource group) allows reading resources without a not-action that removes reads
    of some resource types. A not-action counts when, with * standing for any characters (including /) and ignoring case, it can
    match an action that ends in /read: without a *, when it ends in /read; with a *, when the text after its last * is empty,
    is the end of /read (read, ad, d) or itself ends in /read. So */read, Microsoft.Compute/*, Microsoft.Comp*,
    Microsoft.Compute/*/r*, *ad and Microsoft.Compute/virtualMachines/read count, and Microsoft.Compute/*/delete, */write
    and Microsoft.Compute/*rea do not. A not-action is allowed when the text before its first * (or all of it) starts with
    Microsoft.Authorization/, Microsoft.Commerce/, Microsoft.Consumption/ or Microsoft.Billing/: Microsoft.Authorization/* is
    allowed, but Microsoft.Auth*, which can also match other namespaces, counts. Two narrower roles that together cover every resource type
    do not count either. Such a subscription is not readable, so it is skipped like any other (in this revision; before, it stopped
    the run). I decided this: a report that silently misses whole resource types is incomplete.
  • Usage check (only when consumption is requested, for the readable subscriptions; unchanged in this revision): the usage query is refused for lack of permission (Denied); fails after the
    retries (Error); or returns no rows (NoRows) or only zero quantities (NoPositiveQuantity, including 50 pages without a value)
    while the usage permission was not found by both role-check answers (for example role assignments not visible, the answers
    disagreeing, or the permission granted only on a resource group). For a direct -ResourceGroup run this now applies to that
    resource group's usage rows: a run whose resource group has no usage above zero stops (before this revision it passed when other
    resource groups of the subscription had usage), unless the usage permission is confirmed by both answers, in which case it passes
    with the NoUsage warning. I decided this too.

Bypasses: -SkipConsumption skips the usage check (and the collection of consumption data). The role check has no bypass.
-AllowPartialAccess is still accepted, so existing command lines keep working, but skipping is now the default and the switch
changes nothing.

Cost

Per subscription, the role check makes 2 Azure calls (the role assignment list, plus pages up to 1000, and Azure's effective
permissions; 3 for a direct -ResourceGroup run with consumption) and reads each distinct role definition once per run. The usage
check makes one Resource Graph count query per 1,000 subscriptions, then, for each subscription with resources, usage pages until a
value above zero is found (usually 1, at most 50). A -ResourceGroup run looks for a value in that resource group, so on a
subscription with much usage elsewhere it can read more of those 50 pages. Both checks run up to 8 subscriptions at a time.

Measured live, normal user sign-in (Owner), the 3 subscriptions of a small test tenant, Run-AllSubscriptions.ps1 -SkipMetrics,
two runs each, check time read from the console timestamps:

role check usage check
previous head, one subscription after another 6.6 s, 3.9 s (0.8-3.5 s per subscription) 4.6 s, 4.6 s (1.9-2.4 s per subscription)
this revision, 8 at a time 4.3 s, 5.6 s 1.8 s, 1.3 s (0.7-1.4 s per subscription)

With 3 subscriptions the role check gains little: each parallel runspace first loads Az.Accounts and this tool's functions, about
2-3 s, once per runspace. The wrapper process held 231 MB at the end of the checks before and 250-252 MB with this revision (3
runspaces); its peak over the whole run was the same before and after, 261-266 MB.

Offline, with stand-ins that take 1.0 s per Azure call and one role definition shared by all subscriptions:

Subscriptions Role check before Role check now Usage check before Usage check now Peak memory before / now
3 8.3 s 4.4 s 7.1 s 2.1 s 153 / 165 MB
8 18.3 s 4.4 s 17.1 s 2.2 s 168 / 194 MB
32 66.4 s 10.4 s 65.2 s 5.2 s 205 / 220 MB
100 202.8 s 28.5 s 201.4 s 14.2 s 207 / 248 MB

Before, the usage check also switched the context once per subscription (counted as one Azure call). At most 8 Azure calls were
in flight at any time, and the per-subscription results were the same before and after for every size. The stand-in memory figures
leave out loading Az.Accounts in each runspace.

Projected from these numbers, not measured: each round of 8 subscriptions takes about one subscription's check time. With the live
per-subscription times above (role check 0.8-1.8 s after the first subscription, usage check 0.7-1.4 s, plus about 3 s to start
the runspaces), about 100 subscriptions wait roughly 25-50 s for both checks before the run starts (one after another:
about 4.5-7 minutes), and about 1,000 subscriptions roughly 3.5-7 minutes (one after another: about 45-70 minutes). Azure throttling
at that scale was not tested; throttled calls are retried with backoff (2, 4, 8 s). The role check cannot be skipped;
-SkipConsumption skips the usage check.

Replaces Get-ConsumptionAccessOutcome, Test-ConsumptionAccess, Get-SubscriptionAccessState and Test-SubscriptionAccessAll;
the shared checks live in Functions/Common.Functions.ps1. README: required roles (Reader at the subscription or above; Reader and
Billing Reader include the usage permission, Cost Management Reader does not), the two checks, the wait after a role change, and
troubleshooting entries.

Consumption sheet: usage dates and window (previous update)

The previous update adds two changes to the consumption sheet (Consumption_ResourcesReport_<timestamp>.csv). It does not change
the checks. Elsewhere in this description, "this revision" means the revision before the previous update.

  • Usage dates are the same text on every host. GetResorceConsumption sets the en-US culture and left UsageStartTime and
    UsageEndTime as DateTime values, so Export-Csv wrote them with the culture's own date and time pattern. That pattern comes
    from the host's culture data. On Linux .NET reads it from ICU; with the ICU of the test host (ICU 74, PowerShell 7.6) the en-US
    time pattern has a narrow no-break space (U+202F) before AM/PM, so the host wrote 10/1/2026 12:00:00<U+202F>AM (seen live
    on main on that Linux host, in every usage date). Both dates are now formatted as M/d/yyyy h:mm:ss tt with the invariant culture: 10/1/2026 12:00:00 AM, with a
    plain space, on every host. The clock value is written as it came from Get-UsageAggregates, with no time-zone conversion, as
    before. docs/consumption-data.md states the format.
  • The window comes from the UTC date. Get-ConsumptionWindow took the window from the host's local date, so the same moment
    gave windows a day apart on hosts in different time zones. In a live run at 00:55 UTC on 28 October, a host at UTC-7 collected
    26 September to 26 October and a host at UTC 27 September to 27 October; each sheet matched Azure for its own window. Usage
    days are UTC days. The default clock is now [datetime]::UtcNow, so every host collects the same days at the same moment. The
    window is still midnight 31 days ago to midnight yesterday, sent with Kind=Unspecified as before, and the up-front check and
    the billing phase still share the one window each run computes (Run-AllSubscriptions.ps1 still passes it to every
    ResourceInventory.ps1 it starts). The README and docs/consumption-data.md say the dates are UTC dates.

No column, exit code or stop is added or changed, and there are no extra Azure calls.

-Resume when every subscription left to check is not readable (latest update)

On -Resume the role check leaves out the subscriptions the resume state records as completed: an earlier run wrote their
reports. Before this update, when every subscription it did check was not readable, the run stopped with exit 1, for example after
a run that was interrupted while it collected a subscription the identity can no longer read. Each later -Resume stopped the same
way, so the run never finished and the resume state was never cleared.

What changes, exactly:

  • -Resume no longer stops when at least one subscription in the run is recorded as completed and every subscription it
    checks is not readable. Recorded as completed means the subscriptions this run skips as already completed: in the resume state
    and in this run's scope. The run lists each unreadable subscription with its reason right after the check and again at the end of
    the run, skips it, and finishes with nothing left to collect, as a run that skips some unreadable subscriptions does: the exit
    code is the one the run would have without the skipped subscriptions (0 for a clean run), and the resume state is cleared when
    nothing failed and nothing is left on the retry list. A subscription skipped because its check could not finish, or because its
    two answers disagree, is put on the retry list (see below), so the state is kept for it. The check prints:

      1 subscription(s) are NOT readable by the signed-in identity:
        - <subscription-name> (<subscription-id>) - no read access (role assignments not visible to this identity)
      Skipping them and finishing the run: the other 1 subscription(s) were completed by an earlier run, so nothing is left to collect. To include them: Grant the identity Reader on these subscriptions, then re-run.
    
  • That run uses one stream, whatever -ParallelStreams is, also when the value is chosen automatically (for example 2 on a
    host with 4 vCPU). The sequential loop skips the completed subscriptions; the parallel streams and the path for a single
    subscription left do not read the list of completed subscriptions, so with 2 or more streams they collected them again, without
    a role check in this run. The Parallelism: line says why:

    Parallelism: -ParallelStreams 1 (nothing is left to collect, so one stream instead of the 2 chosen automatically), -ConcurrencyLimit 8 (auto).
    

    With -ParallelStreams passed it ends ... instead of the 2 passed), .... In both cases RunSummary.log lists the streams
    as 1 (nothing left to collect). When one stream was passed or chosen already, nothing is reduced: the Parallelism: line and
    RunSummary.log keep explicit or auto.

    When that run clears the resume state, it also deletes the per-stream state files an interrupted parallel run left
    (.resume-state-<tenant>-stream-<N>.json). A -Resume folds those files in at startup and leaves them for the merge at the end
    of a parallel run, which deletes them; with one stream that merge does not run, so the run printed Resume state cleared (clean run). with the files still on disk, and every later -Resume recovered and skipped their subscriptions again. It deletes only
    the files it read; one it could not read is moved aside instead (see below). When the run keeps the state (a subscription is
    still on the retry list), it keeps those files too, as any one-stream -Resume does.

  • A run without -Resume still stops with exit 1 when none of the subscriptions it checks is readable, also when the resume
    state records completed subscriptions (without -Resume they are checked like the others). Its lines are unchanged.

  • -Resume with no subscription in the run recorded as completed still stops with exit 1. The fix now ends in running
    -Resume again, and a last line says that a run without -Resume checks the same subscriptions (with nothing recorded as
    completed, it does). When every subscription has no read role, the line adds that such a run stops too; when a check could not
    finish, or the two answers disagree after a role change, a later run can pass, so the line says only the first part. Granting
    Reader and running -Resume again collects them and clears the state.

      1 subscription(s) are NOT readable by the signed-in identity:
        - <subscription-name> (<subscription-id>) - no read access (role assignments not visible to this identity)
      No subscription is readable. Stopping before any work. Grant the identity Reader on these subscriptions, then run -Resume again.
      A run without -Resume checks the same subscriptions, so it stops here too.
    

    For a check that could not finish:

      No subscription is readable. Stopping before any work. The role check could not finish (the reason above says why); run -Resume again.
      A run without -Resume checks the same subscriptions.
    
  • A skipped subscription on the retry list is named under Pending Retries. When a run that ends with no new failure has
    subscriptions on the retry list (FailedAttempts) and its role check skipped some of them as not readable, the end of the run
    names them with their reason and gives the fix for each cause, as the start of the run does, ending in running
    -ResumeFailedOnly: grant Reader (no read role), run it again (the check could not finish), or wait 5 minutes (the two answers
    disagree, usually right after a role change). -ResumeFailedOnly runs the same check before it retries, so until the cause is
    fixed it skips them, and when they are all it has to retry it stops with exit 1. Its exit codes are unchanged. The first line
    now says on the retry list (FailedAttempts) instead of from a prior run still in FailedAttempts, because a subscription this
    run skipped can be on it (next bullet):

    Pending Retries:         1 subscription(s) on the retry list (FailedAttempts)
      1 of them were skipped by this run's role check:
        - <subscription-name> (<subscription-id>) - no read access (role assignments not visible to this identity)
      To retry them: Grant the identity Reader on these subscriptions, then run -ResumeFailedOnly.
    Re-run with -ResumeFailedOnly to retry them.
    

    With several causes the fixes are one line per cause, naming the subscriptions:

      To retry them:
        <subscription-name>: Grant the identity Reader on these subscriptions, then run -ResumeFailedOnly.
        <subscription-name>: The role check could not finish (the reason above says why); run -ResumeFailedOnly.
    
  • A subscription skipped for a cause that can pass later stays on the retry list. When the role check skips a subscription
    because its check could not finish (Unknown, for example an answer still missing after retries) or because the two answers
    disagree (Disagree, usually right after a role change), the run puts it on the retry list (FailedAttempts) as a failed run,
    with the reason skipped by the up-front role check: <reason>, and takes it off the completed list. It does this also when the
    run stops because nothing it checks is readable: the failed run is recorded before the exit. A subscription skipped because the
    identity has no read role is not put on the retry list (it needs Reader first). So the resume state is kept, every -Resume and
    -ResumeFailedOnly checks it again, each such run adds one to its count, and the run that collects it takes it off the list.
    The exit codes are unchanged: the run ends with the code it would have without the skipped subscription, and -ResumeFailedOnly
    still stops with exit 1 when nothing on its retry list is readable. The retry list is written into the state file with every
    other key it holds kept as it is. A separate change that stops retrying a subscription after 3 failed runs in a row ends these
    retries: the third such run reaches the limit, and the next -Resume prints Not retried: <name> (<id>) failed 3 runs in a row; last reason: skipped by the up-front role check: ... and clears the state once nothing else is pending (a -ResumeFailedOnly
    instead prints ResumeFailedOnly: nothing left to retry; ... and exits 0; the next -Resume after the state is cleared starts
    with no state and checks the subscription again). Without that limit, a subscription whose check keeps failing
    keeps the state, and every -Resume and -ResumeFailedOnly checks it and lists it again.

    Pending Retries:         1 subscription(s) on the retry list (FailedAttempts)
      1 of them were skipped by this run's role check:
        - <subscription-name> (<subscription-id>) - role check inconclusive after retries (caller permissions: HTTP 429)
      To retry them: The role check could not finish (the reason above says why); run -ResumeFailedOnly.
    Re-run with -ResumeFailedOnly to retry them.
    
  • A per-stream state file that cannot be read is moved aside. A -Resume or -ResumeFailedOnly run folds in the per-stream
    state files an interrupted parallel run left. One that could not be parsed (an interrupted write can leave it cut short) was
    skipped with a verbose message only: none of its records were used, a -Resume with nothing left to collect deleted it while
    printing Resume state cleared (clean run)., and with one stream it stayed and was read again, silently, by every later
    -Resume. Now the
    run prints a warning naming the file (never its content), renames it in place to <name>.unreadable-<yyyyMMdd-HHmmss> (UTC) and
    keeps it for inspection. Its records are not used: the subscriptions it listed are not counted as completed, so a -Resume run
    collects them again, those it can read; -ResumeFailedOnly retries only its retry list, so after it a later -Resume collects
    them, and its warning says so. The renamed file does not end in .json and does not match the pattern for per-stream files, so no
    later run reads it, and neither the wrapper's zips nor a zip step that takes *.json files picks it up. The run never prints
    Resume state cleared (clean run).; a run that reaches its end prints a last state line saying whether the state was cleared or
    kept and where the file went. A run that ends early, for example -ResumeFailedOnly with nothing to retry or a run that stops
    with exit 1, prints no such line; the warning at the start is then the only line about the file. The state is cleared or kept by
    the usual rule (cleared when nothing failed and nothing is left on the retry list): the run collected
    again what the file listed and nothing reads the moved file, so keeping the state would only make the next -Resume skip what this
    run collected. When it clears the state, it also deletes the per-stream files it read, so the next -Resume starts with no state.

    WARNING: The per-stream state file .resume-state-<tenant>-stream-1.json from an interrupted parallel run could not be read, so its records are not used: the subscriptions it lists are not counted as completed and this run collects them again. It was moved aside to .resume-state-<tenant>-stream-1.json.unreadable-20261029-140255.
    ...
    Resume state cleared, but not a clean run: the per-stream state file .resume-state-<tenant>-stream-1.json could not be read and was moved aside to .resume-state-<tenant>-stream-1.json.unreadable-20261029-140255; its records were not used.
    

    Under -ResumeFailedOnly the warning ends ... the subscriptions it lists are not counted as completed and a later -Resume collects them (-ResumeFailedOnly retries only the retry list). It was moved aside to .... When the state is kept, the last line starts
    Resume state kept, but not a clean run: .... If the rename fails, the run now stops (see the strict-mode update below):
    ERROR: The per-stream state file <name> could not be read, and it could not be moved aside: <reason>, named with the command
    that removes it, and exit 1 before it collects anything.

  • A resume state file that cannot be removed is named, and the run does not say it cleared the state. At the end of a run
    that clears the resume state, the per-stream state files it read and the resume state file were removed with Remove-Item,
    whose errors do not stop the script, so the run printed Resume state cleared (clean run). even when a file stayed on disk (for
    example with the inventory root read-only, seen with all three files left). Now the per-stream files are removed first, then the
    resume state file, each with -ErrorAction Stop, and each is checked to be gone (Remove-ResumeStateFiles). A file that is left
    gets a warning naming it and the reason, and the run does not print the clean-run line. While a per-stream file is left, the
    resume state file is kept too, so the next -Resume reads the same state and that file again; the warning asks for the named
    files to be removed once the folder can be written, because only some runs remove per-stream files (a -Resume with nothing
    left to collect, one that moved a file aside, and the merge at the end of a parallel run; see Limitations). The exit codes are
    unchanged.

    WARNING: Could not remove the per-stream state file .resume-state-<tenant>-stream-0.json: Access to the path '<inventory root>/.resume-state-<tenant>-stream-0.json' is denied.
      The resume state file .resume-state-<tenant>.json is kept, so the next -Resume reads the same state and the per-stream state file(s) above again. Once the folder can be written, remove the file(s) named above.
    

    When the resume state file itself cannot be removed: WARNING: Could not remove the resume state file <name>: <reason>, then
    The next run reads it again and retries the removal. The end-of-run clean-up of a parallel run, which deletes the per-stream
    files after merging them, is described in the strict-mode update below.

On this branch alone a -Resume run builds its consolidated zip only from the reports it writes, so when nothing is left to
collect it prints No per-subscription zip files found under <inventory root> to consolidate., leaves the earlier reports in their
folders and clears the state, as a -Resume whose every subscription is already completed does. With #48 the run carries the
earlier reports into its consolidated zip. With #48 and #62, two -Resume runs in a row both end with exit 0 and no resume state,
after a sequential or a parallel interruption: the first carries the reports the interrupted run wrote and clears the resume state,
per-stream files included, and the second, which finds no state, collects those subscriptions again.

The unreadable subscriptions are named only in the console output and the wrapper's transcript; no report zip holds them, with or
without -Obfuscate. No script parameter is added, no exit code is added except the exit 1 for a per-stream file that cannot be
moved aside (strict-mode update below), and there are no extra Azure calls: Resolve-AccessPreflight
takes the number of completed subscriptions in scope (-CompletedCount), Write-AccessPreflightReport takes -Resume for the
words, and Write-PendingRetrySkippedSummary prints the Pending Retries lines; both take the fix for each cause from
Write-AccessRemedyLines, so the fixes read the same. Add-RoleCheckRetryAttempts and Update-ResumeStateRetryList keep the
retry list, and Move-UnreadableStreamStateFile and Write-UnreadableStreamStateSummary handle a per-stream file that cannot be
read; Remove-ResumeStateFiles removes the resume state files with a check. The README's parallel section describes a
per-stream file that cannot be read and a resume state file that cannot be removed, and its role-check section describes the
-Resume case, and its paragraph on roles that leave out some resource types now says such a subscription is not readable (it is
skipped, as the paragraph's last sentence says) instead of saying it stops the run.

Strict mode and per-stream resume files (November 2026 update)

  • Strict mode. An ARM page without a nextLink, a check result without Failed, a failed call's status, and a usage row
    without additionalInfo are now read safely under Set-StrictMode -Version Latest, so a caller running strict mode no longer
    stops the run. The consumption sheet is byte for byte the same.
  • A per-stream file that cannot be read is moved aside at the end of the run too. The end-of-run merge of a parallel run
    does what the start of a -Resume run does: it warns, renames the file to <name>.unreadable-<UTC time> (with -2, -3 and
    so on when that name is taken), and a later -Resume collects its subscriptions.
  • A file that cannot be moved aside stops the run. It is left alone and named with the command that removes it. At the start
    of -Resume or -ResumeFailedOnly the run stops there with exit 1, before it collects anything. Found by the end-of-run
    merge, the run ends with exit 1 in place of 0 and 3-5 (exit 2 keeps its code). The README's parallel section and exit code
    table say so.
  • Stream files are removed only once the resume state holds their records. The end-of-run merge keeps a per-stream file
    whose records were not saved, or that cannot be removed, and compares whole entries when it reads the state back. The writer
    of the retry list stops on any write error, so a file cut short never replaces the state.
  • The per-stream file's shape is checked. Its lists must be lists, with entries of the written shape (a null entry as
    written is fine); each retry entry needs a LastFailedAt date; a null or empty completed id makes the file unreadable.
  • A run that ends early after moving a file aside still says it was not a clean run, and says nothing about unreadable files when
    there are none.

Tested: new Tests/StreamStateFileRead.Tests.ps1 and Tests/StrictModeArmPages.Tests.ps1, and new cases in the existing
files; full Pester suite, test by test, with no new failure; PSScriptAnalyzer one file at a time, with no new finding. Live
runs, plain and with -Obfuscate, were made with this PR on top of the Az PowerShell-only PR (#66), because the test host has
no Azure CLI; inventory, consumption and metrics were the same as that base. Not run live against main, and not run on
Windows.

Testing

  • New Pester tests for the role check (role evaluation, scopes, the combination of the two answers, retries, call sites,
    -AllowPartialAccess, -Resume, end-of-run labels) and for the usage values check (verdicts, paging, page cap, retries, window,
    empty subscriptions, failure message, the NoUsage pass for each combination of the two role-check answers, the end-of-run list,
    both call sites passing the role-check results); they fail against the code before each change and pass on this branch.
    The tests that pin unchanged stops (Denied, Error, and no usage without both answers) pass before and after the second commit.

  • Tests added in this revision: a role that leaves out some resource types (each not-action form, the allowed namespaces, not-actions
    that are not reads, Reader beside such a role, both answers, the wrapper with and without -AllowPartialAccess, a direct run),
    the fix text per cause, the 1000-page limit of the role assignment list, a refused role definition read once per run, one window
    per run (written culture-independently, invalid values ignored with a warning, a collection after midnight, all three places the
    wrapper starts ResourceInventory.ps1), resource group runs (rows of other resource groups, matching without case, the resource
    group count and exemption, an invalid name, a usage row without a resource URI, direct runs) and the wording at the 50-page
    limit. Against the previous head 82 of them fail and 7 pass; the 7 pin behaviour that is meant to stay (Reader beside a narrower
    role, the fix text for no access, not visible and resource group not found, reading a role definition again after a server
    error, and every place the wrapper starts ResourceInventory.ps1 passing the same argument set).

  • Tests added or changed in this revision:

    • the resource group test against resources of another resource group whose names equal it (a web app slot, a SQL server, a
      provider namespace) and against URIs that are not resource URIs: all fail on the previous head and pass now;
    • the usage API call: the request path and query, the token taken from nextLink, an answer outside 2xx with Azure's message
      (403 Denied, 400 not retried, 429 and 503 retried), and malformed answers (a 200 that is not JSON, a nextLink that is not a
      URL or has no token), each stopping that subscription;
    • UpFrontChecksParallel.Tests.ps1: the same stand-in answers checked one at a time and 8 at a time give the same records,
      results and lines; two subscriptions checked at the same time each get their own usage answer; the lines stay in subscription
      order when an earlier subscription finishes last; a shared role definition is read once; nothing that runs in parallel can
      call a context cmdlet; a check that throws becomes a failing record;
    • skipping: the wrapper and a direct run skip an unreadable subscription, list it with the fix, list it again at the end, and stop
      with exit 1 when none is readable; a direct run leaves the skipped subscription's resources out;
    • the role check's next page: a nextLink that names another host is asked for by its path and query, with no request to that
      host; a nextLink that is not a URL, is a relative path, is not http(s), has no path or a path starting with // counts as a
      missing answer, and that subscription is skipped with the reason while the other is collected; the 1000-page limit and a lower
      page limit still end the list, each page asked for by its path. All fail on the previous head and pass now. Live, a resource
      list of 12 pages read through the role check's request function gave the same resource ids as following nextLink directly,
      every page asked for by its path.
      The tests that expected the old stop (an unreadable subscription stopping the run, the -AllowPartialAccess hint) now expect the
      skip. The usage tests that replaced Get-UsageAggregates and Set-AzContext now replace the usage API call, with the same
      expected outcomes.
  • The test of the direct script's last lines still requires the no-usage and skipped-subscription lists right after the report
    and zip logging, and now also accepts Report: name failed collectors, count consolidated subscriptions #51's exit 4 check after them (its comment lines, the failure count and one exit line,
    nothing else), so it passes with or without Report: name failed collectors, count consolidated subscriptions #51.

  • Full suite: the same set of failures before and after this change (none added); lint clean on every changed script.
    Previous revision: 413 passed / 162 failed / 22 skipped before, 500 / 162 / 22 after, the same 162 failures (pre-existing, in
    other test files). This revision: 500 passed / 162 failed / 22 skipped before, 544 / 162 / 22 after, the same failures.
    Previous update: 544 / 162 / 22 before, 550 / 162 / 22 after, the same 162 failures by name; lint clean on every changed script.
    Latest update: 550 / 162 / 22 before, 604 / 162 / 22 after, the same 162 failures by name; lint clean on every changed file.

  • Tests added in the previous update: in ConsumptionDataCheck.Tests.ps1, the usage date text (M/d/yyyy h:mm:ss tt with a plain
    space and no non-ASCII byte in the file; the same clock value for every DateTime kind); and ConsumptionWindowClock.Tests.ps1
    (with no clock passed the window is taken from the UTC date; two child pwsh processes with TZ=Pacific/Kiritimati (UTC+14) and
    TZ=Pacific/Pago_Pago (UTC-11), whose local dates always differ, get the same window; a clock that is passed still decides the
    window; the up-front check's default window is still Get-ConsumptionWindow). The two-zone test is skipped on Windows, where
    TZ does not set a process's time zone. Against the previous head 3 of the 6 fail: both date tests (on a host whose en-US time
    pattern has U+202F, Linux here) and the two-zone test. The other 3 pass before and after: a passed clock, the up-front check's
    default, and the default clock on a host that runs at UTC.

  • Tests added in the latest update, in ReaderAccessCheck.Tests.ps1: the rule (Resolve-AccessPreflight with and without
    completed subscriptions in scope); the words (-Resume with nothing left to collect, a -Resume stop with one cause and with
    three, and the last line for each cause); the Pending Retries lines (Write-PendingRetrySkippedSummary for each cause and for
    mixed causes, and where the wrapper calls it); the helpers for the retry list and for a per-stream file that cannot be read
    (Add-RoleCheckRetryAttempts, Update-ResumeStateRetryList keeping other keys, Move-UnreadableStreamStateFile including a
    rename that fails and the -ResumeFailedOnly words, Write-UnreadableStreamStateSummary, and Remove-ResumeStateFiles with a
    removal that fails, a per-stream file that fails, and a file still there after the removal); the wrapper's check block (a subscription whose check could not finish,
    or whose answers disagree, put on the retry list, also before a stop and taken off the completed list; none without a read role,
    and no state written when nothing is skipped for such a cause); (-Resume with a completed subscription and the rest unreadable, a stop without -Resume
    although the state records completed subscriptions, a -Resume stop when the only completed subscription is out of scope); and
    runs of Run-AllSubscriptions.ps1 itself, each its own pwsh process, with stand-ins for ResourceInventory.ps1 and Azure:
    after an interrupted run, two -Resume runs in a row end with exit 0, list the skipped subscription, clear the state, and the
    first ends its output like a -Resume with nothing left to collect; a run without -Resume stops; a -Resume with no completed
    subscription stops with the new words, a run without -Resume then stops too, and after Reader is granted -Resume collects the
    subscription and clears the state; under -Obfuscate no zip (every entry opened, nested zips too) holds the skipped
    subscription's id or name; with -ParallelStreams 2 and with the automatic value (the process is given 4 vCPU with
    DOTNET_PROCESSOR_COUNT), after one completed subscription and after three (a two-stream run, then -Resume), the finish case
    prints the one-stream Parallelism: line, skips every completed subscription (no Processing subscription: or [stream-N] processing line for them) and leaves no resume state; and a subscription on the retry list that can no longer be read is named
    under Pending Retries by a run without -Resume and by -Resume, -ResumeFailedOnly still stops with exit 1 until Reader is
    granted, then retries it and clears the state; and after a two-stream run whose session ended while it collected the last
    subscription, which then cannot be read, -Resume with -ParallelStreams 2, the automatic value and -ParallelStreams 1
    recovers the per-stream state, skips both completed subscriptions, and leaves no main or per-stream state file, and the next
    -Resume prints no recovery line and collects both again; after such a run whose stream file for one subscription was cut short,
    -Resume with -ParallelStreams 1, 2 and the automatic value prints the warning, moves the file aside, collects that
    subscription again, ends with the cleared-but-not-clean line and no state, and the next -Resume ends clean with no warning and
    no recovery line, and with nothing left to collect the run deletes only the file it read; a subscription whose check cannot
    finish, or whose answers disagree, stays on the retry list through a run without -Resume and then a -Resume, or a
    -ResumeFailedOnly that stops (count 1, 2), then is collected by the same kind of run once its check passes and the state clears;
    one without a read role is not put on it; under -ResumeFailedOnly, a cut-short stream file gets the -ResumeFailedOnly words and
    the next -Resume collects the subscription it named; and with the inventory root made read-only during a -Resume with
    nothing left to collect, the run names both per-stream files it could not remove, keeps the resume state and does not print the
    clean-run line, and the next -Resume, with the folder writable again, ends with Resume state cleared (clean run). and no
    resume state file (that test first checks that a write into the read-only folder is refused, and is skipped when it is not, for
    example as root). If the host's memory makes the automatic value one stream, the
    automatic cases of the earlier test are reported as inconclusive. Against the head before this update (pr-38~7) 49 of the 54 fail: there the end-to-end tests of the finish case, with any
    stream count, fail at the stop, for example Expected $null or empty, but got ' No subscription is readable. Stopping before any work. Grant the identity Reader on these subscriptions, then re-run.' or Expected 0, but got 1. (the exit code), and the
    cut-short and retry-list tests fail, for example with Expected 'Resume state cleared (clean run).' to not be found in collection. The 5 that pass pin behaviour that is meant to stay: the two stops without -Resume, the -Obfuscate case with a
    readable subscription left, no retry-list entry for a subscription without a read role, and no state written when nothing is
    skipped for a cause that can pass later. Against the first commit of this update (pr-38~6) 41 fail; the cases with 2 streams
    and the automatic value fail there, for example with Expected 'Processing subscription: Sub A (sub-a)' to not be found in collection (one completed subscription) or Expected 'Skipping (already completed): Sub A (sub-a)' to be found in collection
    (three completed, or an interrupted parallel run). Against the second (pr-38~5) 31 fail, and against the third (pr-38~4) 23:
    the cut-short stream file, for example Expected 1, but got 0. for the warning line, the retry list, for example Expected 'sub-c|1|skipped by the up-front role check: role check inconclusive after retries (caller permissions: HTTP 429)', but got $null., and the new first Pending Retries line. Against the sixth (pr-38~1) 6 fail: the -ResumeFailedOnly words of the
    warning, the removal helper (The term 'Remove-ResumeStateFiles' is not recognized ...), and the read-only folder, where that
    commit printed the clean-run line with the files still there (Expected 'Resume state cleared (clean run).' to not be found in collection).

  • ConsumptionDataCheck.Tests.ps1: the direct-run tests start ResourceInventory.ps1 from the repository root, as those in
    ReaderAccessCheck.Tests.ps1 do. ResourceInventory.ps1 reads ./Version.json from the current folder and ends with exit 0
    without it, so 4 of them failed when Pester was started from another folder (98 / 4 from /tmp before, 102 / 0 from /tmp and
    from the repository root now).

  • With Carry earlier reports into the -Resume bundle #48 and Keep the resume state while -ResumeFailedOnly leaves a subscription not collected #62 merged (with and without Keep the -Resume completed-ids list an array #49), Keep the resume state while -ResumeFailedOnly leaves a subscription not collected #62's ResumeStateNotReadable.Tests.ps1 passes 8 of 8; its two tests of a
    -Resume with only unreadable subscriptions left failed before this update. On the same merges, the finish case with
    -ParallelStreams 2 and with the automatic value carries every earlier report into the consolidated zip and collects none of
    those subscriptions again, after one, two (with Keep the -Resume completed-ids list an array #49) and three completed subscriptions; after an interrupted two-stream run it
    carries both reports, leaves no main or per-stream state file, and the next -Resume recovers nothing and collects both again
    (also after the removal failed once with the folder read-only);
    after such a run whose stream file for one subscription was cut short, the first -Resume (one stream, two, automatic) carries
    the report recorded in the file it read, collects the other subscription again, and ends with no state, and the second ends
    clean. With the retry limit of 3 failed runs merged as well, a subscription whose check keeps failing (Unknown or Disagree)
    is skipped and counted by a run without -Resume, by -Resume and by a stopped -ResumeFailedOnly, is no longer retried after
    the third, and the next -Resume clears the state; no zip holds its id, name or retry reason under -Obfuscate.

  • Live, the same two changes on a Linux host (a test branch that also carries other fixes, the small test tenant, default
    settings): every usage date value had a plain space and no other non-ASCII character, and a run under
    TZ=America/Los_Angeles at 04:21 UTC, when the Los Angeles date was still the day before, collected the same window as the
    UTC run (27 September to 27 October). This branch itself was not run live.

  • Live in this revision, normal user sign-in (Owner), the 3 subscriptions of a small test tenant, Run-AllSubscriptions.ps1 -SkipMetrics (consumption on), previous head and this revision, two runs each: the same verdicts (all 3 readable; 2 with usage
    values, 4 and 534 rows on the first page; 1 with no resources, not checked), the same 3 subscriptions processed, 11,037 resources
    and 538 consumption records, and exit 4 in all four runs from the scale set collector failure fixed in Fix VMSS collector failing on Flexible scale sets #39. The saved default
    subscription did not change. Check times are under Cost.

  • Skipping an unreadable subscription was not tested live (it needs a second identity). Offline, with the wrapper's own statements
    from the up-front check to the exit code, the real ResourceInventory.ps1, and stand-ins for Azure, 3 subscriptions with 1
    unreadable: both skip it and list it after the check, the wrapper lists it again at the end, both collect the other 2, and the
    wrapper exits 0, as -AllowPartialAccess did on the previous head. All 3 unreadable, or a direct run whose -SubscriptionID is
    unreadable: exit 1. A readable subscription with no usage values whose usage permission only Azure confirms: exit 1, as before.
    With -AllowPartialAccess: the same as without it.

  • Live, on a test subscription, with one test service principal whose role was changed between runs (previous revisions; in
    this revision the rows that stopped with "no read access" skip that subscription instead, and stop with exit 1 only because it is
    the only one):

    Role of the identity Result with this change
    can only see the subscription exit 1 in both scripts: no read access
    Reader at the subscription both checks pass; same records and usage rows as without the change
    Reader without Microsoft.Commerce/* role check passes; exit 1: no usage rows, fix text shown
    Reader on one resource group whole-subscription run: exit 1; -ResourceGroup run: passes and collects that group
    Billing Reader only exit 1: no read access, "Billing Reader at subscription" listed
    Reader without Microsoft.Authorization/* passes on Azure's answer (role assignments not visible)
  • Live, normal user sign-in (Owner), on an otherwise empty test subscription holding one network security group (free, so no usage):

    Code Command Result
    first commit of this PR ResourceInventory.ps1 -SubscriptionID <that subscription> exit 1 before any inventory: [NoRows] <subscription-name> - the query succeeded but returned no usage rows
    this branch same exit 0: [NoUsage] warning naming Owner at subscription, the run completes, the subscription is listed again at the end
    this branch Run-AllSubscriptions.ps1 on the tenant (this subscription and two with usage) all three pass the checks (one NoUsage) and are processed; the summary lists the NoUsage subscription; exit 4 from the scale set collector failure fixed in Fix VMSS collector failing on Flexible scale sets #39

    Not run on main for this case.

  • Live, normal user sign-in (Owner), direct runs with -ResourceGroup on a test subscription whose only usage comes from one
    resource in another resource group:

    Code Command Result
    previous head ResourceInventory.ps1 -SubscriptionID <that subscription> -ResourceGroup <new group with one network security group> exit 0; the check passes on usage from the other resource group: [Pass] <subscription-name> - usage values found (4 row(s) read over 1 page(s)); the consumption sheet has 0 rows
    this revision same exit 0: [NoUsage] <subscription-name> - the query succeeded but returned no usage rows for resource group '<new group>'; the usage permission is confirmed by the role assignments and by Azure (Owner at subscription) and the warning that this resource group's sheet will be empty; the run completes; 0 rows
    this revision ... -ResourceGroup <group that holds the resource with usage> exit 0: [Pass] <subscription-name> - usage values found for resource group '<group>' (4 row(s) read over 1 page(s)); the consumption sheet has 4 rows

    Seen live without the change: the identity that can only see the subscription got exit 0 and an empty report from both scripts,
    and on main the identity without Microsoft.Commerce/* got "Consumption access confirmed", "Records found: 0" and an empty
    consumption sheet.

  • With a normal user sign-in (Owner) on a small tenant: both checks pass for every subscription and the run completes; 20
    back-to-back readings of both answers agreed every time. The usage check also passed under UTC, Los Angeles and Sydney time zones.

Limitations

  • Not reproduced: a partner-managed (CSP) subscription where the partner hides cost data. If the identity's roles there include the
    usage permission in both answers, it now passes with the NoUsage warning (empty consumption sheet) instead of stopping; otherwise
    it stops with NoRows. Not tested; the warning and the README troubleshooting entry mention it.
  • Not testable on the test tenant: roles inherited from a management group or the tenant root, PIM-activated roles, deny
    assignments, role conditions, and access delegated from another tenant (Azure Lighthouse). The group-membership path was verified
    live separately and is covered by a unit test.
  • Right after a role change, the two answers can briefly disagree; the subscription is then not readable, so it is skipped (the run
    stops when it is the only one), and the list asks to wait and re-run.
  • Tested offline only in this revision: a role that leaves out some resource types (making one means changing a role assignment on
    the test tenant, which was not done for this revision), a run crossing midnight, the 50-page limit wording, the fix text per cause,
    the role assignment list limit and the refused role definition read. Only the resource group runs were repeated live.
  • An identity that reads only through narrower custom roles (for example one role per resource provider, or Microsoft.*/read)
    instead of a role with */read is treated as unable to read that subscription, so the subscription is skipped (the run stops when
    no subscription is readable), where main collects what those roles can read. Add Reader instead.
  • The allowed namespaces were checked against the inventory's queries (none reads a type of those namespaces), and live with a
    normal user sign-in: Resource Graph's resources table held no row of those namespaces across every visible subscription, and a
    management lock created on a test resource group did not appear there within 3 minutes (the lock was then removed).
  • Not tested live in this revision: skipping an unreadable subscription (needs a second identity) and more than 3 subscriptions;
    the times for 100 and 1,000 subscriptions are projections. A direct run's end-of-run list of skipped subscriptions is covered by a
    unit test and a check that the script ends with it, not by an offline run to the end.
  • The usage check calls the usage API directly instead of through Get-UsageAggregates. The dates are sent as UTC midnights; in the
    live runs above it returned the same first-page rows (4 and 534) as the cmdlet did for the same window.
  • This revision conflicts with Memory 1/4: write the inventory per collector and release its data #41 in ResourceInventory.ps1: both add lines right after ResourceInventoryAvd. Keep both, the
    skipped-resource filter first, so Memory 1/4: write the inventory per collector and release its data #41's resource count leaves the skipped subscriptions out.
  • The -Resume change of the latest update was not tested against Azure: it needs an identity that loses read access to a
    subscription between two runs. Its end-to-end tests run the wrapper with -ParallelStreams 1, 2 and the automatic value.
  • With -ParallelStreams 2 or more (also when it is chosen automatically), any other -Resume run still gives the subscriptions
    recorded as completed to the parallel streams, or to the path for a single subscription left, which collect them again: they read
    only each stream's own state file from an interrupted parallel run, not the main resume state. This happens when readable
    subscriptions are left to collect, and when every subscription in scope is already completed and none was skipped as not
    readable. It is the same on main; this PR does not change it. Only the case this PR adds, where every subscription left to check
    is not readable, runs one stream and skips them.
  • Any other run with one stream after an interrupted parallel run, -Resume (readable subscriptions left, -ParallelStreams 1)
    or -ResumeFailedOnly (its retry list, collected one at a time), clears the main resume state at its end but leaves the
    per-stream state files it read, so every later -Resume prints Recovered per-stream state from an interrupted parallel run and
    skips the subscriptions they list again. It is the same on main; this PR does not change it. The finish case this PR adds, and
    a run that moved a per-stream file aside, delete the files they read when they clear the state, and keep them when they keep the
    state.
  • The merge at the end of a parallel run deletes each per-stream state file without checking that it is gone, so when a removal
    fails it can still print Resume state cleared (clean run)., and a later -Resume recovers that file again. It is the same on
    main; this PR does not change that merge. The clean-up this PR adds checks each removal and names any file it could not remove.
  • On Windows, Build-MainSummaryFromZip.ps1 -PackageZip with -OutputDirectory set to the inventory root zips every file there,
    the resume state file and a per-stream file moved aside included (a leading dot does not hide a file on Windows). It is the same
    on main for the resume state file; this PR does not change that script. On Linux neither file is taken. The open PR Zip only the summary and this call's report folders with -PackageZip #67
    limits that zip to the summary and the report folders the call reconstructs.
  • -ResumeFailedOnly whose retry list holds only subscriptions without a read role still stops with exit 1 on every run until
    Reader is granted; those runs are not counted toward a retry limit. Only skips for a cause that can pass later are counted.
  • The Recovered per-stream state from an interrupted parallel run: N completed, M failed subscription record(s). line counts the
    empty failure entry each stream file holds when nothing failed, so it can say 2 failed when nothing failed. It is the same on
    main; this PR does not change it.
  • Not run on Windows. The usage date and window changes were run live on a Linux host only (UTC and Los Angeles); a host east of
    UTC only offline (the two-zone test). Not run on macOS.

How to test

Quick check (no Azure)

Needs PowerShell 7 and Pester 5 (Install-Module Pester -MinimumVersion 5.0 -Scope CurrentUser).
The tests define their own stand-ins for the Az cmdlets they call (Get-AzContext, Set-AzContext, Get-AzAccessToken, Invoke-AzRestMethod), so no Azure sign-in is needed. UpFrontChecksParallel.Tests.ps1 writes a small stand-in module to its test folder, so the checks' parallel runspaces load it instead of Az.

From the repository root:

git fetch origin main pull/38/head:pr-38
TESTS="ReaderAccessCheck ConsumptionDataCheck RunAllSubscriptionsReconciliation UpFrontChecksParallel ConsumptionWindowClock"

# main's code with this PR's test files
git worktree add ../rda-main origin/main
git -C ../rda-main checkout pr-38 -- Tests/ReaderAccessCheck.Tests.ps1 Tests/ConsumptionDataCheck.Tests.ps1 Tests/RunAllSubscriptionsReconciliation.Tests.ps1 Tests/UpFrontChecksParallel.Tests.ps1 Tests/ConsumptionWindowClock.Tests.ps1
(cd ../rda-main && for t in $TESTS; do pwsh -NoProfile -Command "Invoke-Pester -Path ./Tests/$t.Tests.ps1 -Output Detailed"; done)
git worktree remove --force ../rda-main

# this PR
git checkout pr-38
for t in $TESTS; do pwsh -NoProfile -Command "Invoke-Pester -Path ./Tests/$t.Tests.ps1 -Output Detailed"; done
Test file main this branch
ReaderAccessCheck.Tests.ps1 Tests Passed: 2, Failed: 220 Tests Passed: 222, Failed: 0
ConsumptionDataCheck.Tests.ps1 Tests Passed: 0, Failed: 102 Tests Passed: 102, Failed: 0
RunAllSubscriptionsReconciliation.Tests.ps1 Tests Passed: 32, Failed: 4 Tests Passed: 36, Failed: 0
UpFrontChecksParallel.Tests.ps1 Tests Passed: 0, Failed: 8 Tests Passed: 8, Failed: 0
ConsumptionWindowClock.Tests.ps1 Tests Passed: 0, Failed: 4 Tests Passed: 4, Failed: 0

On main:

  • ReaderAccessCheck: the role check does not exist, so most tests fail with The term 'Get-RoleCheckAction' is not recognized as a name of a cmdlet, function, script file, or executable program. (or the same for another role-check function), and the call-site tests fail because ResourceInventory.ps1 and Run-AllSubscriptions.ps1 never call it.
    The 2 that pass cover runs where no check is expected (-RunAllSubs, and -ResourceGroup without -SubscriptionID).
  • ConsumptionDataCheck: stops in setup with Expected function 'Get-ConsumptionWindow' to be defined by Functions/Common.Functions.ps1.
  • RunAllSubscriptionsReconciliation: no longer defines the first-subscription consumption gate fails with Expected $null or empty, but got Get-ConsumptionAccessOutcome.
    The three Resolve-AccessPreflight tests about skipping fail too, because main stops on any unreadable subscription, for example
    Expected $false, because the run skips the unreadable sub and collects the readable one, but got $true.
  • UpFrontChecksParallel: stops in setup with The term 'Get-ConsumptionWindow' is not recognized as a name of a cmdlet, function, script file, or executable program.
  • ConsumptionWindowClock: the same message for Get-ConsumptionWindow, and the two-zone test fails with Expected '14', because the child must really run at UTC+14, but got $null.

Usage dates and window (no Azure)

The two consumption-sheet changes of the previous update, against the head before that update (pr-38~9). The date tests in
ConsumptionDataCheck.Tests.ps1 show the date text; on the Linux test host both fail on that head, the first with
Expected strings to be the same, but they were different. (the text has U+202F before AM). The window, on Linux:

git checkout --detach pr-38~9      # the head before that update; then again with: git checkout pr-38
for z in Pacific/Kiritimati Pacific/Pago_Pago; do TZ=$z pwsh -NoProfile -Command '. ./Functions/Common.Functions.ps1; Format-ConsumptionWindow -Window (Get-ConsumptionWindow)' < /dev/null; done

At 12:57 UTC on 28 October that head printed 2026-09-28 to 2026-10-28 and 2026-09-27 to 2026-10-27 (the hosts' local
dates); this branch printed 2026-09-27 to 2026-10-27 twice (the UTC date). The two zones are 25 hours apart, so on that head the
lines always differ by one or two days.

-Resume with only unreadable subscriptions left (no Azure)

The latest update (seven commits), against the head before it (pr-38~7), with this PR's ReaderAccessCheck.Tests.ps1:

git worktree add ../rda-prev pr-38~7
git -C ../rda-prev checkout pr-38 -- Tests/ReaderAccessCheck.Tests.ps1
(cd ../rda-prev && pwsh -NoProfile -Command "Invoke-Pester -Path ./Tests/ReaderAccessCheck.Tests.ps1 -Output Detailed")
git worktree remove --force ../rda-prev
git checkout pr-38
pwsh -NoProfile -Command "Invoke-Pester -Path ./Tests/ReaderAccessCheck.Tests.ps1 -Output Detailed"

The head before the update gives Tests Passed: 173, Failed: 49 and this branch Tests Passed: 222, Failed: 0. The end-to-end tests
start Run-AllSubscriptions.ps1 as its own pwsh process from a copy of the tool in the temp folder, with stand-ins for
ResourceInventory.ps1 and Azure, and are skipped on Windows; the cases with 2 streams and the automatic value take a few
seconds more each, and the interrupted parallel runs end their first run themselves once both streams have recorded a completed
subscription; the cut-short case then removes the last } from one stream file. On the head before the update the first of them fails with
Expected $null or empty, but got ' No subscription is readable. Stopping before any work. Grant the identity Reader on these subscriptions, then re-run.'.
(Not run exactly as written: the two commits were tested from exported copies instead of a git worktree.)

Reproduce on Azure (test subscription)

No cost: a service principal and custom roles are free, and the runs only read.
Needs the Azure CLI and PowerShell 7 with the Az modules, signed in as yourself with rights to create app registrations and role assignments (for example Owner) on the test subscription.
The test identity signs in under a throwaway home folder, so your own sign-ins are not touched.
After every role change, wait about 5 minutes before running (role changes take a few minutes to apply).
For the Reader control in step 6 the subscription needs some usage in the last 31 days (any resource that has run).

  1. Create the test identity and two custom roles:

    SUB=<subscription-id>; TENANT=<tenant-id>
    APP_ID=$(az ad app create --display-name rda-access-test --query appId -o tsv)
    az ad sp create --id "$APP_ID"
    SECRET=$(az ad app credential reset --id "$APP_ID" --end-date "$(date -u -d '+12 hours' +%Y-%m-%dT%H:%M:%SZ)" --query password -o tsv)
    az role definition create --role-definition '{"Name": "RDA test - subscription read only", "Actions": ["Microsoft.Resources/subscriptions/read"], "NotActions": [], "AssignableScopes": ["/subscriptions/<subscription-id>"]}'
    az role definition create --role-definition '{"Name": "RDA test - Reader without Commerce", "Actions": ["*/read"], "NotActions": ["Microsoft.Commerce/*"], "AssignableScopes": ["/subscriptions/<subscription-id>"]}'

    (Not run exactly as written: the identity, secret and roles were created with equivalent commands that were not recorded verbatim, under other names.)

  2. A helper that runs a command as the test identity (bash):

    TESTHOME=$(mktemp -d)
    MODS=$(pwsh -NoProfile -Command '$env:PSModulePath')     # keep your installed Az modules visible under the new home
    asid() { env HOME="$TESTHOME" AZURE_CONFIG_DIR="$TESTHOME/.azure" PSModulePath="$MODS" "$@"; }
    signin() {
      asid az login --service-principal --username "$APP_ID" --password="$SECRET" --tenant "$TENANT" --output none
      asid pwsh -NoProfile -Command "Connect-AzAccount -ServicePrincipal -Tenant '$TENANT' -Credential ([pscredential]::new('$APP_ID', (ConvertTo-SecureString '$SECRET' -AsPlainText -Force))) | Out-Null"
    }

    Run signin again after each role change. If it reports that no subscriptions were found, the role has not applied yet; wait and retry.
    (Not run exactly as written: the sign-in used the same two logins in a throwaway home folder, from a longer script.)

  3. Read access, identity that can only see the subscription:

    az role assignment create --assignee "$APP_ID" --role "RDA test - subscription read only" --scope "/subscriptions/$SUB"
    # wait ~5 minutes, then
    signin
    asid pwsh -NoProfile -File ./Run-AllSubscriptions.ps1 -TenantID "$TENANT" < /dev/null; echo "exit $?"
    asid pwsh -NoProfile -File ./ResourceInventory.ps1 -TenantID "$TENANT" -SubscriptionID "$SUB" < /dev/null; echo "exit $?"

    Run the two tool commands from the repository root, once with main checked out (git checkout --detach origin/main) and once on this branch (git checkout pr-38).

    On main both scripts end with exit 0 and an empty report. The wrapper's existing check passes, because Azure answers the resource-group list with an empty list instead of refusing:

    Access verified: all 1 in-scope subscription(s) are readable.
    ...
    Total resources:  across 0 service type(s)
    GENUINELY EMPTY (1) - access confirmed, the subscription has no resources:
    

    (The main part was not run exactly as written: these lines come from runs of an earlier commit of this change whose wrapper access check is main's code unchanged; a direct run on main has no up-front check at all.)

    On this branch both scripts stop before any inventory work with exit 1, because the only subscription is not readable:

    Verifying subscription access up front for 1 subscription(s)...
      [NoAccess] <subscription-name> - no read access (role assignments not visible to this identity) (<n>s)
          usage permission (Microsoft.Commerce/UsageAggregates/read): no - Azure does not report it (role assignments are not visible to this identity)
      1 subscription(s) are NOT readable by the signed-in identity:
        - <subscription-name> (<subscription-id>) - no read access (role assignments not visible to this identity)
      No subscription is readable. Stopping before any work. Grant the identity Reader on these subscriptions, then re-run.
    

    With more than one subscription in scope, the ones that are not readable are listed the same way, followed by
    Skipping them and continuing with the <n> readable subscription(s). To include them: ..., and the run continues; they are listed
    again at the end under Subscriptions skipped (not readable by the signed-in identity).
    (Not run exactly as written: step 3 was run live on an earlier commit of this change, which printed the same lines with
    Stopping before any work. ... instead of No subscription is readable. Stopping before any work. ...; this revision's lines
    come from the offline runs and tests.)

  4. Usage values, identity with Reader minus Microsoft.Commerce/*:

    az role assignment delete --assignee "$APP_ID" --role "RDA test - subscription read only" --scope "/subscriptions/$SUB"
    az role assignment create --assignee "$APP_ID" --role "RDA test - Reader without Commerce" --scope "/subscriptions/$SUB"
    # wait ~5 minutes, then
    signin

    On main (git checkout --detach origin/main), run the wrapper:

    asid pwsh -NoProfile -File ./Run-AllSubscriptions.ps1 -TenantID "$TENANT" < /dev/null; echo "exit $?"

    Nothing fails: the usage API answers this identity with success and zero rows, and the existing check treats that as access.

    Verifying consumption (billing) access using subscription '<subscription-name>'...
    Consumption access confirmed.
    ...
    Records found: 0...
    

    The run completes with no error about usage data: Consumption_ResourcesReport_<timestamp>.csv holds only its header line and the end summary has no consumption line.
    (The recorded run ended with exit 4, which came from the unrelated scale set collector failure fixed in Fix VMSS collector failing on Flexible scale sets #39.)

  5. Same identity on this branch (git checkout pr-38), direct run:

    asid pwsh -NoProfile -File ./ResourceInventory.ps1 -TenantID "$TENANT" -SubscriptionID "$SUB" < /dev/null; echo "exit $?"

    The role check passes and the usage values check stops the run with exit 1, before any inventory work:

    Verifying subscription access up front for 1 subscription(s)...
      [Pass] <subscription-name> - Read access: RDA test - Reader without Commerce (custom role) at subscription (<n>s)
          usage permission (Microsoft.Commerce/UsageAggregates/read): no - the roles on this subscription do not include it
      Access verified: all 1 in-scope subscription(s) are readable.
    Verifying consumption data (usage values for <start-date> to <end-date>) for 1 subscription(s)...
      [NoRows] <subscription-name> - the query succeeded but returned no usage rows (<n>s)
    ERROR: Consumption data was requested (no -SkipConsumption), but 1 of 1 checked subscription(s) returned no usage values for <start-date> to <end-date>.
      - <subscription-name> (<subscription-id>): NoRows - the query succeeded but returned no usage rows; window <start-date> to <end-date>
    Usage permission found by the role check:
      - <subscription-name>: the roles on this subscription do not include Microsoft.Commerce/UsageAggregates/read: add Reader or Billing Reader at the subscription
    

    The wrapper (Run-AllSubscriptions.ps1 -TenantID "$TENANT") runs the same two checks before its own work.
    (Not run exactly as written for the wrapper: with this identity it was run on an earlier commit of this change, where it stopped with the same [NoRows] refusal and exit 1.)

  6. Control, built-in Reader on the subscription, this branch:

    az role assignment delete --assignee "$APP_ID" --role "RDA test - Reader without Commerce" --scope "/subscriptions/$SUB"
    az role assignment create --assignee "$APP_ID" --role Reader --scope "/subscriptions/$SUB"
    # wait ~5 minutes, then
    signin
    asid pwsh -NoProfile -File ./ResourceInventory.ps1 -TenantID "$TENANT" -SubscriptionID "$SUB" < /dev/null; echo "exit $?"

    Both checks pass and the run continues:

    Verifying subscription access up front for 1 subscription(s)...
      [Pass] <subscription-name> - Read access: Reader at subscription (<n>s)
          usage permission (Microsoft.Commerce/UsageAggregates/read): yes - Reader at subscription
      Access verified: all 1 in-scope subscription(s) are readable.
    Verifying consumption data (usage values for <start-date> to <end-date>) for 1 subscription(s)...
      [Pass] <subscription-name> - usage values found (<n> row(s) read over 1 page(s)) (<n>s)
    Consumption data confirmed: 1 subscription(s) returned usage values for <start-date> to <end-date>.
    

    The run ends with exit 0. Run the same command on main: the inventory records and the consumption rows are the same.
    (Not run exactly as written: the recorded comparison was against an earlier commit of this change instead of main.)

  7. Zero usage with the usage permission confirmed, signed in as yourself (Owner or Reader at the subscription), this branch.
    Use a test subscription with no resources and no usage, and add one network security group (free):

    RG=rda-zero-usage-test
    az group create --subscription "$SUB" -n "$RG" -l eastus
    az network nsg create --subscription "$SUB" -g "$RG" -n rda-zero-usage-nsg
    az graph query -q "resources | where subscriptionId == '$SUB' | count" --subscriptions "$SUB" --query "data[0].Count"   # wait until 1
    pwsh -NoProfile -File ./ResourceInventory.ps1 -TenantID "$TENANT" -SubscriptionID "$SUB" < /dev/null; echo "exit $?"

    The usage check passes the subscription with a yellow warning and the run continues:

    Verifying subscription access up front for 1 subscription(s)...
      [Pass] <subscription-name> - Read access: Owner at subscription (<n>s)
          usage permission (Microsoft.Commerce/UsageAggregates/read): yes - Owner at subscription
      Access verified: all 1 in-scope subscription(s) are readable.
    Verifying consumption data (usage values for <start-date> to <end-date>) for 1 subscription(s)...
      [NoUsage] <subscription-name> - the query succeeded but returned no usage rows; the usage permission is confirmed by the role assignments and by Azure (Owner at subscription) (<n>s)
          WARNING: no usage above zero for <start-date> to <end-date>. Typical causes: a new subscription, only free resources, or paused resources. The run continues; this subscription's consumption sheet will be empty.
    1 subscription(s) returned no usage values for <start-date> to <end-date> and continue with an empty consumption sheet, because the role check confirmed the usage permission (see the warnings above).
    

    At the end of the run:

    Subscriptions with no usage values: 1 - the usage permission was confirmed, but no usage above zero came back for <start-date> to <end-date>, so their consumption sheet is empty:
      - <subscription-name> (<subscription-id>)
      Typical causes: a new subscription, only free resources, or paused resources. If usage was expected, the subscription may be partner-managed (CSP) without cost visibility for this identity.
    

    The run ends with exit 0. On the first commit of this PR the same command stopped with exit 1 and
    [NoRows] <subscription-name> - the query succeeded but returned no usage rows.
    If the subscription has never used Microsoft.Network, the CLI registers that resource provider first (free).
    (Not run exactly as written: the resource group name had a UTC timestamp suffix, and the resource count was read from the
    query's JSON output instead of with --query.)

    Clean up: az group delete --subscription "$SUB" -n "$RG" --yes, then az group exists --subscription "$SUB" -n "$RG" prints
    false.

    Resource group run, signed in as yourself, this branch. Use a subscription that has usage in one resource group
    (<group-with-usage>) and add a new resource group with one network security group (free):

    RG2=rda-rg-usage-test
    az group create --subscription "$SUB" -n "$RG2" -l eastus
    az network nsg create --subscription "$SUB" -g "$RG2" -n rda-rg-usage-nsg
    az graph query -q "resources | where resourceGroup == '$RG2' | count" --subscriptions "$SUB" --query "data[0].Count"   # wait until 1
    pwsh -NoProfile -File ./ResourceInventory.ps1 -TenantID "$TENANT" -SubscriptionID "$SUB" -ResourceGroup "$RG2" < /dev/null; echo "exit $?"
    pwsh -NoProfile -File ./ResourceInventory.ps1 -TenantID "$TENANT" -SubscriptionID "$SUB" -ResourceGroup "<group-with-usage>" < /dev/null; echo "exit $?"

    The first run passes the resource group with a yellow warning and completes; its consumption sheet has no rows:

    Verifying consumption data (usage values for <start-date> to <end-date>) for resource group 'rda-rg-usage-test' in 1 subscription(s)...
      [NoUsage] <subscription-name> - the query succeeded but returned no usage rows for resource group 'rda-rg-usage-test'; the usage permission is confirmed by the role assignments and by Azure (Owner at subscription) (<n>s)
          WARNING: no usage above zero in resource group 'rda-rg-usage-test' for <start-date> to <end-date>. Typical causes: new resources, only free resources, or paused resources. The run continues; the consumption sheet for resource group 'rda-rg-usage-test' will be empty.
    

    The second passes with [Pass] <subscription-name> - usage values found for resource group '<group-with-usage>' (<n> row(s) read over 1 page(s))
    and its consumption sheet has rows. On the previous head of this PR the first run printed
    [Pass] <subscription-name> - usage values found (<n> row(s) read over 1 page(s)) from usage elsewhere in the subscription and
    wrote an empty consumption sheet.
    (Not run exactly as written: the resource group name had a UTC timestamp suffix, and the resource count was read with a
    summarize count() query.)

    Clean up: az group delete --subscription "$SUB" -n "$RG2" --yes, then az group exists --subscription "$SUB" -n "$RG2" prints
    false.

  8. Clean up (signed in as yourself):

    az role assignment delete --assignee "$APP_ID" --scope "/subscriptions/$SUB"
    az role definition delete --name "RDA test - subscription read only" --scope "/subscriptions/$SUB"
    az role definition delete --name "RDA test - Reader without Commerce" --scope "/subscriptions/$SUB"
    APP_OBJ=$(az ad app show --id "$APP_ID" --query id -o tsv)
    SP_OBJ=$(az ad sp show --id "$APP_ID" --query id -o tsv)
    az ad app delete --id "$APP_ID"                  # also removes its service principal
    az rest --method DELETE --url "https://graph.microsoft.com/v1.0/directory/deletedItems/$APP_OBJ"   # purge from deleted items
    az rest --method DELETE --url "https://graph.microsoft.com/v1.0/directory/deletedItems/$SP_OBJ"
    az role assignment list --assignee "$APP_ID" --all --query "length(@)"    # 0
    az role definition list --custom-role-only --scope "/subscriptions/$SUB" --query "[?starts_with(roleName, 'RDA test')] | length(@)"   # 0
    find "$TESTHOME" -mindepth 1 -delete && rmdir "$TESTHOME"   # the test identity's sign-in and reports

    (Not run exactly as written: the same objects were removed, purged and each checked with a fresh query, using equivalent commands that were not recorded verbatim.)

What to look for

  • The exit code and the up-front check lines at the start of the console output: on this branch a subscription that is not readable is named with the reason and the fix and skipped (exit 1 before any inventory output when none is readable), and a missing usage permission ends the run with exit 1 and names the subscription, the reason and the fix, before any inventory output is written.
  • After an interrupted run whose remaining subscriptions the identity cannot read: -Resume lists them, prints Skipping them and finishing the run: ..., then Parallelism: -ParallelStreams 1 (nothing is left to collect, ...) when more than one stream
    was asked for or chosen, skips each completed subscription and ends instead of stopping; with no completed subscription it stops
    and says to run -Resume again.
  • A subscription on the retry list that the identity can no longer read: the Pending Retries lines at the end name it with its
    reason and the fix for that cause before -ResumeFailedOnly.
  • After an interrupted parallel run whose per-stream state file was cut short: the next -Resume prints WARNING: The per-stream state file ... could not be read ..., a .resume-state-*-stream-*.json.unreadable-* file is left in InventoryReports, the
    subscriptions that file listed are collected again, and the run ends with Resume state cleared, but not a clean run: ...; the
    -Resume after it prints no warning and ends with Resume state cleared (clean run).
  • A subscription whose role check cannot finish, or whose two answers disagree: it is under Pending Retries at the end, the
    state file keeps it in FailedAttempts with Attempts one higher after each run that skips it, also after a -ResumeFailedOnly
    that stops with exit 1.
  • A resume state file that cannot be removed at the end (for example a read-only InventoryReports): a WARNING: Could not remove ... line names it, and there is no Resume state cleared (clean run)..
  • After an interrupted parallel run that left only unreadable subscriptions: the first -Resume prints Recovered per-stream state ... and Resume state cleared (clean run)., and no .resume-state-* file is left in InventoryReports; the next -Resume
    prints no recovery line.
  • A subscription with no usage whose usage permission both answers confirm: a yellow [NoUsage] line with the role and scope, the WARNING: no usage above zero ... line, the run continues, and the subscription is listed again under Subscriptions with no usage values at the end.
  • Consumption_ResourcesReport_<timestamp>.csv: on main, the identity without Microsoft.Commerce/* gets a file with only the header line and no error; on this branch that run does not start.
  • A direct -ResourceGroup run: the usage lines name the resource group, and a pass needs usage in that resource group.
  • For the identity that can only see the subscription, Inventory_ResourcesReport_<timestamp>.json on main has no records and the wrapper labels the subscription GENUINELY EMPTY; on this branch the run stops before any inventory file is written.

Peter-John Morgenrood added 5 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.
Extension/Metrics.ps1 builds a request definition for every metric of
the estate before it makes the first Azure Monitor call and keeps all of
them until the metrics phase ends. Each one was a 14-property
[PSCustomObject] of about 2,640 bytes, so 80,000 attached disks (320,000
definitions) held about 806 MiB before any call. With a 2,600 MiB memory
limit such a run ran out of memory while building them and wrote no
metrics.

- Add RdaMetricDefinition, a PowerShell class with the same 14 fields,
  and build every definition with it (all 41 places). One definition now
  takes about 185 bytes: about 56 MiB for the same 320,000.
- The fields are untyped, so a missing value stays $null; a [string]
  field would turn it into ''. Definitions are created on the main
  thread only; the parallel workers just read their properties.
- The output is unchanged: definitions are only read for their values,
  never serialised. For every resource type the script defines metrics
  for, with and without obfuscation and across two output files, the
  metrics files match the previous version record for record and field
  for field.
- Add Tests/MetricDefinitions.Tests.ps1, which runs the real Metrics.ps1
  against a deterministic stand-in for Get-AzMetric with no Azure calls:
  every definition is an RdaMetricDefinition, a missing subscription
  name stays $null, the output files match
  Tests/Fixtures/MetricDefinitions.Output.json (recorded from the
  previous version), and 40,000 disk definitions take under 1,000 bytes
  each (about 240 here, about 2,640 before).
Every Azure Monitor call adds a diagnostics record to $MetricDiagnostics.
Only the summary at the end of the metrics phase reads these records,
but they were kept for the whole phase, so memory grew with the number
of calls. With a stand-in Get-AzMetric, retained heap grew by 99 MB
over 40,000 calls (about 2.5 KB per call); with this change it grows by
9 MB, and no longer with the number of calls.

- After each batch, once all of its parallel calls have finished, fold
  the batch's records on the main thread into running state that holds
  what the summary prints: the call total, the count per outcome, every
  non-success record and the five slowest records. Then clear the
  collection. Metric results are already written out and cleared per
  batch in the same way.
- The per-batch verbose line and the summary read that running state.
- Output is unchanged: the verbose lines, the summary lines and the
  metrics files are the same as before for the same calls. Calls with
  equal rounded durations were, and still are, listed in no fixed order.
- Add Tests/MetricsDiagnostics.Tests.ps1. It runs Metrics.ps1 over 800
  calls (four batches) against a stand-in Get-AzMetric with throttled,
  invalid-metric-name, empty and slow calls, and checks the verbose
  lines, the outcome counts (including a status seen only in the first
  batch), the non-success and slowest lists across batches, that
  nothing is returned to the pipeline, and that the call records are
  not all kept until the end of the phase. A second case checks the
  summary when there are no metric definitions.
Two kinds of missing access went unnoticed and produced a report that
looked complete:

- Get-UsageAggregates answers an identity that lacks
  Microsoft.Commerce/UsageAggregates/read with success and zero rows.
  The previous gate probed only the first subscription for one day and
  treated "no error" as access, so runs could finish with an empty
  consumption sheet.
- The Reader check listed the subscription's resource groups. Azure
  filters that list to what the caller may see instead of refusing, so
  an identity that can read nothing passed and the run ended with an
  empty report. Direct runs of ResourceInventory.ps1 had no check.

Before any inventory or metrics work, Run-AllSubscriptions.ps1 and
direct runs of ResourceInventory.ps1 now check every subscription the
run will process. Under -RunAllSubs the inner script does not repeat
the checks; on -Resume only the remaining subscriptions are checked.

- Role check: the identity's own role assignments (assignedTo, so
  group grants count) and their role definitions, combined with
  Azure's caller-permissions answer (Microsoft.Authorization/
  permissions). Read access needs */read that the same role's
  notActions do not remove; for a -ResourceGroup run a role on that
  resource group is enough. A disagreement, or an answer still missing
  after retries, stops the run. When role assignments are not visible
  to the identity, the caller-permissions answer decides. Whether the
  roles allow reading usage is reported for information.
- Usage values check, when consumption is requested: same cmdlet,
  options and 31-day window as the billing phase (one helper,
  Get-ConsumptionWindow). A subscription passes when at least one usage
  row has a quantity above zero. Zero rows, only zero quantities, a
  permission error, or an error that persists after bounded retries
  stops the run. Subscriptions with no resources are not checked.

A stop is exit code 1 with every failing subscription and the fix.
-AllowPartialAccess skips subscriptions that fail the role check and
does not bypass the usage check. The context switch for the usage
check is process-scoped, so the saved default subscription is not
changed.

The shared checks live in Functions/Common.Functions.ps1 and replace
Get-ConsumptionAccessOutcome, Test-ConsumptionAccess,
Get-SubscriptionAccessState and Test-SubscriptionAccessAll.
Peter-John Morgenrood added 5 commits October 27, 2026 14:47
…n is confirmed; cap usage paging

A subscription that holds resources but has no usage above zero in the
31-day window (a new subscription, only free resources such as network
security groups, paused resources) stopped the run with NoRows or
NoPositiveQuantity, although nothing was wrong with access.

The consumption data check now takes the up-front role check records
(new optional -RoleCheck parameter of Invoke-ConsumptionDataCheck; both
Run-AllSubscriptions.ps1 and direct runs of ResourceInventory.ps1 pass
them). When the outcome would be NoRows or NoPositiveQuantity and the
role check found Microsoft.Commerce/UsageAggregates/read at the
subscription or above in BOTH answers (the identity's role assignments
and Azure's caller permissions), the subscription passes with the new
outcome NoUsage. It is printed in yellow with the role and scope, the
window, the typical causes and that its consumption sheet will be
empty, and it is listed again at the end of the run by both scripts
(Write-NoUsageSummary). Exit codes and parameters are unchanged.

Everything else still stops with exit 1 as before: Denied, Error, and
NoRows/NoPositiveQuantity when the usage permission was confirmed by
only one answer, by neither, with role assignments not visible, only
below the subscription, or when no role check record exists for the
subscription.

Invoke-ConsumptionValueProbe followed ContinuationToken without a
limit. It now stops after -MaxPages pages (default 50, as
Invoke-RoleCheckGet in the same file). Reaching the cap without a row
above zero is NoPositiveQuantity, and the detail says only the first N
pages were read, so the rule above applies to it.

README and docs/consumption-data.md describe the new pass and what
still stops. The direct-run test that expects exit 1 on zero usage now
uses role assignments that are not visible, because with Reader in both
answers that run now passes with a warning.
The -RunAllSubs direct-run test now also asserts that the inner script makes
no usage (Get-UsageAggregates) and no resource-count call, so it fails if the
usage check runs under -RunAllSubs. The test title is updated to match.
'does not keep every call record until the end of the phase' read
$MetricDiagnostics.Count once, after the phase, so code that folded and
cleared the records only after the last batch would still pass.

The test now records how many call records are held each time the script
dispatches the next batch and when it ends the phase, which is once after
each of the four batches, and expects 0 every time. It does this by
wrapping Write-RdaProgress in the scope the script runs in; the wrapper
passes every call on unchanged.
… front

- Read access now needs one role that reads every resource type. A role
  whose notActions remove reads of some resource types (a not-action ending
  in '*' or 'read', outside Microsoft.Authorization, Microsoft.Commerce,
  Microsoft.Consumption and Microsoft.Billing) no longer counts, because
  Resource Graph leaves those resources out without an error. The stop
  reason names the role and the excluded pattern; in Run-AllSubscriptions.ps1
  -AllowPartialAccess skips such a subscription.
- The consumption window is computed once per run. A direct run uses it for
  the up-front check and the consumption phase; Run-AllSubscriptions.ps1
  passes it to every ResourceInventory.ps1 it starts (-ConsumptionWindowStart
  and -ConsumptionWindowEnd), so a subscription collected after midnight
  collects the window that was checked.
- A direct -ResourceGroup run checks that resource group: only its usage rows
  count, by the same test the consumption phase keeps rows with
  (Test-ConsumptionResourceUriInResourceGroup), and Resource Graph's count is
  of that resource group.
- When the usage check stops at its 50-page cap, the NoUsage and stop texts
  say only that no usage above zero was found in the pages read.
- The role assignment list is followed for up to 1000 pages, and the stop
  message gives the fix for each cause: grant Reader, re-run, or wait
  5 minutes and re-run.
- A role definition whose read is refused (HTTP 401, 403 or 404) is not read
  again for later subscriptions; after a transient failure it is read again.
A not-action now counts as removing reads of some resource types when, with
'*' standing for any characters (as Test-RoleActionPatternMatch reads it), it
can match an action that ends in '/read': without '*' when it ends in
'/read'; with '*' when the text after its last '*' is empty, is the end of
'/read' or itself ends in '/read'. Patterns such as 'Microsoft.Comp*',
'Microsoft.Compute/*/r*' and '*ad' were missed before. A not-action is
allowed only when the text before its first '*' starts with one of the
allowed namespaces and '/', so 'Microsoft.Authorization/*' stays allowed
and 'Microsoft.Auth*' counts.

Adds a test that a -ResourceGroup collection skips a usage row without a
resource URI and keeps collecting the subscription. The README describes
the rule.
Peter-John Morgenrood added 3 commits October 27, 2026 21:33
Test-ConsumptionResourceUriInResourceGroup looked for '/<name>/' anywhere in
the resource URI, so resource group 'web' also matched
/subscriptions/<id>/resourceGroups/prod/providers/Microsoft.Web/sites/web/slots/staging.
The consumption data check could then pass a -ResourceGroup run on another
resource group's usage, and the consumption phase kept that row in the
resource group's sheet. Compare the name after /subscriptions/<id>/resourceGroups/
instead, without case.
Both up-front checks went through the subscriptions one after another, so
their wall clock grew with every subscription. They now run up to 8
subscriptions at a time with ForEach-Object -Parallel (the pattern
Extension/Metrics.ps1 uses) and print one line per subscription in
subscription order, as before.

Nothing in the parallel part reads or changes the Azure context:
- The role check already named the subscription in every request. Role
  definitions stay cached for the whole run; a definition not yet cached is
  read under the cache's lock, so each is still read once.
- The usage check switched the process context to each subscription for
  Get-UsageAggregates, which reads the subscription of the current context;
  Az has no supported way to build a context for another subscription
  without selecting it for the whole process. The check now calls the API
  the cmdlet wraps (Microsoft.Commerce/UsageAggregates, api-version
  2015-06-01-preview) through Invoke-AzRestMethod, with the subscription in
  the path and the same window and options. The next page is requested with
  the continuation token from nextLink, as the cmdlet does. Retries, the
  50-page cap and the verdicts are unchanged. The consumption phase still
  uses the cmdlet.

A subscription whose check fails unexpectedly gets a failing record
(Unknown, or Error for the usage check) instead of being left out.
-ThrottleLimit 1 runs the checks one subscription at a time in the caller's
runspace; the tests that replace Azure with Pester mocks use it.
A subscription that fails the up-front role check no longer stops the run.
It is skipped: listed with its reason and the fix right after the check, and
again at the end of the run, because the report does not contain it. The
other subscriptions are collected. This was Run-AllSubscriptions.ps1
-AllowPartialAccess; it is now the default in the wrapper and in a direct
ResourceInventory.ps1 run over every visible subscription. A direct run
leaves a skipped subscription out of the consumption check, its subscription
list and the resources Resource Graph returned for it.

When no checked subscription is readable the run still stops with exit 1
before any work, for example a direct run whose -SubscriptionID is not
readable. Skipping does not change the exit code. The consumption data check
is unchanged and only checks the readable subscriptions.

-AllowPartialAccess is still accepted so existing command lines keep
working; it changes nothing.
Peter-John Morgenrood added 2 commits October 27, 2026 23:36
Invoke-RoleCheckGet followed an answer's nextLink with Invoke-AzRestMethod
-Uri, so the next request, and the access token with it, went to whatever
host the answer named. It now asks for the link's path and query with -Path,
on the context's Resource Manager endpoint, as every other call in the file
does. This covers the role assignment list, role definitions and caller
permissions.

A nextLink that is not an absolute http(s) URL, or has no path (or one
starting with '//'), counts as a missing answer: the role check for that
subscription is inconclusive, so the subscription is not readable and is
skipped with that reason. The link itself is not logged. The page cap and its
outcome are unchanged.
…mary

When the direct script also exits 4 for a run that lost a collector, that
check sits after the no-usage and skipped-subscription lists, so the file no
longer ends with the summary call. The test still requires both lists right
after the report and zip logging, in that order, and allows only that exit 4
check (comment lines, the failure count and one exit line) after them, so it
passes with or without the check. The wrapper assertion is unchanged.
Peter-John Morgenrood added 2 commits October 28, 2026 12:58
GetResorceConsumption sets the en-US culture and left UsageStartTime and
UsageEndTime as DateTime values, so Export-Csv wrote them with the
culture's own date and time pattern. That pattern comes from the host's
culture data: on Linux .NET reads it from ICU, and with ICU 74 the en-US
time pattern has a narrow no-break space (U+202F) before AM/PM, so the
same usage row gave different bytes on different hosts.

The two dates are now formatted as 'M/d/yyyy h:mm:ss tt' with the
invariant culture, for example '10/1/2026 12:00:00 AM', with a plain
space. On such a Linux host the only change is U+202F becoming a plain
space. The clock value is written as it came from Get-UsageAggregates,
with no time-zone conversion, as before. docs/consumption-data.md states
the format.
Get-ConsumptionWindow took the window from the host's local date, so the
same moment gave windows a day apart on hosts in different time zones: at
00:55 UTC on 28 October a host at UTC-7 collected 26 September to 26
October and a host at UTC 27 September to 27 October. Usage days are UTC
days.

The default clock is now [datetime]::UtcNow, so every host gets the same
window for the same moment. The window is still midnight 31 days ago to
midnight yesterday, sent with Kind=Unspecified as before. The up-front
consumption check and the billing phase still share the one window each
run computes (Run-AllSubscriptions.ps1 still passes it to every
ResourceInventory.ps1 it starts). The comment, README and
docs/consumption-data.md say the dates are UTC dates.
Peter-John Morgenrood added 5 commits October 29, 2026 10:38
On -Resume the role check leaves out the subscriptions the resume state
records as completed, and it stopped with exit 1 when every subscription
it did check was unreadable. Each later -Resume stopped the same way, so
the run never finished and the resume state was never cleared, although
the reports of the completed subscriptions had been written.

Resolve-AccessPreflight now takes the number of completed subscriptions
in scope (-CompletedCount) and does not stop while it is above 0. The
unreadable subscriptions are skipped and listed after the check and at
the end of the run, as when readable ones are left, and the run finishes
with nothing left to collect. A run without -Resume, and a -Resume run
with no completed subscription in scope, still stop. On such a -Resume
stop the fix ends in running -Resume again, and a last line says that a
run without -Resume checks the same subscriptions and stops too.

No script parameter or exit code is added. Tests: the rule, the wording,
the wrapper's check block, and runs of the wrapper itself with stand-ins
for Azure (two -Resume runs in a row after an interrupted run, the stop
without -Resume, each way out of the -Resume stop, and every zip opened
under -Obfuscate).
When every subscription a -Resume run has left to check is not readable
and the others were completed by an earlier run, the run skips the
unreadable ones and finishes. With -ParallelStreams 2 or more, also when
the value is chosen automatically, it then collected the completed
subscriptions again: the one-subscription path and the parallel streams
do not read the parent's list of completed subscriptions, and these
subscriptions were not part of this run's role check. The run now uses
one stream in that case, so the sequential loop skips them, and the
Parallelism line says why.

A -Resume stop says a run without -Resume stops too only when every
cause is a missing role; a check that could not finish, or answers that
disagree after a role change, can pass on the next run, so for those it
says only that a run without -Resume checks the same subscriptions.

When the role check skipped a subscription that is on the retry list,
the end-of-run Pending Retries lines name it and say Reader must be
granted before -ResumeFailedOnly can retry it. -ResumeFailedOnly itself
is unchanged.

README: a role that leaves out some resource types makes the
subscription not readable (it is skipped, as the paragraph already
ends), and the -Resume paragraph describes the one-stream finish and
the Pending Retries lines.

Tests: the wording for each cause, the Pending Retries helper, and runs
of the wrapper itself with -ParallelStreams 2 and the automatic value
after one and after three completed subscriptions, and with a
subscription on the retry list that can no longer be read.
…lect

A parallel run keeps each stream's progress in its own state file and
merges those files into the resume state at its end, deleting them. A
-Resume run after an interrupted parallel run folds them in at startup
and leaves them for that merge. When nothing is left to collect, the run
uses one stream, so the merge does not run: it printed "Resume state
cleared (clean run)." with the per-stream files still on disk, and every
later -Resume recovered and skipped the same subscriptions again. When
that run clears the resume state, it now also deletes the per-stream
files it folded in, as the merge does, so the next -Resume starts fresh.
Other one-stream -Resume runs keep them, as before.

The Pending Retries lines gave the fix for a missing role whatever the
reason a retry-list subscription was skipped. They now list each with
its reason and give the fix for each cause, ending in running
-ResumeFailedOnly: grant Reader, re-run after a check that could not
finish, or wait 5 minutes after the two answers disagree. The fix text
is shared with the role check's own report (Write-AccessRemedyLines).

Tests: runs of the wrapper itself after a parallel run whose session
ended while it was collecting, with -ParallelStreams 2, the automatic
value and 1 on the -Resume (no main or per-stream state file left, and
the next -Resume recovers nothing and collects again), and the Pending
Retries lines for each cause and for mixed causes.
…on the retry list

A -Resume or -ResumeFailedOnly run folds in the per-stream state files an
interrupted parallel run left. A file that could not be parsed (an
interrupted write can leave it cut short) was skipped with a verbose
message only: the run went on as if it held nothing, a run that cleared
the state deleted it while printing "Resume state cleared (clean run).",
and with one stream it stayed and was skipped again on every -Resume.
Such a file is now renamed in place to <name>.unreadable-<UTC time> with
a warning naming it: no later run reads it, it does not end in .json, and
it is kept for inspection. Its records are not used, so the subscriptions
it listed are not counted as completed and the run collects them again.
That run does not print the clean-run line: it says whether the state was
cleared or kept and where the file went. When it clears the state it
deletes the per-stream files it read, as the finish case already did, so
the next -Resume starts with no state. Files that were read are deleted
as before; the one moved aside is not.

A subscription the up-front role check skips because the check could not
finish, or because the two answers disagree while a role change takes
effect, now stays on the retry list (FailedAttempts) as a failed run,
with a reason naming the cause, and is taken off the completed list. The
state is kept, -Resume and -ResumeFailedOnly check it again, and each
run counts, also a run that stops because nothing it checks is readable,
so the retry limit can end the retries. A subscription skipped for a
missing role is not added. The Pending Retries line now says the
subscriptions are on the retry list, not that they all come from a prior
run. The state file keeps every other key it holds when the retry list is
written (Update-ResumeStateRetryList).

No script parameter, exit code or stop is added.
The lists of per-stream files read and moved aside are now plain arrays
appended with @(...) + item, so the fold of per-stream state also works
when it runs without the lines before it set them up. No change in what
a run does.
Peter-John Morgenrood added 9 commits November 10, 2026 18:01
…empts null is not a list

Read-StreamResumeStateFile let 'FailedAttempts': null through, and did not look inside the lists: an entry with no Id (or a non-object) was grouped under an empty id and saved, so the state never cleared, and under strict mode the fold threw on it every run. Write-StreamState always writes Completed as a list of ids and FailedAttempts as a list of Add-FailedAttempt records, so any other shape is a file that cannot be read (moved aside). Tests: 8 shapes refused (red before), the written shapes and an older file with no FailedAttempts still read.
119f01e refused a null entry, but Write-StreamState writes 'FailedAttempts': [null] for an empty retry list (@($null) of the list Remove-FailedAttempt returns), so every parallel run's stream file was moved aside as unreadable and its completions collected again (12 whole-wrapper tests red in the full suite). Null entries are skipped by every reader, so the check now refuses only an entry of another type: a Completed entry that is not a string, a FailedAttempts entry that is not an object with a non-empty string Id. FailedAttempts null itself stays refused (never written). Tests: the written [null] shape reads (red before), and the 12 whole-wrapper tests pass again.
…leted id is a file that cannot be read

The start fold and the end-of-run merge added a stream file's FailedAttempts entries as they are, so the [null] Write-StreamState writes for an empty list counted as a failed record: the fold printed '2 completed, 2 failed subscription record(s)' for two streams with no failure (pre-existing on main; all-fixes-optimized filters them). Both now drop null entries. 9321827 had also let a null or empty Completed entry through, which Write-StreamState never writes; it is refused again, with its two test cases back. Tests: the two whole-wrapper fold lines now read '0 failed' (red before), and the two Completed cases are refused (red before).
…ents name the shape rule

Read-StreamResumeStateFile let a retry entry with no LastFailedAt, or one that is not a date, through; Merge-FailedAttempts then converts it with [datetime], which fails (under strict mode the missing property throws), so the fold failed on every run instead of moving the file aside. As all-fixes-optimized does, LastFailedAt must be a [datetime] (ConvertFrom-Json's reading of ISO 8601 text) or text the cast parses (invariant culture). The function's header and the start fold's comment now say a file not in the written shape reads as one that cannot be read. Tests: no date, a word, a number (red before), and the missing-date case under Set-StrictMode -Version Latest returns no record instead of throwing (red before).
…was not a clean run

Write-UnreadableStreamStateSummary ran only at the end of the run, so a run that exited early after the start-up fold moved a per-stream file aside (-ResumeFailedOnly with an empty retry list, or with retry ids no longer visible, or the output check's exit 2) never said the run was not clean, or whether the resume state was kept. Exit-Wrapper, which every such exit goes through, now says it when it was not said before (the summary records that it ran). Test: the -ResumeFailedOnly case with an empty retry list prints 'Resume state kept, but not a clean run: ...' once (red before). Full Pester: 0 new.
Exit-Wrapper read the list of per-stream state files it could not read as one object, so an empty list passed the filter. Every stop after the start-up fold then said the run was not clean, naming an empty file. The list is now read item by item, with a test.
It stops with code 7, which pwsh never gives on its own, and fails on any error text.
Two tests: the end-of-run line is not repeated at the stop after it, and a stop with no earlier line says it, with kept or cleared. The comment says when the variables are not set.
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 12, 2026
Peter-John Morgenrood added 14 commits November 12, 2026 17:03
…nd-usage-check

Brings in the three memory PRs awslabs main merged. The run counts the
discovered resources into $Global:ResourceCount after this branch leaves
out a skipped subscription's resources, and the end-of-run lines of awslabs#41
come first, then this branch's no-usage and skipped-subscription lists.
The awslabs#41 inventory-write harness stubs every Azure step of a direct run;
this branch adds the up-front role check, so the harness stubs it too
(no subscription reported unreadable) and the run still never loads
Az.Accounts. The end-of-run order check reads the report line inside
the if/else on $ZipWritten that awslabs#41 added, with the no-usage and
skipped-subscription lists right after it.
Get-ConsumptionRowResourceUri read 'Microsoft.Resources'.resourceUri
directly, so under Set-StrictMode a row whose InstanceData lacks either
property stopped the consumption data check of a resource group run.
It now returns nothing for such a row, as its comment says.
A direct run over every visible subscription that found none skipped the
up-front checks and went on to write an empty report. It now stops with
exit 1, as a run whose subscriptions are all unreadable does. The test
harness can now start with no subscription at all.
The harness passed the up-front checks only because the setup's empty
subscription value counts as one. Its sign-in stand-in now finds one
placeholder subscription, as a real direct run does, so the harness
does not depend on that value.
The comments and the README said a retry limit ends the retries of a
subscription the role check could not finish, but this branch has no
such limit. They now say it stays on the retry list, with its run count
and reason, until a later check passes, as any failed subscription does.
A passing role check does not take the subscription off the retry list;
the run that then collects it does. The comment and the README now say
so, and the README names the list once.
When a per-stream state file cannot be read at the end of a parallel run,
its records are set aside, and with them may go this run's failure of a
subscription an earlier run completed. That completion stayed, so
-Resume skipped the subscription and carried the older report. Of this
run's subscriptions, only those a file that was read lists as completed
now keep a completion; -Resume collects the others again.
A readable file an earlier run left can list a subscription whose
failure this run's unreadable file held, so trusting the readable files
could still keep a stale completion. Which stream's records were lost
is not known, so when any file cannot be read at the end of a parallel
run, none of this run's subscriptions keeps a completion and -Resume
collects them all again.
…ole run

Since the merge keeps no completion of a run's subscriptions when one
per-stream file cannot be read, the warning and the README now say that
a later -Resume collects all of that run's subscriptions again, not only
those the file listed.
The comments on Move-UnreadableStreamStateFile and on the merge loop's
unreadable branch still named only the file's own subscriptions for the
end of a run; they now say none of that run's subscriptions counts as
completed.
…am file

The merge saved a state that keeps none of the run's subscriptions as
completed, but the clean-up at the end of the run still removed the
state when no failure was reported, and with it the completions of
earlier runs. A run whose merge could not read a per-stream file now
keeps the resume state, as the file may have held a failure.
The clean-up case passed the flag by hand, so it would still pass if
the merge stopped setting it. It now reads the flag from the merge
block's result and checks it is set.
The case reads its test-case values inside a child script block, so the
analyzer saw the declared parameters as unused. Pester sets the values
as variables, so the block is not needed.
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 17, 2026
…rk remains

Changes on the merged candidate (consolidated report):

- loop trap (awslabs#68): a run that skipped a subscription for the retry
  limit and completed the rest cleared the resume state, so the count was
  forgotten and the next -Resume collected it again from the first attempt:
  fail x3, skip, clear, forever. Entries past the limit now keep the state,
  and a run that skips one ends with exit 2 (its report is missing from the
  bundle). They leave the state when a run collects them (the subscription on
  its own, or a run without -Resume), as the advice says.
- loop trap (pre-existing): a retry-list entry for a subscription the
  identity no longer sees was never retried or counted and kept the state
  forever. -Resume and -ResumeFailedOnly now drop such an entry with a line
  naming it. A disabled subscription is still listed, so its entry stays.
- (awslabs#62/awslabs#68): -ResumeFailedOnly kept the state and exited 0 while work
  remained (never-reached subscriptions, retry-list ids not in the current
  set, only entries past the limit), so a repeated command reported success
  forever. Those exits are now 2; 0 stays for nothing owed.
- stale comment on the one-stream -Resume.

The tests of awslabs#38, awslabs#62, awslabs#68 and the parallel -Resume fix that asserted the
old exit 0 or the cleared state now expect the new behaviour, and the
capped case traces the next two -Resume runs. A new case drops an entry for a
subscription that is gone. README updated.
The comments, the console lines and the README now say what the usage
values show and that a subscription with no resources has no usage to
read. No check or exit code changes.
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 18, 2026
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 18, 2026
pmorgenrood pushed a commit to pmorgenrood/resource-discovery-for-azure that referenced this pull request Nov 18, 2026
…scan

- The check looked only at the first and last bytes of the JSON files and the
  CSV header, so well-bracketed bad JSON, a metrics file with no Metrics list,
  or a consumption row with a cell that does not parse passed. The JSON
  files are now parsed (System.Text.Json: an object; the metrics file's
  Metrics is a list whose MetricCount, MetricValue, MetricPercentile are
  numbers and MetricError is true or false where given), and every row of the
  consumption file is read: the header names the needed columns,
  each row has every column, and Quantity, Cost, UnitPrice, UsageStartTime and
  UsageEndTime parse with culture-free rules (an empty cell is not checked:
  that row is dropped, not the file).
- The scan ran a PowerShell loop over every byte (about 0.5 MB/s); the read
  to the end is the plain buffered read again, and the parsing runs in .NET.
shortcut (in the code): the JSON is parsed in memory, so a report of several
GB takes that much memory here.
Note: on a branch without PR awslabs#38's culture-free usage text, a host whose
culture writes a comma decimal mark writes cells that do not parse; such a
report is then named as unreadable, not shipped.
Tests: six more unreadable cases (6 red before), the file shape with a
BOM and a quoted JSON cell reads, and a zip with a 20 MB inventory and a 20 MB
consumption file is checked in under a minute.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant