Skip to content

feat: add an opt-in library store and fetch libraries concurrently - #255

Open
Yingjie Chen (Y1ngJ1eChen) wants to merge 1 commit into
mainfrom
user/yingjie/fix-issue-4328-library-fetch-reuse
Open

Yingjie Chen (Y1ngJ1eChen) wants to merge 1 commit into
mainfrom
user/yingjie/fix-issue-4328-library-fetch-reuse

Conversation

@Y1ngJ1eChen

Copy link
Copy Markdown
Contributor

Summary

Two changes to how alzlib fetches libraries. Both target the time terraform-provider-alz spends in ConfigureProvider on every plan and apply (~33–37 s reported in Azure/Azure-Landing-Zones#4328), most of which is fetching libraries:

  • Concurrent fetch, same order. FetchWithDependencies fetches libraries and their dependencies up to four at a time. The result is still built by the same depth-first walk, so the order of the libraries (which decides which library overwrites another) and the errors are unchanged.
  • Library store, opt-in. With ALZLIB_LIBRARY_STORE_ENABLED=true or alzlib.LibraryStoreEnabled.Store(true), libraries that cannot change (ALZ Library members, and git URLs pinned to a commit SHA) are fetched once into <ALZLIB_DIR>/store. They are then reused by later calls, by other processes, and by later pipeline runs that cache ALZLIB_DIR. The store is disabled by default.

Refs Azure/Azure-Landing-Zones#4328. Not "Fixes": the issue has four items across alzlib and terraform-provider-alz, and this PR is the alzlib part of Item 2 (see "Where this fits in Azure/Azure-Landing-Zones#4328" below).

Problem

  • terraform-provider-alz stores a random alzlib.Instance in every Configure() (provider.go#L152-L153). The libraries therefore go to a new <ALZLIB_DIR>/<random>/<hash> directory each time, and nothing is reused between runs, or between plan and apply.
  • FetchLibraryByGetterString deletes the destination and downloads the library with go-getter (initialize.go#L120-L159). fetchLibraryWithDependencies fetches the libraries and their dependencies one at a time (initialize.go#L32-L79). Both are unchanged on main.
  • Measured on main against the ALZ Library on GitHub, fetching takes 21.9 s for platform/alz@2026.11.0 + platform/amba@2026.10.0, and 28.2 s for platform/slz@2026.11.0 + platform/amba@2026.10.0 (details under Testing).

Changes

File Change
initialize.go fetchLibrariesWithDependencies: a concurrent prefetch (prefetchLibraries), then the depth-first walk of before (libraryWalk), with cycle detection. When the store is enabled, FetchAzureLandingZonesLibraryMember and FetchLibraryByGetterString use it for libraries that cannot change; everything else is fetched as before (fetchLibraryToInstanceDir).
library_store.go (new) The library store: LibraryStoreEnabled, which URLs are stored, the entry layout and fetch.json, the temporary directory and rename, a per-entry lock within a process, the rename retry on Windows, and credential redaction.
metadata.go FetchWithDependencies of LibraryReferences, AlzLibraryReference and CustomLibraryReference calls fetchLibrariesWithDependencies. Both reference types get an unexported setFS, so the walk can reuse a prefetched filesystem. The LibraryReference interface does not change.
internal/environment/environment.go ALZLIB_LIBRARY_STORE_ENABLED, read with strconv.ParseBool.
README.md Documents the concurrent fetch and the library store.
library_store_test.go, fetch_with_dependencies_test.go, internal/environment/environment_test.go (new) See Testing.
metadata_test.go The two existing FetchWithDependencies tests assert the exact order (Equal) instead of ElementsMatch.

How it works

Concurrent fetch, same order

  1. prefetchLibraries fetches the references and then, as soon as a library's metadata has been read, its dependencies, with at most four downloads at a time. Each library (by String()) is fetched once. Errors are not reported in this phase.
  2. libraryWalk then walks the references exactly as fetchLibraryWithDependencies did, using the prefetched filesystems. The walk fetches anything that was not prefetched, including a library whose prefetch failed. It therefore returns the same libraries, in the same order, with the same errors as before.

References created with NewCustomLibraryReferenceFromFS are not fetched, as before. LibraryReference implementations from outside this package are not prefetched; the walk fetches them as before.

A circular dependency now fails with circular dependency on library <reference>. On main, the walk fetches the cycle again and again until the context is cancelled or expires.

Library store

The store is disabled by default. When it is enabled:

  • What is stored: ALZ Library members, which are fetched at release tags (assumed never to move, see "Questions for reviewers"), and go-getter git URLs whose ref is a full, 40-character commit SHA. Everything else (local directories, branches and tags of custom libraries, other getters) is fetched to <ALZLIB_DIR>/<Instance>/<hash> as before.
  • Layout: <ALZLIB_DIR>/store/<SHA-224 of the go-getter URL>/ holds the library in lib/ and a fetch.json marker.
    • The key is the complete URL, so a mirror set with ALZLIB_LIBRARY_GIT_URL gets its own entries.
    • fetch.json records the URL without credentials (the URL's user information and the sshkey parameter are redacted), the SHA-256 of the complete URL, the alzlib version and the fetch time. This lets the store be shared through a CI/CD cache.
  • Publishing: a library is fetched into store/tmp-*, the marker is written, and the directory is renamed to the entry. Readers see either no entry or a complete one.
    • Within one process, goroutines take a per-entry lock, so the library is downloaded once.
    • There is no lock between processes. Processes that start on an empty store at the same time each download the library; the first rename wins, and the others drop their copy and use that entry.
    • On Windows, the rename is retried for up to 2 s while, for example, a virus scanner holds a new file, as the Go command does for its module cache.
  • Invalid entries: an entry without a valid marker for the URL, or without lib/, is neither used nor changed. The library is fetched as when the store is disabled.
  • No clean-up: nothing is removed from the store. Delete <ALZLIB_DIR>/store to clear it. A tmp-* directory left by an interrupted fetch is never used and can be deleted.

Testing

All tests were run locally on Windows 11 with Go 1.27.4, and golangci-lint with GOTOOLCHAIN=go1.25.2 as in CI. CI is authoritative, in particular for directory renames, which behave differently on Linux.

In-repo

  • go build ./..., go vet ./... and go test ./... pass. The 7 tests that need Azure credentials also pass with az login.
  • The new tests pass 3 runs in a row (-count=3), and with -race. golangci-lint v2.11.4 reports 0 issues in the changed packages.
  • library_store_test.go covers:
    • an ALZ Library member and a pinned custom library, each stored once and then reused without a download;
    • the store disabled, and the store enabled by the environment variable;
    • invalid entries, which are left untouched;
    • concurrent fetches in one process, which download once;
    • an entry added by another process, which is reused;
    • a rename while a file of the new entry is open (Windows);
    • several processes on one store;
    • which URLs count as pinned, and that credentials are kept out of fetch.json.
  • fetch_with_dependencies_test.go covers the order of the result, at most four downloads at a time, reuse of a prefetched library, a circular dependency, and that the first error in walk order is returned.

End-to-end suite outside the repo

This suite ran against this branch and against main (5461147), with local git repositories and a git wrapper that records every clone.

  • 21 store tests, 19 fetch tests, 2 stress tests (concurrent callers on random dependency graphs) and 4 process-level tests pass. The store, fetch and stress tests also pass with -race.
  • Against main, the 16 tests that check the new behaviour fail and the 24 tests that check unchanged behaviour pass.
  • On random dependency graphs, including shared and diamond dependencies, the order matches a reference implementation of the old walk.
  • alzlibtool generate architecture and alzlibtool document library produce byte-identical output for main, store disabled, cold store and warm store.
  • terraform-provider-alz v0.22.1 builds against this branch and its unit tests pass; acceptance tests were not run.
  • terraform plan with that build, ALZLIB_LIBRARY_STORE_ENABLED=true in terraform's environment, and a local copy of the Library:
    • The second plan spends 0.005 s between Begin fetch library dependencies and End fetch library dependencies, with no download.
    • alz_library_references is identical to that of the provider built against main.

Live, against github.com/Azure/Azure-Landing-Zones-Library on 2026-11-12 (fetch time, median of 3 runs):

Libraries main This PR, store disabled Store, cold Store, warm
platform/alz@2026.11.0 + platform/amba@2026.10.0 21.89 s 13.14 s (1.67×) 13.01 s 0.005 s, no download
platform/slz@2026.11.0 + platform/amba@2026.10.0 (3 libraries, slz depends on alz) 28.16 s 18.23 s (1.54×) 20.16 s 0.007 s, no download
  • main downloads one library at a time. This PR downloaded up to two at a time (as many as these dependency graphs allow), and never more than four.
  • For both sets, the following are identical between main, store disabled, cold store and warm store:
    • the libraries and their order;
    • the result of AlzLib.Init;
    • the output of alzlibtool document library;
    • the 321 files of alzlibtool generate architecture ... alz, generated with a built-in definitions cache read from Azure.
  • Four processes started at the same time on an empty store all succeed with identical results, and leave one complete entry per library and no tmp-* directory. Four more processes then fetch from the store in 6.5–9.4 ms each, with no download.

Backwards compatibility and upgrade impact

  • No new dependencies. The only public API additions are alzlib.LibraryStoreEnabled and the ALZLIB_LIBRARY_STORE_ENABLED environment variable. No signatures change, and the LibraryReference interface is unchanged.
  • With the store disabled (the default), the directories, downloads and result are the same as before, except that up to four git clones run at the same time.
  • If a fetch fails, libraries that come after the failing one may already have been downloaded by the prefetch. The returned error is unchanged.
  • A circular library dependency is now an error, instead of being fetched until the context is cancelled or expires.
  • With the store enabled, FetchAzureLandingZonesLibraryMember and FetchLibraryByGetterString ignore dstDir for stored libraries. They return a filesystem under <ALZLIB_DIR>/store, which is shared between processes and must not be modified.

Where this fits in Azure/Azure-Landing-Zones#4328

Item Where Status
1. cache_file_save_enabled saves an empty cache terraform-provider-alz Planned, separate PR
2. ConfigureProvider takes ~33–37 s on every command alzlib: this PR. terraform-provider-alz: bump alzlib, and a setting for the store This PR; provider follow-up after the alzlib release
3. ~700 per-definition ListBuiltIn requests alzlib, on top of #253, after measuring how many requests the latest-version listing can answer Planned
4. Ship #253 and make its parallelism configurable alzlib #253 (Azure/Azure-Landing-Zones#4310), then terraform-provider-alz #253 in review

This PR and #253 have no files in common.

Two suggestions of Item 2 are not in this PR:

  • depth=1 for Library tags: it brought no measurable benefit. A bare clone of the Library repository (about 8 MB) took 4.1–4.4 s in full, and 3.8–4.3 s with --depth 1 --branch <tag>.
  • DEBUG timings for library fetch, Init and cache load: these belong in terraform-provider-alz and come with Item 1.

Questions for reviewers

  1. Are ALZ Library release tags immutable? The store reuses an ALZ Library member by its tag. If a tag can move, each entry must also record the commit SHA and check it (for example with git ls-remote), or ALZ Library members must stay out of the store.
  2. Switch and default. For now the store is opt-in, through alzlib.LibraryStoreEnabled and ALZLIB_LIBRARY_STORE_ENABLED. Are these names fine? Should the store be enabled by default once a release has been in use for a while?
  3. Concurrency. The limit of four concurrent downloads is fixed. Should it be an option?

Out of scope

  • terraform-provider-alz work: bumping alzlib (after which the concurrent fetch applies to every plan and apply), a provider setting for the store, and documentation on caching ALZLIB_DIR in CI/CD. Until there is a setting, ALZLIB_LIBRARY_STORE_ENABLED=true in the pipeline environment enables the store for a provider built with this alzlib.
  • Removing old entries from the store, and the <ALZLIB_DIR>/<Instance> directories left by earlier runs.
  • Pre-existing issues found while testing, unchanged here:
    • processor.Client.Process leaves .json and .yaml files that are not library assets, such as alz_library_metadata.json, open until the garbage collector closes them. On Windows they cannot be deleted while the process runs.
    • Concurrent calls in one process that fetch the same mutable library with the same Instance share a destination directory.

Suggested release note

Performance: FetchWithDependencies fetches up to four libraries at the same time. The libraries are returned in the same order as before (Azure/Azure-Landing-Zones#4328).

Feature: opt-in library store. With ALZLIB_LIBRARY_STORE_ENABLED=true (or alzlib.LibraryStoreEnabled), ALZ Library members and libraries pinned to a commit SHA are fetched once into <ALZLIB_DIR>/store and reused by later runs and other processes. Cache ALZLIB_DIR in CI/CD to skip fetching them.

Behaviour change: a circular library dependency is reported as an error, instead of being fetched again and again until the context expires.

@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 71.70543% with 73 lines in your changes missing coverage. Please review.
✅ Project coverage is 56.42%. Comparing base (5461147) to head (b73ec71).

Files with missing lines Patch % Lines
library_store.go 58.74% 49 Missing and 10 partials ⚠️
initialize.go 89.32% 7 Missing and 4 partials ⚠️
metadata.go 66.66% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #255      +/-   ##
==========================================
+ Coverage   55.87%   56.42%   +0.55%     
==========================================
  Files          56       57       +1     
  Lines        5264     5485     +221     
==========================================
+ Hits         2941     3095     +154     
- Misses       2003     2056      +53     
- Partials      320      334      +14     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

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

This branch was successfully deployed

1 active deployment
test — b73ec71b Deployed Nov 12, 2026 by Y1ngJ1eChen via test (windows-latest) #699
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants