Skip to content

feat: add infrahubctl storage encrypt for files stored before encryption was enabled - #1535

Merged
DharmaBytesX merged 9 commits into
infrahub-developfrom
sas-storage-encrypt
Dec 2, 2026
Merged

DharmaBytesX merged 9 commits into
infrahub-developfrom
sas-storage-encrypt

Conversation

@DharmaBytesX

@DharmaBytesX DharmaBytesX commented Nov 17, 2026 •

Copy link
Copy Markdown

For humans

Files stored before encryption was switched on stay unencrypted, and nothing fixes them.
This adds an infrahubctl command that encrypts them through the server, with progress and resume.
Check: it needs server routes that are not released, and the speed proof is partly noisy.

Why

Files stored before storage encryption was enabled stay in plaintext, and regenerating an artifact does not encrypt the old files. An operator has no way to encrypt them.

Goal: a command that encrypts the stored files through the API of an Infrahub server, which holds the key. The operator sees the total and the progress, and can stop and resume at any time, as with infrahub upgrade for database migrations.

Non-goals: no key on the client.

Source: INFP-740. The server routes are added in opsmill/infrahub#11561, merged into develop on 2026-12-02 and not released yet.

What changed

  • New command infrahubctl storage encrypt. It lists the stored objects, counts them first, and prints the total.
  • The progress line shows done out of total, percentage, objects per second, time remaining, bytes, the concurrency limit, 429 answers and retries.
  • It sends 50 objects per request with several requests in flight (--concurrency, default 8, at most 64), starting at half that number. A 429, 503 or 504 answer, or a request that times out, halves the number in flight, once for all the requests sent before that decrease. After as many successful batches in a row as the current number, the number rises by one. It waits on 429 answers using Retry-After (one pause is capped at 300 s) and retries network errors, timeouts and 500, 502, 503 and 504 answers.
  • A state file keeps the position, so a run stopped with Ctrl-C (exit 130), SIGTERM (exit 143) or a kill resumes where it stopped. A report file lists every object that was not encrypted.
  • Other options: --dry-run, --rate, --before, --limit, --allow-unverified, --no-count, --restart, --priority.
  • The position follows the cursor that the server returns for each page, so a page that is empty but has a cursor does not stop or repeat the run. A server that returns the same position twice stops the run with an error (exit 2).
  • A password login that expires during a long run is renewed once and the request is sent again.
  • After a freeze of the process (SIGSTOP, a paused container) the remaining time shows estimating for 4 seconds and then the right value: the rate tracker drops its samples when two samples are more than 5 seconds apart. A stall of the server is not a freeze: the refresh goes on, the rate falls and the remaining time grows.
  • A stop in the middle of a page lists the objects that the server confirmed in that page in separate rows marked interrupted page, not saved, with a note. The totals and the state file do not change.
  • The command builds its own httpx client from the SDK configuration, because the SDK opens a new connection for each request and retries 429 answers itself, which would hide them from the pacing.

How to review

  • Start with infrahub_sdk/ctl/storage/migration.py (state, pacing, retries), then encrypt.py (command, signals) and progress.py (progress line).
  • Decisions to confirm: the own httpx client built from private SDK members; unlimited waiting on 429 answers (Ctrl-C and SIGTERM stop it); state and report files in the current directory by default; the count pass before the run.

Testing

  • On commit 25649531: 231 tests in the three storage test files; tests/unit/ctl: 676 passed, 1 expected failure, on Python 3.14.7 and 3.10.21. CI on 25649531: 28 checks passed, 4 skipped.
  • Each new test fails when the behaviour it covers is broken and passes with it: 62 deliberate breakages for the progress work, 71 for the first tests, and one for each fix after the code review and for the cursor change (7 of the 8 cursor tests fail with the old loop; the eighth guards the --limit cut and fails with a naive fix). The reports are local files and are not published.
  • ruff, ty, mypy, rumdl and vale pass. docs-generate gives the same page on a second run.
  • Stop and resume on local disk, small dataset (6,300 files): SIGKILL, SIGTERM and Ctrl-C each followed by a rerun. The rerun printed Already handled in earlier runs: 1,000 and To process: 5,300, ended at 6,300 of 6,300, and the audit passed (2,300 of 2,300 downloads match, no temporary file).
  • Speed on a laptop, S3 (Garage on the same machine), small dataset: the median of the command was 98.9% of the standalone benchmark client over 13 runs. The baseline alone ranged from 234 to 304 objects per second because other jobs loaded the laptop. Over the first five planned pairs it was 93.4%, and over the runs after the other jobs stopped 97.6%. Against a mock server (100,000 objects) it was 99.7%. This does not prove or rule out a regression.
  • Count pass: 0.25 s for 6,300 objects on S3. For 157,000 objects: 2.8 and 2.9 s on local disk, 6.8 and 8.5 s on S3.
  • Clean VM, 157,000 files in S3 (Garage), 5 foreground requests per second: the command took 579 s (267.6 objects per second) and the standalone client 601 s (258.1). The audits passed: 155,000 files encrypted, the 2,000 orphan files unchanged, 0 of 50,300 downloads failed. This ran the version before the count pass and the review fixes.

Impact & rollout

Not done or not verified

  • After a freeze the non-terminal output prints a burst of lines. A freeze longer than --timeout makes the requests in flight time out, which halves the limit and sends them again (inferred, not tested). Ctrl-Z, a paused container or VM and machine sleep were not tested.

  • The clean VM run used the version before the count pass and the review fixes. The comparison of the final version on S3 was disturbed by other jobs.

  • No remote S3 service: every S3 run used Garage on the same machine.

  • No integration test against a real server in CI: the tests use mocks. The runs against a real server used a local stack built from the server branch.

  • Python 3.11 and 3.12 were not run. Python 3.13 ran only on the code before the review fixes. Windows was not checked.

  • The server stores encrypted on the default-branch artifacts whose file it encrypts. An artifact that exists only on another branch keeps its stored value until its check runs.

Follow-up to the review comments of cubic

Three commits (2026-11-23) answer the six open threads of cubic: 2bdc2887 (the pace of the command is no longer counted in the latency that adapts the limit, and server error text is printed without control characters), d5db04d9 (the line that points to the report prints only when the report lists an object, a rate below 10 objects/s shows one decimal, and the exit code help is corrected) and 7ec57a54 (the list of subcommand groups). Each fix has a test that fails without it. The code-review and security-review skills did not review these commits.

Follow-up to the review of danipl

Commit 62483267 (2026-12-01) answers the review of danipl. The command compares the identifiers in the answer to each batch with the identifiers it sent. When a file has no result, a result names a file that was not sent, or a file has two results, the command stops with exit code 2 before it saves its position, and the next run sends the page again. The server of opsmill/infrahub#11561 returns one result for each identifier sent, so the check guards against a faulty or changed server. 8 new tests fail without the fix and pass with it; tests/unit/ctl: 679 passed, 1 expected failure, on Python 3.14 and 3.10. Commit 3bcd8bf1 answers the comment of cubic on that commit: when the command stops on such an answer, the results that name a file sent, once, are shown in the rows of the interrupted page and in the number done before the error. The position and the state file do not change. The code-review and security-review skills did not review these two commits.

Follow-up to the review of ajtmccarty

ajtmccarty approved commit 3bcd8bf1 with 12 optional comments. Two commits (2026-12-02) answer six of them:

  • 81c03446: a timeout or a 503 or 504 answer now halves the limit of requests in flight, as a 429 does (comment). A 500 answer is retried, as the SDK does (comment). The limit no longer reacts to how long a batch takes, because a batch of files already encrypted is much faster than one to encrypt, so a resumed run lowered the limit to 1 (comment).
  • 25649531: the progress display takes its clock and its sleep as arguments, and its test compares the printed lines exactly with a fake clock (comment). A state file in the format of development versions of the command is no longer converted, because no released version wrote it; a state file with an unknown field is refused as unreadable (comment). The count-pass tests that repeated cases of the run are removed; one test keeps what only the count pass does on a failure (comment).

Run against a local server built from opsmill/infrahub#11561 with commit 81c03446 (950 stored files): a 9-second pause of the server lowered the limit from 7 to 3 to 1, and it rose back to 8 afterwards; 930 files were encrypted, the 20 orphan files were skipped, and the audit passed. The code-review and security-review skills did not review these two commits.

The other six comments are left for after the 1.13 release (decision of the PR author):

  • Use public SDK helpers instead of private ones (comment).
  • Reuse the SDK client instead of building an own httpx client (comment).
  • Retry the files that failed in an earlier run, for example with a --retry-failed option (comment).
  • Split the module along the component design of the Infrahub backend (comment).
  • Give one owner to the choice of the counter that measures progress (comment).
  • Split test_storage_migration.py into smaller files (comment).

Code review

The commit a3266e8e (the remaining time after a freeze, and the table after a stop) was pushed after the reviews below and was not reviewed by the code-review or security-review skills. Both defects were found in an end-to-end test by another agent and reproduced with the real command: 5 new tests fail without the first fix and 7 without the second, and all pass with them. 216 tests pass in the three storage files and 661 in tests/unit/ctl, on Python 3.14 and 3.10.

The code-review skill ran once at level high, by an agent other than the author, on commit 4dcc5c72. The fixes, and the later change of the paging position (follow the cursor of the server, found while reviewing the server routes), are amended into the final commit 1b8c6d87 and were not reviewed again. The skill reviewed the right checkout. The agent verified its 10 findings (2 dropped) and added its own.

0 critical, 3 important, 12 minor.

Important, all fixed:

  • An expired login token was never renewed, so a long run stopped on a 401.
  • A missing directory for --state-file or --report was found only after the first page was encrypted, or after the count pass.
  • No test failed when a --limit run moved the resume position past unsent objects, or when the report was overwritten instead of appended.

Minor, fixed: overflow of the backoff exponent after 8.5 hours of 429 answers; Retry-After with inf or an HTTP date; an unused console; pytest.raises without match; docs on skipped objects on resume and on exit code 1; no upper bound for --concurrency; a zero latency sample; --priority not using the SDK enum.

Minor, left as they are:

  • The latency that drove the concurrency limit included pacing and retry waits, so one 429 with Retry-After: 20 lowered the limit twice. No longer applies: commit 81c03446 removed the latency signal.
  • "Done before the error" counts batches of a page that later fails. The state file is correct.
  • The report is flushed before the state is saved, so a kill between the two adds the same report lines again on resume.

Security review

The built-in security-review skill ran once, by an agent other than the author, on d5161c5f: the code of the final commit 1b8c6d87 without the paging position change (about 20 lines in migration.py). Its diff was this change; the agent did the analysis by hand.

0 high, 0 medium, 1 low (4 findings dropped as below the skill's confidence rules or hardening only).

Low, left as it is: text from the server is printed after Rich escapes its brackets, but escape characters are kept, so a compromised server could change the terminal title or clear the screen. Other infrahubctl commands print server text the same way.

Checklist

  • Tests added/updated
  • Changelog entry added
  • External docs updated (generated CLI page)
  • Internal .md docs updated (dev/knowledge/cli-architecture.md)

…ion was enabled

Files stored before storage encryption was enabled stay in plaintext, and an
operator has no way to encrypt them. The new command encrypts them through
the storage routes of the Infrahub server, which holds the key. The key never
reaches the machine that runs the command.

The command lists the stored objects, counts them, and sends them in batches
of 50 with an adaptive number of batches in flight. It shows done out of
total, the percentage and the time remaining. It waits on 429 answers,
retries network errors, and keeps a state file, so a run stopped with Ctrl-C,
SIGTERM or a kill resumes where it stopped. Objects that were not encrypted
are listed in a report file.

It needs an Infrahub server that has the storage encryption routes, so it
targets infrahub-develop.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Deploying infrahub-sdk-python with  Cloudflare Pages  Cloudflare Pages

Latest commit: 2564953
Status: ✅  Deploy successful!
Preview URL: https://8d0dd533.infrahub-sdk-python.pages.dev
Branch Preview URL: https://sas-storage-encrypt.infrahub-sdk-python.pages.dev

View logs

@codecov

codecov Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.06061% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
infrahub_sdk/ctl/storage/migration.py 97.95% 3 Missing and 8 partials ⚠️
infrahub_sdk/ctl/storage/encrypt.py 97.26% 4 Missing and 1 partial ⚠️
@@                 Coverage Diff                  @@
##           infrahub-develop    #1535      +/-   ##
====================================================
+ Coverage             87.88%   88.42%   +0.53%     
====================================================
  Files                   157      161       +4     
  Lines                 15658    16486     +828     
  Branches               2114     2221     +107     
====================================================
+ Hits                  13761    14577     +816     
- Misses                 1336     1341       +5     
- Partials                561      568       +7     
Flag Coverage Δ
integration-tests 42.17% <26.78%> (-0.78%) ⬇️
python-3.10 64.87% <98.06%> (+1.83%) ⬆️
python-3.11 64.86% <98.06%> (+1.81%) ⬆️
python-3.12 64.86% <98.06%> (+1.81%) ⬆️
python-3.13 64.87% <98.06%> (+1.82%) ⬆️
python-3.14 64.86% <98.06%> (+1.81%) ⬆️
python-3.15 64.87% <98.06%> (+1.82%) ⬆️
python-filler-3.12 21.89% <0.00%> (-1.16%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
infrahub_sdk/ctl/cli_commands.py 74.80% <100.00%> (+0.19%) ⬆️
infrahub_sdk/ctl/storage/__init__.py 100.00% <100.00%> (ø)
infrahub_sdk/ctl/storage/progress.py 100.00% <100.00%> (ø)
infrahub_sdk/ctl/storage/encrypt.py 97.26% <97.26%> (ø)
infrahub_sdk/ctl/storage/migration.py 97.95% <97.95%> (ø)

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@DharmaBytesX
DharmaBytesX marked this pull request as ready for review November 17, 2026 14:32
@DharmaBytesX
DharmaBytesX requested a review from a team as a code owner November 17, 2026 14:32

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 11 files

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread infrahub_sdk/ctl/storage/migration.py Resolved
Comment thread infrahub_sdk/ctl/storage/encrypt.py Resolved
Comment thread dev/knowledge/cli-architecture.md Resolved
Comment thread infrahub_sdk/ctl/storage/encrypt.py Resolved
Comment thread infrahub_sdk/ctl/storage/progress.py Resolved
Comment thread infrahub_sdk/ctl/storage/encrypt.py Resolved
… a stopped page confirmed

After the process was frozen (SIGSTOP, a paused container), the rate window
still held a sample from before the freeze, so the remaining time showed
hours for about 30 seconds. The rate tracker now drops its samples when two
samples are more than 5 seconds apart, so the line shows `estimating` for
4 seconds and then the right value. A stall of the server is not a gap: the
refresh goes on and the rate falls.

A stop in the middle of a page printed a table without the objects that the
server had already confirmed in that page, because a page is counted only
when it is complete. The table now lists them in separate rows marked
`interrupted page, not saved`, and a note says that no position was saved and
that a smaller `--page-size` saves it more often. The totals, the state file,
the options and the exit codes are unchanged.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>
…limit

The latency of a batch included the wait for the pace, the pause after a 429
answer and the delay after a failure, so the adaptive limit could shrink
while the server was not slow. The request now returns the time of the HTTP
call that produced the answer, and the limit uses that.

The text of a server error is printed with its control characters replaced by
spaces, so that an escape sequence in an answer does not reach the terminal.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>
…s, fix the exit code help

The line that points to the report was printed after every run that
processed an object, also when all of them were encrypted and the report was
empty. It is now printed when a result other than encrypted was counted,
which is what the report lists.

The progress line shows one decimal below 10 objects a second, so that a rate
of 0.4 is not shown as 0 while the remaining time is computed from 0.4.

The exit code help listed a file error under exit 1, but a state file or
report that cannot be used exits 2. The generated page follows.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>
The list of groups stopped at storage. It now has marketplace, telemetry and
troubleshooting, which cli_commands.py also registers.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>
@danipl

danipl commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

ty @DharmaBytesX !!

Must fix: answers are not checked against the files sent

_encrypt_batch (migration.py) accepts any results list. If the server answers for 49 of 50 files, the saved position still moves past all 50. The missing file stays unencrypted, is not in the report, is not retried on resume, and the exit code is 0.

Please compare the identifiers in results with the identifiers sent, and record each missing one as failed (or raise MigrationError) before the position moves.

Aside of this check, it lgtm!

The command moved its position past every file of a batch, even when the
server answered for only some of them. A file left out of the answer stayed
unencrypted, was not in the report, and the command exited 0.

The command now compares the identifiers in the answer with the identifiers
it sent. When a file has no result, a result names a file that was not sent,
or a file has two results, it stops with exit code 2 before it saves its
position, so the next run sends the page again. A result without a usable
identifier stops the run as an answer of an unexpected shape.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>
@DharmaBytesX

Copy link
Copy Markdown
Author

ty @DharmaBytesX !!

Must fix: answers are not checked against the files sent

_encrypt_batch (migration.py) accepts any results list. If the server answers for 49 of 50 files, the saved position still moves past all 50. The missing file stays unencrypted, is not in the report, is not retried on resume, and the exit code is 0.

Please compare the identifiers in results with the identifiers sent, and record each missing one as failed (or raise MigrationError) before the position moves.

Aside of this check, it lgtm!

Thanks, fixed in 6248326: the command now stops with an error when the answer to a batch does not list every file sent exactly once, and the next run sends them again.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread infrahub_sdk/ctl/storage/migration.py Resolved
When the answer to a batch did not name each file sent exactly once, the
command stopped before it counted any result of that batch. The files the
server confirmed in it were missing from the stop summary and from the
number done before the error.

The results that name a file sent, once, now go to the rows of the
interrupted page and to the number done. The position and the state file
do not change, so the rerun repeats the page.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>

@ajtmccarty ajtmccarty left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

approved. all of the comments are optional. some are from applying testing and component design principles of dev/guidelines and dev/knowledge in the infrahub repo to these changes.

I'd suggest having an LLM check on the structural change suggestions for migration.py and the tests.

return delay * (1 + BACKOFF_JITTER * rng.random())


_RETRY_AFTER_PARSER = RateLimitRetryHandler(max_retries=0, backoff_base=0.0, backoff_max=RETRY_AFTER_MAX_SECONDS)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This module depends on three SDK helpers, one private and two by copying or by creating an object only to reach a method:

  • _should_refresh_token is private to the client module (client.py#L199-L213).
  • _RETRY_AFTER_PARSER creates a RateLimitRetryHandler only to call parse_retry_after, which does not use any state of the handler (rate_limit.py#L46-L75).
  • backoff_delay computes the same capped delay as RateLimitRetryHandler.compute_backoff, base × 2^attempt with the exponent capped at 63, with a different jitter (rate_limit.py#L77-L83).

Can the SDK expose these as public functions, for example a module-level parse_retry_after in rate_limit.py, so that this module calls them instead of copying them?

The two parsers also give different results for the same header. This module accepts a decimal value such as Retry-After: 1.5. The SDK parser returns None for it, because it accepts only an integer or an HTTP date. If the decimal form is needed, the change belongs in the SDK parser, so that both code paths read the header the same way.

If the command sends its requests through the SDK client (see the comment on encrypt.py), _get and _post renew an expired login themselves (client.py#L229-L237), and the import of _should_refresh_token is no longer needed.

http.headers["Authorization"] = client.headers["Authorization"]

encryptor.refresh_login = renew_login
async with httpx.AsyncClient(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The command builds its own httpx.AsyncClient from three private members of the SDK client: _merge_request_headers, _build_timeout and _build_proxy_config. The PR description gives two reasons: the SDK opens a new connection for each request (client.py#L2045), and the SDK retries 429 answers itself. The SDK configuration has a public setting for each reason:

  • rate_limit_retry_enabled=False turns off the SDK's 429 retries, so every 429 reaches the command (config.py#L96).
  • requester replaces the function that sends each request (config.py#L311, client.py#L576). The command can pass a function that sends through one pooled httpx.AsyncClient.

With these two settings, the command can send its requests with client._get and client._post, as other infrahubctl commands do (ctl/branch.py#L62). Can the command use them instead of its own client?

The own client also skips SDK behavior that applies to every other request:

  • _merge_request_headers adds the trace context headers once, when the client is built (client.py#L421), so every request of a long run carries the trace context from its start.
  • The configured custom_recorder does not record the requests (client.py#L384-L385).

One difference to keep in mind: handle_relogin renews the login once for each request that gets a 401, so with 8 requests in flight an expired token can cause 8 renewals. The renewal in this PR uses a lock to renew once.


Objects that the server leaves unchanged are listed in the report file, which every run appends to.
A run that resumes does not retry them, nor the objects that failed, because the saved position is past them.
A new full pass, which starts after a pass has finished, or --restart, tries them again.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A run that resumes does not retry the objects that failed, because the saved position is past them (lines 291-293). The only way to retry them is a new full pass or --restart, which lists every stored object and sends each one to the server again. On a large installation, retrying a few failed objects then costs as much as the first pass.

The report already holds what a retry needs: one JSON line per object that was not encrypted, with its identifier and outcome (migration.py#L605-L611). The encrypt route takes a list of identifiers (migration.py#L572-L576), so a retry does not need the listing.

Can the command take an option such as --retry-failed <report>? It would read the lines whose outcome is failed, send those identifiers in batches with the same pacing and retries, and write the objects that fail again to a new report.

For this to work, the report must show which run wrote each line. Every run appends to the same file, including after --restart (migration.py#L740), and a line carries only the result from the server. An object that failed in one pass and was encrypted in a later pass stays listed as failed. A run identifier and a time on each line, or a new report file for each pass, would let a retry pick only the objects that are still not encrypted.

Comment thread infrahub_sdk/ctl/storage/migration.py Outdated
saved = dict(state["totals"])
known = {item.name for item in fields(Totals)}
totals = Totals(**{name: value for name, value in saved.items() if name in known})
if "bytes_handled" not in saved:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No released version of the command exists, so every state file has bytes_handled and only known Totals fields. The only files without them were written by development versions of this PR, before the count pass was added; the test helper old_state describes them as "A state file as the version without the count pass wrote it" (test_storage_migration.py#L1089-L1090). Can this branch, the filtering of unknown Totals fields (lines 333-334), and the tests that use old_state be removed?

If a later release changes the format of the state file, load_state can check the version field, which save_state writes (line 360) but nothing reads today.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 2564953: the conversion, the filtering of unknown fields and the tests that used them are removed. A state file with an unknown field is now refused as unreadable.

self._paused_until = max(self._paused_until, self._clock() + seconds)


class AdaptiveLimit:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The signal that lowers the limit is the latency per unit of work, compared with the lowest smoothed latency seen. A unit is one object plus one per 64 KiB of the size from the listing (line 584). The work of the server per object depends on its outcome, which the listing does not show. An object that is already encrypted costs one header read of 4,096 bytes and no database query, and an object to encrypt costs a full read, the encryption, a write and a second header read (migrate.py#L14-L25). So a change in the mix of objects looks like a slower server.

A run that resumes sends its first page again, and most of that page is already encrypted. Those fast batches set a low floor, and the batches to encrypt after them look slow. I ran this class with 100 batches of 0.3 s followed by batches of 1.2 s, with a latency that does not depend on the number of requests in flight. The limit dropped from 8 to 1 within 10 seconds and stayed at 1 until between 120 and 180 seconds, until the floor had risen enough. A fresh run with only the 1.2 s batches stayed at 8.

The server already answers 429 when it is overloaded: the admission middleware sheds requests (middleware.py#L39), and the route answers 429 with Retry-After when its memory budget is full (encryption_migration.py#L77-L86). The benchmarks in the PR description compare the command with a simple client and find no difference, so they do not show what the latency signal adds. Can the limit react only to 429 answers, lowering on a 429 and rising slowly afterward? That removes the latency signal and its constants (SMOOTHING, COOLDOWN_SECONDS, FLOOR_DRIFT_PER_SECOND, slow_factor, SMALL_OBJECT_BYTES), which have no stated source.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 81c0344: the latency signal and its constants are removed. The limit halves on a 429, 503, 504 or timeout, once for the requests sent before that decrease, and rises by one after as many successful batches as the limit.
I used that rule instead of the 2 s cooldown, so 8 answers to the same overload don't take the limit from 8 to 1. Your fast-then-slow case is now a test.

call_started = self._clock()
try:
response = await http.request(method, path, params=params, json=body)
except httpx.TransportError as exc:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A network error, a timeout or a 502, 503 or 504 answer neither lowers the limit nor counts as a slow batch: the request keeps its slot, waits for the backoff and sends the same batch again. The server keeps working on a batch after its request is cancelled, because the route runs it in a task that "outlives a cancelled request" (encryption_migration.py#L145, #L176-L178). So when the server is too slow to answer within --timeout, each retry adds a second task for the same batch, and the load grows while the server is slowest. Can a timeout and a 503 lower the limit as a 429 does?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 81c0344: a timeout, a 503 or a 504 now halves the limit like a 429.
Tested on a local stack: with the server paused 9 s mid-run, the limit dropped twice, came back to 8, and the run finished by itself.

raise typer.BadParameter(f"must be one of {', '.join(item.value for item in Priority)}") from None


def _view(encryptor: StorageEncryptor, rate: float | None) -> ProgressView:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_view, _done_objects, _done_text and _summary_table each choose which counter measures progress: totals.objects_listed in a dry run, encryptor.done_objects otherwise, and the same for the total and the bytes (lines 61-67, 77, 83). Which counter measures progress is a fact about the run, so it belongs to the component that owns the counters. _view already builds a ProgressView. Can that component return the ProgressView itself, so that these helpers read one object instead of the attributes of the encryptor?

@@ -0,0 +1,2044 @@
from __future__ import annotations

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file has 2,044 lines and 103 tests in 12 sections, more than any other file in tests/unit/ctl/. The SDK already groups the tests of a command in a directory (tests/unit/ctl/object/, tests/unit/ctl/schema/). Can the storage tests move to tests/unit/ctl/storage/, with the helpers (FakeTime, stored, page, answer, make, run, sent_bodies) in a conftest.py, and this file split along its sections? For example:

  • paging, the listing cursor and --limit (about 520 lines)
  • the state file and the checks before the run (about 340 lines)
  • 429 answers, transient errors, Retry-After, refusals and the expired login (about 430 lines)
  • the count pass (436 lines)
  • the checks of malformed answers, which are in the section "Connections" today (about 230 lines)
  • AdaptiveLimit (80 lines)

test_storage_app.py and test_storage_progress.py would move to the same directory. If StorageEncryptor is split into components, each new file can follow one component.

assert seen == [3]


async def test_a_429_answer_during_the_count_is_waited_out_and_counted(httpx_mock: HTTPXMock, tmp_path: Path) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The count pass sends its requests through _fetch_listing and _request, the same code as the listing of the run. The sections "429 answers", "Transient errors" and "Refusals" test that code already. This test and the ones at lines 1440, 1457, 1470 and 1485 repeat those cases through the count pass, and test_storage_app.py lines 514 and 528 repeat them again through the command. The Infrahub testing guideline asks not to repeat the same cases through every caller (testing.md#L79-L80). Which failure does each of these catch that the earlier sections do not?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They catch nothing the other sections miss, so they are removed in 2564953, with the command-level unreachable test. One count test stays: a refusal leaves no state file, resets the count flag and keeps its requests apart from the run. The command-level refusal test stays too: it checks that no total is printed.

Comment thread tests/unit/ctl/test_storage_app.py Outdated
return StorageEncryptor(options=options, address=BASE)


async def test_the_progress_line_printed_when_the_output_is_not_a_terminal_shows_total_percent_and_remaining_time(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test replaces the time module of encrypt.py and two of its constants, because _Progress and _show_progress call time.monotonic() directly (encrypt.py lines 101, 113, 116). It then drives the display with real sleeps of 0.01 s against a refresh of 0.02 s, so how many lines are printed depends on the speed of the machine. It checks parts of the line ("remaining" in last, "%)" in last) instead of the whole line. The Infrahub testing guideline asks for an injected clock instead of a patched one (testing.md#L354-L366) and for exact expected values (testing.md#L458-L460). Can the display take a clock as an argument, and this test advance it and compare the printed line with an exact expected line?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 2564953: the display takes a clock and a sleep as arguments. The test advances a fake clock and compares the two printed lines exactly; it passed 100 runs in a row.

…e latency signal

A timeout, or a 503 or 504 answer, now halves the number of requests in
flight, as a 429 does. The server keeps working on a batch after its
request times out, so sending it again at the same concurrency added load
while the server was slowest.

A 500 answer is retried like 502, 503 and 504, as the SDK does, because
Infrahub reports some temporary database errors as 500.

The limit no longer reacts to how long a batch takes. A batch of objects
that are already encrypted is much faster than one to encrypt, so a
resumed run looked like a slower server and the limit fell to 1 for
minutes. The limit now halves once for all the requests sent before the
last decrease, and rises by one after as many successful batches as the
limit.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>
…nd repeated count tests

The progress display takes its clock and sleep as arguments. Its test
advances a fake clock and compares the printed lines exactly, instead of
patching the time module and racing real sleeps against the refresh.

A state file no longer goes through a conversion for the format of
development versions of the command; no released version wrote it. A
state file with a field this version does not know is refused as
unreadable.

The count-pass tests that repeated the 429, refusal, connection and
malformed-answer cases of the run are removed. One test keeps what only
the count pass does on a failure: no batch, no state file, the count flag
reset and its requests counted apart from the run.

Signed-off-by: Simon AURA--SCUSSEL <simon@opsmill.com>
@DharmaBytesX
DharmaBytesX merged commit 365dd28 into infrahub-develop Dec 2, 2026
32 checks passed
@DharmaBytesX
DharmaBytesX deleted the sas-storage-encrypt branch December 2, 2026 10:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type/documentation Improvements or additions to documentation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants