Eine aufbereitete Darstellung der Quelle

 
     
 
 
 
Anforderungen  |   Konzepte  |   Entwurf  |   Entwicklung  |   Qualitätssicherung  |   Lebenszyklus  |   Steuerung


Quelle  Test.lean   Sprache: Lean

 

/-
Copyright (c) 2026 Marcelo Lynch. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Marcelo Lynch
-/

module

public import Cache.Cli
public import Cache.Lean
public import Cache.Location
public import Cache.Marker
public import Cache.Query
public import Cache.Requests
public import Cache.Upload
public import Cache.Warning

/-!
# Unit tests for the cache CLI

These tests cover the pure logic of the cache system, including:
- Container model (trust levels, URL shapes)
- Trust-ordered fallback chains per repo
- URL construction (`Location`) with support for per-SHA scoping
- CLI flag parsing (`--cache-from`, `--scope`, `--unsafe`, `--repo`, etc.)
- `--unsafe` read locations (`readLocationsFrom`) and the
  non-default-scope security warning it triggers
- Decompression-pipeline carry across download rounds (`DecompState`,
  `finalizeDecomp`, `monitorCurl`)
- Transfer classification (`classifyDownload`/`classifyUpload`): delivered,
  miss, skip, or failed, per HTTP status and curl exit code
- The two retry-flag tiers (`curlRetryArgs`)
- Failure-line diagnostics (`splitWriteOut`, `transferDiagnostics`)
- Utility functions (URL extraction, filename hashing, etc.)

Anything that touches the network is left to CI, which exercises the
`cache get`/`put` paths end-to-end on real containers. The unit tests spawn
local processes only: `curl --version`, one curl `file://` copy, and one
leantar run on a nonexistent archive; none makes a network request.

## Invariants these tests defend

1. Trust boundary per container: each container has a dedicated writer (an
   OIDC-scoped credential per container) and reads follow a per-repo
   trust-ordered list, so a PR cannot upload to a higher-trust container.
2. Per-SHA namespace for fork uploads: fork uploads land at `/f/{repo}/{sha}/{hash}`,
   so one commit's artifacts never serve another commit on the same fork.
3. Flat layout for single-writer containers: `master` reads and writes flat at
   `/f/{hash}`, the path older tools also use.
4. Prefixed layout for the multi-writer container: `forks` namespaces by repo
   so uploads from different sources don't collide.
5. Multi-round downloads decompress every file they fetch: the decompression
   pipeline state is carried from each download round into the next and
   drained after the last one, so a fork-PR `get` leaves no downloaded file
   compressed on disk.
7. Missing-file guidance is keyed on the download's outcome, not on upfront
   proxies: a read fully served by the locations prints nothing, and the
   fork-workflow hint replaces the generic divergence warning only for naive
   fork reads whose HEAD has no published fork cache.

## Running the tests

Run with `lake exe cache-test`. Exits 0 on success, non-zero on failure.

The tests stand alone (no dependency on `MathlibTest`). A Lake package has a
single `testDriver`, and the enclosing `mathlib` package binds that to
`MathlibTest` (see `lakefile.lean`); if the cache tool moves to its own Lake
project, the `cache-test` `lean_exe` here can become that project's `testDriver`.
-/


namespace Cache.Test

open Cache.Requests

/-- Counter for failed assertions. -/
initialize failures : IO.Ref Nat ← IO.mkRef 0

/-- A single named assertion. On failure, prints details and bumps the counter. -/
def assertTrue (name : String) (cond : Bool) : IO Unit := do
  if cond then
    IO.println s!"  ok: {name}"
  else
    IO.eprintln s!"  FAIL: {name}"
    failures.modify (· + 1)

/-- Assert two strings are equal; show both on failure. -/
def assertEq (name expected actual : String) : IO Unit := do
  if expected == actual then
    IO.println s!"  ok: {name}"
  else
    IO.eprintln s!"  FAIL: {name}\n    expected: {expected}\n    actual:   {actual}"
    failures.modify (· + 1)

/-- Run `body` with the `--scope=` override (`scopeOverride`) restored on
completion, including on exception, so a test that sets it leaves the tests
after it unaffected. -/

private def withSavedScopeOverride (body : IO Unit) : IO Unit := do
  let saved ← scopeOverride.get
  try body finally scopeOverride.set saved

/-- Run `action` with both stdout and stderr redirected to the platform null
device. Restores both on completion, including on exception. Apply this to every
production code call in tests so diagnostic prints never mix with test output,
regardless of whether the production code currently produces any. -/

private def withSuppressedOutput (action : IO α) : IO α := do
  let savedOut ← IO.getStdout
  let savedErr ← IO.getStderr
  let sink ← IO.FS.Handle.mk Cache.IO.nullDevice IO.FS.Mode.append
  let sinkStream := IO.FS.Stream.ofHandle sink
  -- `IO.setStdout`/`IO.setStderr` return the previous stream; we already saved it,
  -- so discard the return value here.
  discard <| IO.setStdout sinkStream
  discard <| IO.setStderr sinkStream
  try
    let r ← action
    discard <| IO.setStdout savedOut
    discard <| IO.setStderr savedErr
    return r
  catch e =>
    discard <| IO.setStdout savedOut
    discard <| IO.setStderr savedErr
    throw e

/-- Run a cache action with a controlled Mathlib path and suppress its diagnostics. -/
private def withSuppressedCacheOutput (action : IO.CacheM α)
    (mathlibDepPath : System.FilePath := ".") : IO α :=
  withSuppressedOutput (ReaderT.run action { mathlibDepPath, srcSearchPath := [] })

section ContainerModel

/-- The short name is the string used on the CLI (`--container=NAME`) and to
derive the container's path segment. These names are part of the public CLI
contract, so they are pinned here: a rename must be a deliberate edit to this
test, not an accident. -/

def test_Container_name : IO Unit := do
  IO.println "Container.name:"
  assertEq "master"             "master"             Container.master.name
  assertEq "forks"              "forks"              Container.forks.name

/-- Parser is the inverse of `Container.name` on valid inputs, and rejects everything else. -/
def test_Container_parse : IO Unit := do
  IO.println "Container.parse?:"
  -- Every canonical name round-trips back to its enum case.
  assertTrue "master parses"          (Container.parse? "master" == some .master)
  assertTrue "forks parses"           (Container.parse? "forks" == some .forks)
  -- Matching is case-insensitive, so `--container=Master` canonicalizes too.
  assertTrue "case-insensitive"       (Container.parse? "Master" == some .master)
  -- An unknown name returns `none` so `--container=bogus` errors out rather than
  -- defaulting to some container the user didn't ask for.
  assertTrue "unknown rejected"       (Container.parse? "bogus" == none)
  assertTrue "empty rejected"         (Container.parse? "" == none)

/-- A variable that names a read URL or a read chain arrives trimmed, and an
empty or whitespace-only value means unset. `MATHLIB_CACHE_BASE_URL`,
`MATHLIB_CACHE_GET_URL`, and `MATHLIB_CACHE_FROM` follow that rule. CI wires
them from a GitHub Actions `vars` lookup, which yields `""` for an undefined
variable, and such a value behaves as an absent one. The upload endpoint
`MATHLIB_CACHE_PUT_URL` keeps the opposite rule: an empty value there fails the
upload rather than divert it to the fallback container. -/

def test_envValueNormalization : IO Unit := do
  IO.println "nonEmptyEnvValue / normalizeBaseURL:"
  -- `<unset>` stands in for `none`, so a failure shows both sides as strings.
  let shown (value? : Option String) : String := value?.getD "<unset>"
  assertEq "absent value reads as unset" "<unset>" (shown (nonEmptyEnvValue none))
  assertEq "empty value reads as unset" "<unset>" (shown (nonEmptyEnvValue (some "")))
  assertEq "whitespace-only value reads as unset" "<unset>"
    (shown (nonEmptyEnvValue (some " \n")))
  assertEq "value is trimmed" "master,forks" (shown (nonEmptyEnvValue (some " master,forks\n")))
  assertEq "URL keeps its own path" "https://cache.example.org/mathlib4"
    (shown (normalizeBaseURL (some "https://cache.example.org/mathlib4")))
  assertEq "trailing slashes are stripped" "https://cache.example.org"
    (shown (normalizeBaseURL (some "https://cache.example.org///")))
  assertEq "a slash-only value reads as unset" "<unset>" (shown (normalizeBaseURL (some "/")))

/-- `getBaseURLFrom` returns `MATHLIB_CACHE_BASE_URL` when the variable is set, and
`publicCacheEndpoint` otherwise. -/

def test_getBaseURLFrom : IO Unit := do
  IO.println "getBaseURLFrom:"
  assertEq "no override → the read endpoint"
    "https://cache.mathlib.org" (getBaseURLFrom none)
  assertEq "override → the given base"
    "https://cache.example.org" (getBaseURLFrom (some "https://cache.example.org"))
  -- A GitHub Actions `${{ vars.… }}` lookup yields "" while the variable is
  -- undefined, so an empty value must keep the default.
  assertEq "empty value counts as unset"
    publicCacheEndpoint (getBaseURLFrom (some ""))

end ContainerModel

section PerRepoAllowlist

/-- Trust-ordered read chain per GitHub repo: the tool tries containers in this
order and stops at the first hit, so both membership and ordering are part of
the trust boundary. Key points the tests pin:
- The fork chain leads with `master` (shared upstream deps), then `forks`
  (PR-specific files).
-/

def test_defaultContainersForRepo : IO Unit := do
  IO.println "defaultContainersForRepo:"
  assertTrue "canonical repo → [master]"
    (defaultContainersForRepo MATHLIBREPO == [.master])
  assertTrue "fork repo → [master, forks]"
    (defaultContainersForRepo "alice/mathlib4" == [.master, .forks])
  assertTrue "unknown repo falls back to the fork chain"
    (defaultContainersForRepo "some/other-repo" == [.master, .forks])

/-- `effectiveGetBases` pairs the lookup chain with read bases in trust order.
This test covers the default chain and the `--cache-from` override. The
`MATHLIB_CACHE_GET_URL` and `MATHLIB_CACHE_FROM` branches need process state,
so the CI integration tests exercise them instead. -/

def test_effectiveGetBases : IO Unit := do
  IO.println "effectiveGetBases:"
  if (← getEnvNonEmpty "MATHLIB_CACHE_GET_URL").isSome ||
      (← getEnvNonEmpty "MATHLIB_CACHE_FROM").isSome then
    IO.println "  skipped: MATHLIB_CACHE_GET_URL or MATHLIB_CACHE_FROM is set"
    return
  let base ← getBaseURL
  assertTrue "default chain pairs each container with its read base"
    ((← effectiveGetBases MATHLIBREPO) ==
      [(some .master, base)])
  cacheFromOverride.set (some [.forks, .master])
  assertTrue "--cache-from override keeps its order"
    ((← effectiveGetBases MATHLIBREPO) ==
      [(some .forks, base), (some .master, base)])
  cacheFromOverride.set none

end PerRepoAllowlist

section FileURL

/-- The file URL of one read location from a base or endpoint, with no HEAD
fallback. -/

def fileURLOf (container? : Option Container) (repo url fileName : String)
    (scope? : Option String := none) : String :=
  ((readLocationsFrom repo [(container?, url)] scope? []).head!).fileURL fileName

/-- URL construction for a cache file. The path shape follows the container
(`Container.flatPath`), not the repo, so the same repo lands flat in `master`
and prefixed in `forks`. A `none` container is the user-supplied-URL case
(`MATHLIB_CACHE_GET_URL` / `_PUT_URL`), where the shape follows the repo alone.

A per-SHA scope (`MATHLIB_CACHE_REPO_SCOPE`) inserts `{sha}` between repo and
hash on prefixed paths only — `/f/{repo}/{sha}/{hash}` — keeping each commit's
fork uploads in their own namespace. Flat paths ignore the scope.
-/

def test_fileURL : IO Unit := do
  IO.println "Location.fileURL:"
  let base := "https://cache.example.org"
  assertEq "master is flat for the canonical repo"
    "https://cache.example.org/mathlib4-master/f/abc.ltar"
    (fileURLOf (some .master) MATHLIBREPO base "abc.ltar")
  assertEq "master is flat for a fork repo too"
    "https://cache.example.org/mathlib4-master/f/abc.ltar"
    (fileURLOf (some .master) "alice/mathlib4" base "abc.ltar")
  -- `forks` prefixes by repo even for the canonical repo, so its fork-trust
  -- uploads don't collide with fork uploads in the same container.
  assertEq "forks prefixes by repo for the canonical repo"
    "https://cache.example.org/mathlib4-forks/f/leanprover-community/mathlib4/abc.ltar"
    (fileURLOf (some .forks) MATHLIBREPO base "abc.ltar")
  assertEq "forks prefixes by repo for a fork repo"
    "https://cache.example.org/mathlib4-forks/f/alice/mathlib4/abc.ltar"
    (fileURLOf (some .forks) "alice/mathlib4" base "abc.ltar")
  -- No container (user-supplied URL): the shape follows the repo — flat for the
  -- canonical repo, prefixed otherwise.
  assertEq "user URL is flat for the canonical repo"
    "https://custom.example/cache/f/abc.ltar"
    (fileURLOf none MATHLIBREPO "https://custom.example/cache" "abc.ltar")
  assertEq "user URL prefixes by repo for a fork repo"
    "https://custom.example/cache/f/alice/mathlib4/abc.ltar"
    (fileURLOf none "alice/mathlib4" "https://custom.example/cache" "abc.ltar")
  -- A scope adds a `{sha}` path segment on prefixed paths.
  assertEq "scope adds a SHA segment on a fork path"
    "https://cache.example.org/mathlib4-forks/f/alice/mathlib4/abc123def/H.ltar"
    (fileURLOf (some .forks) "alice/mathlib4" base "H.ltar" (some "abc123def"))
  assertEq "scope adds a SHA segment on the canonical repo's forks path"
    "https://cache.example.org/mathlib4-forks/f/leanprover-community/mathlib4/abc123def/H.ltar"
    (fileURLOf (some .forks) MATHLIBREPO base "H.ltar" (some "abc123def"))
  -- A scope is ignored on flat paths.
  assertEq "scope is ignored on a flat master path"
    "https://cache.example.org/mathlib4-master/f/abc.ltar"
    (fileURLOf (some .master) MATHLIBREPO base "abc.ltar" (some "abc123def"))
  -- The repo segment is lowercased, so a mixed-case GitHub owner resolves to the
  -- same path whether it reaches the cache from CI or a local remote URL.
  assertEq "fork repo is lowercased in the path"
    "https://cache.example.org/mathlib4-forks/f/alice/mathlib4/abc.ltar"
    (fileURLOf (some .forks) "Alice/Mathlib4" base "abc.ltar")

end FileURL

section ParseCacheFromList

/-- Parser for `--cache-from=a,b,c`. List order is the trust order tried at
download time, so it is preserved exactly. The parser is strict: one bad name
or empty input fails the whole list rather than degrading to a default, so a
typo surfaces instead of silently changing where the cache is read. -/

def test_parseCacheFromList : IO Unit := do
  IO.println "parseCacheFromList:"
  assertTrue "both containers"
    (parseCacheFromList "master,forks" == some [.master, .forks])
  -- Order is preserved, not normalized: `forks,master` reverses the priority.
  assertTrue "preserves the given order"
    (parseCacheFromList "forks,master" == some [.forks, .master])
  -- Whitespace around commas is tolerated, so the flag survives shell expansion.
  assertTrue "whitespace around names is tolerated"
    (parseCacheFromList " master , forks " == some [.master, .forks])
  assertTrue "one unknown name rejects the whole list"
    (parseCacheFromList "master,bogus" == none)
  assertTrue "empty input is rejected"
    (parseCacheFromList "" == none)

end ParseCacheFromList

section ExtractRepoFromUrl

/-- Parses `owner/name` from a git remote URL. The result selects the per-repo
read chain, so misreading a fork as the canonical repo would read the wrong
chain; these cases cover every URL shape git emits via `git remote get-url` or a
direct remote (e.g. `gh pr checkout`). Unparseable input returns `none`, and the
caller falls back to `MATHLIBREPO`. -/

def test_extractRepoFromUrl : IO Unit := do
  IO.println "extractRepoFromUrl:"
  assertTrue "ssh URL with .git suffix"
    (extractRepoFromUrl "git@github.com:alice/mathlib4.git" == some "alice/mathlib4")
  assertTrue "ssh URL without .git suffix"
    (extractRepoFromUrl "git@github.com:alice/mathlib4" == some "alice/mathlib4")
  assertTrue "https URL with .git suffix"
    (extractRepoFromUrl "https://github.com/alice/mathlib4.git" == some "alice/mathlib4")
  assertTrue "https URL without .git suffix"
    (extractRepoFromUrl "https://github.com/alice/mathlib4" == some "alice/mathlib4")
  -- A hyphenated owner is part of the repo identity and must survive intact.
  assertTrue "hyphenated owner is preserved"
    (extractRepoFromUrl "https://github.com/leanprover-community/mathlib4.git" == some "leanprover-community/mathlib4")
  assertTrue "empty input returns none"
    (extractRepoFromUrl "" == none)
  assertTrue "a token with no slash or colon returns none"
    (extractRepoFromUrl "norepo" == none)

end ExtractRepoFromUrl

section ExtractPRNumber

/-- Extracts a PR number from a git ref. The contract is "second-to-last
segment must be `pr`, last must be a Nat". -/

def test_extractPRNumber : IO Unit := do
  IO.println "extractPRNumber:"
  -- The shape git produces for fetched PR refs.
  assertTrue "standard PR ref format"
    (extractPRNumber "refs/remotes/upstream/pr/1234" == some 1234)
  -- Branch refs are not PR refs; must not match.
  assertTrue "master branch returns none"
    (extractPRNumber "refs/heads/master" == none)
  -- Minimal `pr/N` is also accepted — the parser only inspects the trailing two segments.
  assertTrue "simple pr number"
    (extractPRNumber "pr/42" == some 42)
  -- The tail must be a valid Nat; non-numeric tails are rejected (no partial parsing).
  assertTrue "non-numeric tail returns none"
    (extractPRNumber "refs/remotes/upstream/pr/foo" == none)
  -- `0` is a valid Nat; pin down that it isn't special-cased.
  assertTrue "zero PR number"
    (extractPRNumber "refs/remotes/upstream/pr/0" == some 0)
  -- A numeric tail without the `pr/` parent must not be mistaken for a PR ref.
  assertTrue "missing pr segment returns none"
    (extractPRNumber "refs/remotes/upstream/42" == none)

end ExtractPRNumber

section HashFromFileName

/-- Recovers the UInt64 cache hash from a cached file's path, the inverse of
`UInt64.asLTar`. The subtle cases are the in-flight suffixes curl writes during a
download: today's process-tagged `.ltar.<pid>.part` (see `IO.PARTSUFFIX`) and the
untagged `.ltar.part` a cache from before tagging may have left in the shared
directory. A regression here corrupts cache lookups, so every suffix and a
non-hex stem are covered. -/

def test_hashFromFileName : IO Unit := do
  IO.println "hashFromFileName:"
  assertTrue "plain .ltar file"
    (hashFromFileName "abc123def.ltar" == String.parseHexToUInt64? "000000abc123def")
  assertTrue "in-flight process-tagged .part file strips all three suffixes"
    (hashFromFileName "abc123def.ltar.31415.part" == String.parseHexToUInt64? "000000abc123def")
  assertTrue "legacy untagged .ltar.part file strips both suffixes"
    (hashFromFileName "abc123def.ltar.part" == String.parseHexToUInt64? "000000abc123def")
  assertTrue "the tag this process actually writes round-trips"
    (hashFromFileName ("abc123def.ltar" ++ IO.PARTSUFFIX) ==
      String.parseHexToUInt64? "000000abc123def")
  assertTrue "full 16-digit hex stem"
    (hashFromFileName "deadbeef00112233.ltar" == String.parseHexToUInt64? "deadbeef00112233")
  -- A non-hex stem returns none rather than a garbage hash.
  assertTrue "non-hex stem returns none"
    (hashFromFileName "nothexa.ltar" == none)
  assertTrue "non-hex stem returns none for a tagged part file too"
    (hashFromFileName "nothexa.ltar.31415.part" == none)
  -- Directory components are ignored; only the basename's stem is parsed.
  assertTrue "leading path is ignored"
    (hashFromFileName "/path/to/abc123def.ltar" == String.parseHexToUInt64? "000000abc123def")

end HashFromFileName

section TempFileNames

/-- Every temporary file `cache` writes into the shared `CACHEDIR` carries this process's
tag, so two runs in flight in one cache directory cannot write each other's curl
configuration or each other's partial downloads. The `.part` ending is load-bearing
beyond uniqueness: the download monitor keys both its rename-on-success and its
remove-on-error off it. -/

def test_tempFileNames : IO Unit := do
  IO.println "temporary file names:"
  assertTrue "the process tag is non-empty" (!IO.PROCTAG.isEmpty)
  assertTrue "the in-flight suffix still ends in .part" (IO.PARTSUFFIX.endsWith ".part")
  assertTrue "the in-flight suffix is tagged, not a bare .part" (IO.PARTSUFFIX != ".part")
  assertTrue "the in-flight suffix carries the tag" ((IO.PARTSUFFIX.splitOn IO.PROCTAG).length == 2)
  assertTrue "the curl config carries the tag"
    ((IO.CURLCFG.toString.splitOn IO.PROCTAG).length == 2)
  assertTrue "the curl config sits in the cache directory"
    (IO.CURLCFG.parent == some IO.CACHEDIR)
  assertTrue "an upload's curl config sits under the given directory"
    ((IO.curlConfigIn "staging").parent == some "staging")
  assertTrue "an upload's curl config carries the same tagged name"
    ((IO.curlConfigIn "staging").fileName == IO.CURLCFG.fileName)
  -- The tag must not reintroduce a path separator or a shell/curl-config hazard.
  assertTrue "the tag is a bare identifier" (IO.PROCTAG.all fun c => c.isAlphanum)

end TempFileNames

section IsRemoteURL

/-- Discriminator: is this string a remote URL (vs a local filesystem path)?
Used to decide whether to short-circuit `git remote get-url` lookups. -/

def test_isRemoteURL : IO Unit := do
  IO.println "isRemoteURL:"
  -- The three protocols accepted by the cache tool.
  assertTrue "https URL is remote"
    (isRemoteURL "https://github.com/alice/mathlib4.git" == true)
  assertTrue "http URL is remote"
    (isRemoteURL "http://github.com/alice/mathlib4" == true)
  assertTrue "ssh URL is remote"
    (isRemoteURL "git@github.com:alice/mathlib4.git" == true)
  -- Absolute and relative local paths must be classified as not-remote so they
  -- get routed through `git remote get-url`.
  assertTrue "local path is not remote"
    (isRemoteURL "/local/path/to/repo" == false)
  assertTrue "relative path is not remote"
    (isRemoteURL "./local/repo" == false)
  -- Defensive — empty input shouldn't accidentally match the predicate.
  assertTrue "empty string is not remote"
    (isRemoteURL "" == false)

end IsRemoteURL

section UInt64Formatting

/-- Filename derived from a cache hash: exactly 16 lowercase hex digits plus
`.ltar`. The fixed width makes the hash ↔ filename mapping unique and
invertible — without it, `0x1` and `0x01` would share a stem and collide. -/

def test_UInt64_asLTar : IO Unit := do
  IO.println "UInt64.asLTar:"
  assertEq "small value is left-padded to 16 digits"
    "0000000000000001.ltar"
    (1 : UInt64).asLTar
  assertEq "mid-width value is left-padded"
    "0000000000abc123.ltar"
    (0xabc123 : UInt64).asLTar
  assertEq "full-width value is not truncated"
    "deadbeef00112233.ltar"
    (0xdeadbeef00112233 : UInt64).asLTar
  assertEq "zero is padded, not emptied"
    "0000000000000000.ltar"
    (0 : UInt64).asLTar
  -- Max value is 16 lowercase `f`s; the parser elsewhere is case-sensitive.
  assertEq "max value is lowercase hex"
    "ffffffffffffffff.ltar"
    (0xffffffffffffffff : UInt64).asLTar

end UInt64Formatting

section RoundTrip

/-- `asLTar` then `hashFromFileName` must return the original hash — the property
that lets the filename serve as the cache key. A padding or truncation bug would
read a file back as a different hash, causing misses or collisions. -/

def test_hash_roundtrip : IO Unit := do
  IO.println "hash roundtrip (asLTar then hashFromFileName):"
  let h1 : UInt64 := 0xdeadbeef00112233
  assertTrue "full-width hash round-trips"
    (hashFromFileName h1.asLTar == some h1)
  -- A short hash exercises both pad-on-write and trim-on-read.
  let h2 : UInt64 := 0xabc123
  assertTrue "padded hash round-trips"
    (hashFromFileName h2.asLTar == some h2)

end RoundTrip

section Marker

/-- URL shape of the per-SHA marker that `cache put` writes and `cache query`
probes with a HEAD request (`Location.markerURL?`). The marker lives at
`/m/{repo}/{sha}` under the location's root. A 200 HEAD response signals that
all artifacts for the commit were uploaded. -/

def test_markerURL : IO Unit := do
  IO.println "Location.markerURL?:"
  let dest (container? : Option Container) (putBase? : Option String) : String :=
    ((uploadLocationFrom .s3 none putBase? container? "alice/mathlib4"
      (some "abc123")).toOption.bind (·.markerURL?)).getD "(unresolved)"
  -- The marker lives under `/m/`, its own namespace, and is keyed by repo.
  assertEq "marker is under /m/, keyed by repo"
    "m/leanprover-community/mathlib4/deadbeef"
    (((Container.forks.location "U" MATHLIBREPO (some "deadbeef")).marker?.map
      (·.path)).getD "(no marker)")
  -- A put base rebases the marker with the artifacts it marks: both use one
  -- location, rooted at `{base}/{container}` (`uploadLocationFrom`).
  assertEq "marker URL follows a rebased upload destination"
    "https://bucket.example.org/mirror/mathlib4-forks/m/alice/mathlib4/abc123"
    (dest (some .forks) (some "https://bucket.example.org/mirror"))
  -- The repo segment is lowercased, so an upload and a probe for the same fork
  -- meet at one path regardless of how the owner name was capitalized.
  assertEq "marker repo is lowercased in the path"
    "m/alice/mathlib4/abc123"
    (((Container.forks.location "U" "Alice/Mathlib4" (some "abc123")).marker?.map
      (·.path)).getD "(no marker)")

/-- `markerProbeURL` builds the marker probe URL on the read base, and
`Location.markerURL?` builds the marker write URL on the upload location. -/

def test_markerProbeURL : IO Unit := do
  IO.println "markerProbeURL:"
  let base ← getBaseURL
  assertEq "probe URL follows the read base"
    s!"{base}/mathlib4-forks/m/alice/mathlib4/abc123"
    ((← markerProbeURL .forks "alice/mathlib4" "abc123").getD "(no marker)")
  assertEq "probe repo is lowercased in the path"
    s!"{base}/mathlib4-forks/m/alice/mathlib4/abc123"
    ((← markerProbeURL .forks "Alice/Mathlib4" "abc123").getD "(no marker)")
  assertTrue "a flat container has no marker to probe"
    ((← markerProbeURL .master MATHLIBREPO "abc123").isNone)

end Marker

section ScopeResolution

/-- `getRepoScope` answers "is the user reading from a SHA-scoped namespace?".
It reads the `--scope=` flag (the `scopeOverride` ref) first, then the
`MATHLIB_CACHE_REPO_SCOPE` env var, so an explicit flag is never overridden by
an inherited env var. The flag value is returned as given. The env-var branch
needs process state, so it is exercised by the CI integration tests rather than
here. -/

def test_getRepoScope : IO Unit := do
  IO.println "getRepoScope:"
  withSavedScopeOverride do
    scopeOverride.set none
    assertTrue "no scope set returns none" ((← withSuppressedOutput getRepoScope) == none)

    scopeOverride.set (some "abc123")
    assertTrue "the flag value is returned" ((← withSuppressedOutput getRepoScope) == some "abc123")

    -- The flag value is returned as-is, without trimming or normalization.
    scopeOverride.set (some "deadbeef")
    assertTrue "the flag value is returned verbatim"
      ((← withSuppressedOutput getRepoScope) == some "deadbeef")

    scopeOverride.set none
    assertTrue "clearing the flag returns none" ((← withSuppressedOutput getRepoScope) == none)

end ScopeResolution

section ReadLocations

/-- Exercise the read resolver, including the HEAD fallback and the order of
unsafe rounds. Expected paths do not use the location builders. -/

def test_readLocations : IO Unit := do
  IO.println "readLocations:"
  if (← getEnvNonEmpty "MATHLIB_CACHE_GET_URL").isSome ||
      (← getEnvNonEmpty "MATHLIB_CACHE_FROM").isSome ||
      (← getEnvNonEmpty "MATHLIB_CACHE_REPO_SCOPE").isSome ||
      (← getEnvNonEmpty "GIT_DIR").isSome ||
      (← getEnvNonEmpty "GIT_WORK_TREE").isSome then
    IO.println "  skipped: cache read overrides or Git directory overrides are set"
    return
  let savedContainers ← cacheFromOverride.get
  let savedScope ← scopeOverride.get
  let cwd ← IO.Process.getCurrentDir
  let dir ← IO.FS.createTempDir
  try
    -- A temporary checkout makes HEAD resolution independent of the caller's checkout.
    discard <| IO.runCmd "git" #["init", "--quiet", "--template=", dir.toString]
    IO.Process.setCurrentDir dir
    discard <| IO.runCmd "
git" #["-c", "user.name=cache-test", "-c",
      "
user.email=cache-test@example.invalid", "-c", "commit.gpgsign=false",
      "
commit", "--quiet", "--allow-empty", "--no-verify", "-m", "cache test"]
    let head := (← IO.runCmd "git" #["log", "-1", "--format=%H"]).trimAsciiEnd.copy
    let base ← getBaseURL
    let paths (locations : List Location) :=
      locations.map fun l => (l.fileURL "
x.ltar", l.sha?, l.label)
    cacheFromOverride.set none
    scopeOverride.set none
    assertTrue "
the default fork chain uses HEAD only for forks"
      (paths (← withSuppressedCacheOutput (readLocations "
Alice/Mathlib4") dir) ==
        [(s!"
{base}/mathlib4-master/f/x.ltar", none, "master"),
         (s!"
{base}/mathlib4-forks/f/alice/mathlib4/{head}/x.ltar", some head, "forks")])
    assertTrue "
the canonical default chain contains only master"
      (paths (← withSuppressedCacheOutput (readLocations MATHLIBREPO) dir) ==
        [(s!"
{base}/mathlib4-master/f/x.ltar", none, "master")])
    scopeOverride.set (some "
abc1")
    assertTrue "
an explicit scope replaces HEAD"
      (paths (← withSuppressedCacheOutput (readLocations "
Alice/Mathlib4") dir) ==
        [(s!"
{base}/mathlib4-master/f/x.ltar", none, "master"),
         (s!"
{base}/mathlib4-forks/f/alice/mathlib4/abc1/x.ltar", some "abc1", "forks")])
    cacheFromOverride.set (some [.forks, .master])
    assertTrue "
unsafe rounds preserve the requested container and SHA order"
      (paths (← withSuppressedCacheOutput (readLocations "
Alice/Mathlib4" ["abc2", "abc3"]) dir) ==
        [(s!"
{base}/mathlib4-forks/f/alice/mathlib4/abc2/x.ltar", some "abc2", "forks"),
         (s!"
{base}/mathlib4-forks/f/alice/mathlib4/abc3/x.ltar", some "abc3", "forks"),
         (s!"
{base}/mathlib4-master/f/x.ltar", none, "master")])
    cacheFromOverride.set (some [])
    assertTrue "
an empty container override produces no locations"
      ((← withSuppressedCacheOutput (readLocations "
alice/mathlib4") dir).isEmpty)
  finally
    IO.Process.setCurrentDir cwd
    cacheFromOverride.set savedContainers
    scopeOverride.set savedScope
    IO.FS.removeDirAll dir

/-- Scope refs and default fork reads use Mathlib's HEAD, even from a downstream checkout. -/
def test_mathlibGitLookups : IO Unit := do
  IO.println "
Mathlib Git lookup context:"
  if (← getEnvNonEmpty "
GIT_DIR").isSome ||
      (← getEnvNonEmpty "
GIT_WORK_TREE").isSome ||
      (← getEnvNonEmpty "
MATHLIB_CACHE_GET_URL").isSome ||
      (← getEnvNonEmpty "
MATHLIB_CACHE_FROM").isSome ||
      (← getEnvNonEmpty "
MATHLIB_CACHE_REPO_SCOPE").isSome then
    IO.println "
  skipped: cache read overrides or Git directory overrides are set"
    return
  let savedScope ← scopeOverride.get
  let savedContainers ← cacheFromOverride.get
  let cwd ← IO.Process.getCurrentDir
  let dir ← IO.FS.createTempDir
  let mathlibPath := dir / "
mathlib"
  let downstreamPath := dir / "
downstream"
  let git (path : System.FilePath) (args : Array String) : IO String := do
    let out ← IO.Process.output { cmd := "
git", args, cwd := path }
    unless out.exitCode == 0 do
      throw <| IO.userError s!"
test git command failed: {out.stderr}"
    return out.stdout.trimAscii.toString
  try
    -- Different commit messages give the two checkouts different HEADs.
    for (path, message) in [(mathlibPath, "
mathlib"), (downstreamPath, "downstream")] do
      IO.FS.createDirAll path
      discard <| git path #["
init", "--quiet", "--template="]
      discard <| git path #["-c", "user.name=cache-test", "-c",
        "user.email=cache-test@example.invalid", "-c", "commit.gpgsign=false",
        "commit", "--quiet", "--allow-empty", "--no-verify", "-m", message]
    let mathlibHead ← git mathlibPath #["
rev-parse", "HEAD"]
    IO.Process.setCurrentDir downstreamPath
    scopeOverride.set none
    cacheFromOverride.set none
    assertEq "
scope refs resolve in the Mathlib checkout" mathlibHead
      (← withSuppressedCacheOutput (resolveGitRef "
HEAD") mathlibPath)
    let locations ← withSuppressedCacheOutput (readLocations "
alice/mathlib4") mathlibPath
    assertTrue "
the default fork read uses Mathlib's HEAD scope"
      (locations.map (·.sha?) == [none, some mathlibHead])
  finally
    IO.Process.setCurrentDir cwd
    scopeOverride.set savedScope
    cacheFromOverride.set savedContainers
    IO.FS.removeDirAll dir

end ReadLocations

section NonDefaultScope

/-- `shouldWarnNonDefaultScope` decides whether `cache get` prints the
non-default-scope security warning. It warns when any of three inputs takes the
reader off the repo's default trust boundary:

1. a scope is set (`--scope=` or `MATHLIB_CACHE_REPO_SCOPE`) and differs from
   the checked-out HEAD;
2. `--cache-from=LIST` differs from the repo's default chain (passing the
   default explicitly is not widening);
3. `--repo=` is given and differs from the detected git remote, or names a
   non-canonical repo with no detectable remote to compare against.

The behavior the tests pin most carefully: a plain `cache get` with no flags
never warns, even on a fork checkout whose remote isn't the canonical repo.
`detectedRepo?` is passed in (resolved once by `resolveRepo`), so the cases are
deterministic without needing a real checkout. -/
def test_shouldWarnNonDefaultScope : IO Unit := do
  IO.println "
shouldWarnNonDefaultScope:"
  withSavedScopeOverride do
    scopeOverride.set none

    assertTrue "
plain get with no flags does not warn"
      (!(← withSuppressedCacheOutput (shouldWarnNonDefaultScope none none none MATHLIBREPO)))

    scopeOverride.set (some "
abc123")
    assertTrue "
a set scope warns"
      (← withSuppressedCacheOutput (shouldWarnNonDefaultScope none none none MATHLIBREPO))
    scopeOverride.set none

    -- A scope equal to HEAD is trust-equivalent to no scope (CI's normal mode).
    -- Skipped when HEAD can't be resolved (not in a git checkout).
    let head? ← try some <$> withSuppressedCacheOutput getGitCommitHash catch _ => pure none
    if let some head := head? then
      scopeOverride.set (some head)
      assertTrue "
a scope equal to HEAD does not warn"
        (!(← withSuppressedCacheOutput (shouldWarnNonDefaultScope none none none MATHLIBREPO)))
      scopeOverride.set none

    -- --cache-from equal to the repo's default chain is not widening.
    let mathlibDefault := defaultContainersForRepo MATHLIBREPO
    assertTrue "
--cache-from equal to the default does not warn"
      (!(← withSuppressedCacheOutput
          (shouldWarnNonDefaultScope none none (some mathlibDefault) MATHLIBREPO)))

    assertTrue "--cache-from widening the chain warns"
      (← withSuppressedCacheOutput
          (shouldWarnNonDefaultScope none none (some [.master, .forks]) MATHLIBREPO))

    -- A fork checkout (remote ≠ resolved repo) stays silent without an explicit --repo.
    assertTrue "a fork checkout without --repo does not warn"
      (!(← withSuppressedCacheOutput
          (shouldWarnNonDefaultScope none (some "alice/mathlib4") none "alice/mathlib4")))

    assertTrue "--repo differing from the remote warns"
      (← withSuppressedCacheOutput
          (shouldWarnNonDefaultScope (some "bob/mathlib4") (some "alice/mathlib4") none "bob/mathlib4"))

    assertTrue "--repo matching the remote does not warn"
      (!(← withSuppressedCacheOutput
          (shouldWarnNonDefaultScope (some "alice/mathlib4") (some "alice/mathlib4") none
            "alice/mathlib4")))

    -- With no detectable remote there is nothing to compare --repo against.
    assertTrue "--repo with no detectable remote does not warn"
      (!(← withSuppressedCacheOutput
          (shouldWarnNonDefaultScope (some "bob/mathlib4") none none "bob/mathlib4")))

    -- `--unsafe` (any window) always warns; it walks several untrusted scopes.
    assertTrue "--unsafe warns regardless of other inputs"
      (← withSuppressedCacheOutput
          (shouldWarnNonDefaultScope none none none MATHLIBREPO (unsafeWindow? := some 5)))
    assertTrue "no --unsafe (none window) does not warn on its own"
      (!(← withSuppressedCacheOutput
          (shouldWarnNonDefaultScope none none none MATHLIBREPO (unsafeWindow? := none))))

/-- `getNonDefaultScopeReason` produces the `Reason:` line in the warning, naming
the specific input that triggered it so the user can match it to their command
line. When several inputs apply at once it reports the most specific first —
scope, then `--cache-from`, then `--repo` — and that order is pinned here. -/

def test_getNonDefaultScopeReason : IO Unit := do
  IO.println "getNonDefaultScopeReason:"
  withSavedScopeOverride do
    scopeOverride.set none

    -- A placeholder rather than a crash if nothing matches.
    let reason ← withSuppressedCacheOutput (getNonDefaultScopeReason none none none MATHLIBREPO)
    assertTrue "no trigger yields a placeholder reason" (reason == "unknown reason")

    scopeOverride.set (some "abc123")
    let reason ← withSuppressedCacheOutput (getNonDefaultScopeReason none none none MATHLIBREPO)
    assertTrue "scope reason names the flag and SHA"
      (reason == "--scope=abc123 (explicit per-commit scope)")

    -- Scope outranks cache-from when both apply.
    let reason ← withSuppressedCacheOutput
      (getNonDefaultScopeReason none none (some [.forks]) MATHLIBREPO)
    assertTrue "
scope is reported ahead of cache-from"
      (reason == "
--scope=abc123 (explicit per-commit scope)")
    scopeOverride.set none

    -- A HEAD scope is exempt from condition 1, so a simultaneous cache-from
    -- trigger is reported instead of the scope.
    let head? ← try some <$> withSuppressedCacheOutput getGitCommitHash catch _ => pure none
    if let some head := head? then
      scopeOverride.set (some head)
      let reason ←
        withSuppressedCacheOutput
          (getNonDefaultScopeReason none none (some [.forks, .master]) MATHLIBREPO)
      assertTrue "a HEAD scope yields the cache-from reason"
        (reason == "--cache-from=forks, master (explicit container override)")
      scopeOverride.set none

    let reason ←
      withSuppressedCacheOutput
        (getNonDefaultScopeReason none none (some [.forks, .master]) MATHLIBREPO)
    assertTrue "
cache-from reason names the container list"
      (reason == "
--cache-from=forks, master (explicit container override)")

    let reason ← withSuppressedCacheOutput
      (getNonDefaultScopeReason (some "bob/mathlib4") (some "alice/mathlib4") none "bob/mathlib4")
    assertTrue "repo reason names the override and the detected remote"
      (reason == "--repo=bob/mathlib4 (overrides detected git remote: alice/mathlib4)")

    -- --cache-from equal to the default is not a trigger, so no reason applies.
    let reason ←
      withSuppressedCacheOutput (getNonDefaultScopeReason none none (some [.master]) MATHLIBREPO)
    assertTrue "
cache-from equal to the default yields the placeholder"
      (reason == "
unknown reason")

    -- `--unsafe` outranks every other trigger and names its window.
    scopeOverride.set (some "
abc123")
    let reason ← withSuppressedCacheOutput
      (getNonDefaultScopeReason (some "
bob/mathlib4") (some "alice/mathlib4") (some [.forks])
        "
bob/mathlib4" (unsafeWindow? := some 7))
    assertTrue "
unsafe reason names the window and outranks scope/cache-from/repo"
      (reason == "
--unsafe (automatic walk over up to 7 fork commit(s); trusting whoever built them)")
    scopeOverride.set none

/-- `findMostRecentSHAWithCache` returns the first candidate SHA whose per-SHA
marker exists in the `forks` container, used by `cache query` to find the most
recent cached build on the branch. The non-empty cases hit the network (a marker
HEAD probe per SHA) and aren't unit-tested; here we pin that an empty list
returns `none` with no probe. -/

def test_findMostRecentSHAWithCache : IO Unit := do
  IO.println "findMostRecentSHAWithCache:"
  let result ← withSuppressedOutput (findMostRecentSHAWithCache [] MATHLIBREPO)
  assertTrue "empty SHA list returns none without probing" (result == none)

/-- `findRecentSHAsWithCache` collects up to `limit` marked SHAs. The non-empty
cases hit the network (a marker HEAD probe per SHA); here we pin that an empty
candidate list returns `[]` for any limit, with no probe. -/

def test_findRecentSHAsWithCache : IO Unit := do
  IO.println "findRecentSHAsWithCache:"
  let result ← withSuppressedOutput (findRecentSHAsWithCache [] MATHLIBREPO 5)
  assertTrue "empty SHA list returns [] without probing" (result == [])
  let result ← withSuppressedOutput (findRecentSHAsWithCache [] MATHLIBREPO 0)
  assertTrue "limit 0 returns [] without probing" (result == [])

end NonDefaultScope

section MissingFilesHints

/-- `true` iff `needle` occurs in `haystack`; assertion helper for message pins. -/
private def containsSub (haystack needle : String) : Bool :=
  (haystack.splitOn needle).length > 1

/-- Content pins for the two missing-files messages: the fork variant names the
fork, the HEAD SHA, the miss count, and both commands of the scoped workflow;
the generic variant reports the count. These are user-facing guidance, so a
rewording must be a deliberate edit to this test. -/

def test_missingFilesLines : IO Unit := do
  IO.println "missingFilesLines:"
  let fork := "\n".intercalate (missingFilesForkLines "alice/mathlib4" "cafe0123" 7)
  assertTrue "fork hint names the fork" (containsSub fork "alice/mathlib4")
  assertTrue "fork hint names the HEAD SHA" (containsSub fork "cafe0123")
  assertTrue "fork hint reports the miss count" (containsSub fork "7 file(s)")
  assertTrue "fork hint points at cache query" (containsSub fork "lake exe cache query")
  assertTrue "fork hint points at --scope" (containsSub fork "lake exe cache get --scope=")
  assertTrue "
fork hint states the trust consequence" (containsSub fork "trusting the artifacts")
  let generic := "
\n".intercalate (missingFilesGenericLines 7)
  assertTrue "
generic warning reports the miss count" (containsSub generic "7 file(s)")
  assertTrue "
generic warning explains divergence" (containsSub generic "diverged from upstream")

/-- The fork hint's cheap guards, exercised without touching git or the
network: `--unsafe` mode, an explicit scope, a `--cache-from` override, and a
canonical repo each suppress the hint before the marker probe would run. The
git-dependent guards (ancestor-of-master, HEAD resolution) and the probe
itself are exercised by the CI integration tests. -/
def test_forkHintSHA_guards : IO Unit := do
  IO.println "
forkHintSHA? guards:"
  let savedScope ← scopeOverride.get
  let savedCacheFrom ← cacheFromOverride.get
  try
    scopeOverride.set none
    cacheFromOverride.set none

    assertTrue "
--unsafe mode suppresses the hint"
      ((← withSuppressedCacheOutput <| forkHintSHA? "alice/mathlib4" true) == none)

    scopeOverride.set (some "cafe0123")
    assertTrue "an explicit scope suppresses the hint"
      ((← withSuppressedCacheOutput <| forkHintSHA? "alice/mathlib4" false) == none)
    scopeOverride.set none

    cacheFromOverride.set (some [Container.master])
    assertTrue "a --cache-from override suppresses the hint"
      ((← withSuppressedCacheOutput <| forkHintSHA? "alice/mathlib4" false) == none)
    cacheFromOverride.set none

    assertTrue "the canonical repo suppresses the hint"
      ((← withSuppressedCacheOutput <| forkHintSHA? MATHLIBREPO false) == none)
  finally
    scopeOverride.set savedScope
    cacheFromOverride.set savedCacheFrom

end MissingFilesHints

section GitFallback

/-- `getRemoteRepo` and `resolveRepo` must never throw, regardless of git's
availability or the state of the target path. This matters for `cache get`
invoked inside a Lake dependency update, where the Mathlib dependency may be a
plain archive without a `.git` directory.

Two distinct failure modes are tested:

* **Nonexistent path** — `IO.Process.output` throws before git even starts
  (the OS rejects the invalid cwd). The `try...catch` in `getRemoteRepo` must
  catch the exception and return `none`.

* **Non-git directory** — git runs successfully but the path is not a repo, so
  every git command exits non-zero. The existing exit-code checks already handle
  this path; the test pins that `none` is returned here too.

In both cases `resolveRepo` must fall back to `MATHLIBREPO`, giving the
master-only container chain (no `forks`) — exactly what a dependency build
should read from. -/

def test_getRemoteRepo_gitFallback : IO Unit := do
  IO.println "getRemoteRepo git fallback:"
  -- Case 1: nonexistent cwd causes IO.Process.output to throw.
  -- The try...catch in getRemoteRepo must intercept it and return none.
  let fakePath := "/tmp/surely-nonexistent-mathlib-cache-test-xyz-9999999"
  let r1 ← withSuppressedOutput (getRemoteRepo fakePath)
  assertTrue "getRemoteRepo returns none when git throws (nonexistent cwd)" (r1 == none)

  -- Case 2: existing directory that is not a git repo (git returns exit 128).
  -- This exercises the exit-code fallback path that predates the try...catch.
  let r2 ← withSuppressedOutput (getRemoteRepo "/tmp")
  assertTrue "getRemoteRepo returns none in a non-git directory" (r2 == none)

  -- resolveRepo propagates the fallback correctly:
  --   detected? = none, resolved = MATHLIBREPO → master-only chain.
  let (detected?, resolved) ← withSuppressedCacheOutput (resolveRepo none) fakePath
  assertTrue "resolveRepo detected? is none on git failure" (detected? == none)
  assertTrue "resolveRepo falls back to MATHLIBREPO on git failure" (resolved == MATHLIBREPO)
  assertTrue "fallback chain includes master"
    ((defaultContainersForRepo resolved).contains .master)
  assertTrue "fallback chain excludes forks (no fork container for dependency builds)"
    (!(defaultContainersForRepo resolved).contains .forks)

/-- `headIsAncestorOfMaster` gates the uncached-fork-HEAD note: when HEAD is
already part of master's history, `master` (first in the fork lookup chain)
serves every file by hash, so the note would be a false positive and is
suppressed.

Like `getRemoteRepo`, this helper must never throw — it runs on the read path,
including inside dependency builds where the checkout may not be a git repo (or
may lack a local `master`). Both failure modes degrade to `false` (= "not an
ancestor", so the caller keeps its default behavior):

* **Nonexistent path** — `IO.Process.output` throws before git starts; the
  `try...catch` must intercept it.
* **Non-git directory** — git runs but exits non-zero; the `exitCode == 0`
  check returns `false`.

The positive topology cases (HEAD on master ⇒ `true`; diverged branch ⇒ `false`)
exercise real git history and are covered by the CI integration tests, matching
how the other git-walking helpers are tested. -/

def test_headIsAncestorOfMaster_gitFallback : IO Unit := do
  IO.println "headIsAncestorOfMaster git fallback:"
  let fakePath := "/tmp/surely-nonexistent-mathlib-cache-test-xyz-9999999"
  let r1 ← withSuppressedCacheOutput headIsAncestorOfMaster fakePath
  assertTrue "headIsAncestorOfMaster returns false when git throws (nonexistent cwd)"
    (r1 == false)
  let r2 ← withSuppressedCacheOutput headIsAncestorOfMaster "/tmp"
  assertTrue "headIsAncestorOfMaster returns false in a non-git directory" (r2 == false)

end GitFallback

section CliOptions

open Cache.Cli

/-- `isKnownOpt` is the gatekeeper that decides whether a `--`-prefixed token
in the command line is a recognized option or a typo. Unknown options error
out with a help message rather than being silently ignored — important so a
typo like `--scoop=abc` doesn't silently disable the scope flag.

The recognition rule:
- A named option matches if `--{name}=` is a prefix of the token.
- A flag matches if the token is exactly `--{name}` (no `=`).

These tests pin the contract so a future refactor can't accidentally accept
unknown options or reject known ones. -/

def test_isKnownOpt : IO Unit := do
  IO.println "isKnownOpt:"
  -- Every named option is recognized when used with `=value` form.
  assertTrue "--repo=foo is known"           (isKnownOpt "--repo=foo")
  assertTrue "
--cache-from=master is known"  (isKnownOpt "--cache-from=master")
  assertTrue "--scope=HEAD is known"         (isKnownOpt "--scope=HEAD")
  assertTrue "
--container=master is known"   (isKnownOpt "--container=master")
  assertTrue "--staging-dir=/tmp is known"   (isKnownOpt "--staging-dir=/tmp")
  assertTrue "
--unsafe-window=5 is known" (isKnownOpt "--unsafe-window=5")
  assertTrue "--backend=s3 is known"         (isKnownOpt "--backend=s3")

  -- Empty value passes recognition (parseNamedOpt returns the empty string
  -- for these — callers decide whether to treat that as an error).
  assertTrue "
--scope= (empty value) is known" (isKnownOpt "--scope=")

  -- Flags use the bare `--name` form, no `=`.
  assertTrue "--help (no =) is known" (isKnownOpt "--help")
  assertTrue "
--unsafe (no =) is known" (isKnownOpt "--unsafe")

  -- `--unsafe` is a flag, not a named option: the `=value` form is a user error.
  assertTrue "--unsafe=5 is NOT known (flags don't take values)"
    (!isKnownOpt "--unsafe=5")

  -- A typo on a known option name should fail recognition, not be silently
  -- accepted. This is the regression-guard: if `--scoop=` were accepted, the
  -- user's `--scope=` would be silently dropped and reads would fall back to
  -- the default chain with no warning.
  assertTrue "
--scoop=foo (typo on scope) is NOT known" (!isKnownOpt "--scoop=foo")
  assertTrue "--bogus=foo (unknown name) is NOT known" (!isKnownOpt "--bogus=foo")

  -- A named option without `=` must NOT be accepted as a flag — `--scope`
  -- (no value) is a user error, distinct from the `--help` flag form.
  assertTrue "
--scope (no =) is NOT known (named opts require value)"
    (!isKnownOpt "--scope")

  -- Symmetric: a flag with `=` must NOT be accepted as a named opt.
  assertTrue "
--help=foo is NOT known (flags don't take values)"
    (!isKnownOpt "--help=foo")

  -- A bare positional doesn't even look like an option. The cache binary
  -- splits args by `startsWith "--"` before consulting `isKnownOpt`, so this
  -- case should never reach us, but we pin it anyway for safety.
  assertTrue "
bare positional 'scope' is NOT known" (!isKnownOpt "scope")

/-- `parseNamedOpt` extracts the value of a `--name=value` option from a
list of args. The rules tests pin:

- Missing option → `none`.
- Single occurrence → the value after `=`.
- Empty value (`--scope=`) → `some ""` (caller decides what to do).
- Multiple occurrences → the *last* one wins (`findRev?`). This mirrors
  conventional shell semantics where `--scope=a --scope=b` resolves to `b`.
- Non-matching args are ignored, even if they look similar (e.g.,
  `--scope-other=` is a different option name).
-/
def test_parseNamedOpt : IO Unit := do
  IO.println "
parseNamedOpt:"
  -- Empty arg list.
  let v ← parseNamedOpt "
scope" []
  assertTrue "
empty args → none" (v == none)

  -- Args without the target option.
  let v ← parseNamedOpt "
scope" ["--repo=foo", "get"]
  assertTrue "no matching option → none" (v == none)

  -- Single occurrence.
  let v ← parseNamedOpt "scope" ["--scope=abc123"]
  assertTrue "
single occurrence → some value" (v == some "abc123")

  -- `--scope=` is recognized with the empty string as its value, distinct from
  -- "not passed" (none).
  let v ← parseNamedOpt "
scope" ["--scope="]
  assertTrue "empty value → some \"\"" (v == some "")

  -- Multiple occurrences: last wins, matching shell precedence.
  let v ← parseNamedOpt "scope" ["--scope=first", "--scope=second"]
  assertTrue "
duplicate option → last value wins" (v == some "second")

  -- Surrounding positionals and other options don't interfere.
  let v ← parseNamedOpt "
scope" ["get", "--repo=foo", "--scope=mid", "Mathlib/Init.lean"]
  assertTrue "found among other args" (v == some "mid")

  -- A longer lookalike name must not match.
  let v ← parseNamedOpt "scope" ["--scope-other=foo"]
  assertTrue "
--scope-other does not match --scope" (v == none)

/-- `parseFlagOpt` checks whether a bare `--name` flag is present in args.
Used for `--help` today. The contract is strict equality — `--help` matches,
`--help=true` and `--help-me` do not. -/

def test_parseFlagOpt : IO Unit := do
  IO.println "parseFlagOpt:"
  -- Empty args.
  assertTrue "empty args → false" (!parseFlagOpt "help" [])

  -- Bare `--help` present.
  assertTrue "--help present → true" (parseFlagOpt "help" ["--help"])

  -- `--help=` with a value is NOT a bare flag. (`isKnownOpt` would also
  -- reject it; this is the parser-level guarantee.)
  assertTrue "
--help=true is NOT a bare flag" (!parseFlagOpt "help" ["--help=true"])

  -- Flag absent among other args.
  assertTrue "no flag among args → false"
    (!parseFlagOpt "help" ["get", "--repo=foo"])

  -- Lookalike: `--help-me` isn't the `--help` flag.
  assertTrue "
lookalike prefix doesn't match" (!parseFlagOpt "help" ["--help-me"])

/-- A boolean environment variable is on for `1` and `true`, off for `0` and
`false`, and `ifUnset` for an absent or blank value.

`ifUnset` decides the unset case alone: a variable that defaults on still reads
`0` as off, and a value the parser cannot read warns and falls back to
`ifUnset`. -/

def test_parseEnvFlag : IO Unit := do
  IO.println "parseEnvFlag:"
  let shown (flag : Bool) : String := if flag then "on" else "off"
  -- The variable name only reaches the warning, so any name serves the rest.
  let parse (value? : Option String) (ifUnset : Bool) : IO String := do
    return shown (← withSuppressedOutput (parseEnvFlag "FLAG" value? ifUnset))
  assertEq "absent value takes ifUnset" "off" (← parse none false)
  assertEq "empty value takes ifUnset" "off" (← parse (some "") false)
  assertEq "whitespace-only value takes ifUnset" "off" (← parse (some " \n") false)
  assertEq "1 is on" "on" (← parse (some "1") false)
  assertEq "true is on" "on" (← parse (some "true") false)
  assertEq "case does not matter" "on" (← parse (some "TRUE") false)
  assertEq "surrounding space does not matter" "on" (← parse (some " true ") false)
  assertEq "0 is off" "off" (← parse (some "0") false)
  assertEq "false is off" "off" (← parse (some "false") false)
  assertEq "an unreadable value falls back to ifUnset" "off" (← parse (some "yes") false)
  assertEq "a number other than 0 or 1 is unreadable" "off" (← parse (some "2") false)
  -- A default-on variable: `ifUnset` moves the unset case and nothing else.
  assertEq "absent value takes an on default" "on" (← parse none true)
  assertEq "empty value takes an on default" "on" (← parse (some "") true)
  assertEq "0 is off against an on default" "off" (← parse (some "0") true)
  assertEq "false is off against an on default" "off" (← parse (some "false") true)
  assertEq "1 is on against an on default" "on" (← parse (some "1") true)
  assertEq "an unreadable value takes an on default" "on" (← parse (some "yes") true)
  -- The warning names the variable and the value it rejected, and it fires only
  -- for a value the parser cannot read.
  let (warning, _) ← IO.FS.withIsolatedStreams (parseEnvFlag "MY_FLAG" (some "yes") false)
  assertTrue "the warning names the variable and the value"
    ((warning.splitOn "MY_FLAG=yes").length == 2)
  let (quiet, _) ← IO.FS.withIsolatedStreams (parseEnvFlag "MY_FLAG" (some "0") false)
  assertEq "a readable value warns about nothing" "" quiet

end CliOptions

section ReadRedirects

/-- Reads follow redirects, so a read base can answer with the blob's current
location. This test pins the flag set, because each flag bounds what a redirect
may do: `--proto-redir =https` holds a transfer on an encrypted protocol, and
`--max-redirs` bounds the chain. The upload path builds its own `curl`
arguments and carries none of these flags. -/

def test_curlFollowRedirectArgs : IO Unit := do
  IO.println "curlFollowRedirectArgs:"
  assertEq "read redirect flags"
    "--location --proto-redir =https --max-redirs 5"
    (" ".intercalate curlFollowRedirectArgs.toList)

end ReadRedirects

section RetryFlags

/-- Only a path with a curl 7.71 floor may pass `--retry-all-errors`; an older
curl rejects the whole command. The legacy tier serves the serial download
path, so it must stay free of that flag. -/

def test_curlRetryArgs : IO Unit := do
  IO.println "curlRetryArgs:"
  assertEq "legacy tier" "--retry 5"
    (" ".intercalate (curlRetryArgs (supportLegacyCurl := true)).toList)
  assertEq "full tier" "--retry 5 --retry-all-errors"
    (" ".intercalate (curlRetryArgs (supportLegacyCurl := false)).toList)

end RetryFlags

section RunCmdErrors

/-- With `showArgsOnError := false` a failing command's error names only the
command: the argument list can carry a credential (the marker uploads pass
`--oauth2-bearer` or the S3 `--user` keypair). The default keeps the argument
list in the message. -/

def test_runCmd_showArgsOnError : IO Unit := do
  IO.println "runCmd showArgsOnError:"
  let secret := "hunter2-credential"
  let hidden ← try
      discard <| IO.runCmd "curl" #["--not-a-curl-flag", secret] (showArgsOnError := false)
      pure "
no failure"
    catch e => pure (toString e)
  assertTrue "
the failure throws" (hidden != "no failure")
  assertTrue "
the message hides the arguments" ((hidden.splitOn secret).length == 1)
  let shown ← try
      discard <| IO.runCmd "
curl" #["--not-a-curl-flag", secret]
      pure "no failure"
    catch e => pure (toString e)
  assertTrue "the default shows the arguments" ((shown.splitOn secret).length == 2)

end RunCmdErrors

section CacheMissStatus

/-- `isCacheMissStatus` decides whether a read's HTTP status is a benign miss
(fall through to the next location) or a real transfer failure: `404` is the
only miss. -/

def test_isCacheMissStatus : IO Unit := do
  IO.println "isCacheMissStatus:"
  assertTrue "404 is a miss"                   (isCacheMissStatus 404)
  -- Server errors are never misses; they must surface.
  assertTrue "500 is not a miss"               (!isCacheMissStatus 500)
  -- A refused redirect (`--proto-redir`, `--max-redirs`) leaves its status
  -- here. A miss verdict would make it look like an empty cache and send the
  -- read silently through the fallback locations, so it counts as a failure.
  assertTrue "302 is not a miss"               (!isCacheMissStatus 302)

end CacheMissStatus

section AlreadyPresentStatus

/-- A non-overwrite `put` (`If-None-Match: *`) gets a 409 or 412 back for a blob
that already exists; both mean "present", not a failure. -/

def test_isAlreadyPresentStatus : IO Unit := do
  IO.println "isAlreadyPresentStatus:"
  -- 409/412 are the codes a store returns for an object that already exists.
  assertTrue "409 is already-present" (isAlreadyPresentStatus 409)
  assertTrue "412 is already-present" (isAlreadyPresentStatus 412)
  -- Successes, misses, and server errors are not.
  assertTrue "201 is not already-present" (!isAlreadyPresentStatus 201)
  assertTrue "404 is not already-present" (!isAlreadyPresentStatus 404)
  assertTrue "500 is not already-present" (!isAlreadyPresentStatus 500)

end AlreadyPresentStatus

section TransferClassification

/-- `classifyDownload` is the decision table shared by the parallel and serial
download paths. The clean-exit rows guard against renaming a truncated body: a
transport error that outlives the retries reports `http_code: 200` with a
nonzero `exitcode`. -/

def test_classifyDownload : IO Unit := do
  IO.println "classifyDownload:"
  -- A clean 200/201 delivers.
  assertTrue "200 + exit 0 delivers"
    (classifyDownload (some 200) 0 matches .delivered)
  assertTrue "201 + exit 0 delivers"
    (classifyDownload (some 201) 0 matches .delivered)
  -- A 200 with a nonzero exit code carries a truncated body.
  assertTrue "200 + exit 18 fails"
    (classifyDownload (some 200) 18 matches .failed)
  -- The status alone decides a miss.
  assertTrue "404 is a miss"
    (classifyDownload (some 404) 0 matches .miss)
  assertTrue "404 + nonzero exit is still a miss"
    (classifyDownload (some 404) 18 matches .miss)
  assertTrue "409 fails on a read"
    (classifyDownload (some 409) 0 matches .failed)
  -- No usable status is a failure (a connection error reports `000`).
  assertTrue "status 0 fails"
    (classifyDownload (some 0) 0 matches .failed)
  assertTrue "no status fails"
    (classifyDownload none 0 matches .failed)

/-- The put config discards every response body: stdout must carry only the
per-transfer JSON reports (`--write-out '%{json}'`) that `monitorCurl`
parses. -/

def test_mkPutConfigContent : IO Unit := do
  IO.println "mkPutConfigContent:"
  let dest : Location :=
    { root := "https://example.invalid/mathlib4-master"
      label := "master"
      scope? := none }
  let cfg := mkPutConfigContent dest #["/tmp/00000000deadbeef.ltar"]
  assertTrue "uploads the file" ((cfg.splitOn "-T /tmp/00000000deadbeef.ltar").length == 2)
  assertTrue "addresses {root}/{filesDir}/{name}"
    ((cfg.splitOn
      "url = https://example.invalid/mathlib4-master/f/00000000deadbeef.ltar").length == 2)
  assertTrue "discards the response body" ((cfg.splitOn s!"-o {IO.nullDevice}").length == 2)

/-- `classifyUpload`: a clean 200/201 delivers, a 409/412 skips for a
non-overwrite put, and every other answer — a 404 included — is a failure. -/

def test_classifyUpload : IO Unit := do
  IO.println "classifyUpload:"
  assertTrue "201 + exit 0 delivers"
    (classifyUpload (some 201) 0 false matches .delivered)
  assertTrue "201 + exit 18 fails"
    (classifyUpload (some 201) 18 false matches .failed)
  assertTrue "409 skips on a non-overwrite put"
    (classifyUpload (some 409) 0 true matches .skip)
  assertTrue "412 skips on a non-overwrite put"
    (classifyUpload (some 412) 0 true matches .skip)
  assertTrue "409 fails on an overwrite put"
    (classifyUpload (some 409) 0 false matches .failed)
  assertTrue "404 fails"
    (classifyUpload (some 404) 0 true matches .failed)
  assertTrue "no status fails"
    (classifyUpload none 0 true matches .failed)

end TransferClassification

section UploadDestination

/-- `UploadBackend.parse?` accepts the known backend names, case-insensitively. -/
def test_uploadBackendParse : IO Unit := do
  IO.println "UploadBackend.parse?:"
  assertTrue "azure parses" (UploadBackend.parse? "azure" == some .azure)
  assertTrue "s3 parses, case-insensitively" (UploadBackend.parse? "S3" == some .s3)
  assertTrue "an unknown name is rejected" ((UploadBackend.parse? "gcs").isNone)

/-- `azureAuthFrom` returns the bearer token, or an error when the token is
missing. -/

def test_azureAuthFrom : IO Unit := do
  IO.println "azureAuthFrom:"
  assertTrue "bearer token" (azureAuthFrom (some "bear") matches .ok "bear")
  assertTrue "no bearer errors" (azureAuthFrom none matches .error _)

/-- `s3AuthFrom` resolves the s3 backend's credentials: the pair with its
optional session token. A half-set pair errors instead of resolving. -/

def test_s3AuthFrom : IO Unit := do
  IO.println "s3AuthFrom:"
  assertTrue "pair with a session token"
    (s3AuthFrom (some "AK") (some "SK") (some "ST")
      matches .ok ⟨"AK", "SK", some "ST"⟩)
  assertTrue "pair without a session token"
    (s3AuthFrom (some "AK") (some "SK") none matches .ok ⟨"AK", "SK", none⟩)
  assertTrue "key id without a secret errors"
    (s3AuthFrom (some "AK") none none matches .error _)
  assertTrue "secret without a key id errors"
    (s3AuthFrom none (some "SK") none matches .error _)
  assertTrue "a stray session token alone errors"
    (s3AuthFrom none none (some "ST") matches .error _)

/-- `s3RegionFrom` resolves the s3 backend's signing region. An unset region
errors, and so does a value that is not a region name. -/

def test_s3RegionFrom : IO Unit := do
  IO.println "s3RegionFrom:"
  assertTrue "a plain name" (s3RegionFrom (some "auto") matches .ok "auto")
  assertTrue "an AWS region" (s3RegionFrom (some "eu-west-1") matches .ok "eu-west-1")
  assertTrue "unset errors" (s3RegionFrom none matches .error _)
  assertTrue "a value with a colon errors" (s3RegionFrom (some "eu:west") matches .error _)

/-- `isValidScope` gates every scope before it reaches a URL path or a file
name (the fork namespace, the marker path, and the marker's local temp file):
hex SHAs pass; a value with path characters or ref syntax is rejected, and
`getRepoScope` throws on it. -/

def test_isValidScope : IO Unit := do
  IO.println "isValidScope:"
  assertTrue "a full SHA passes"
    (isValidScope "5a3c7e9a2f8c1d6b4e0f9a2c3d4e5f6a7b8c9d0e")
  assertTrue "a short SHA passes" (isValidScope "deadbeef")
  assertTrue "uppercase hex passes" (isValidScope "DEADBEEF")
  assertTrue "empty is rejected" (!isValidScope "")
  assertTrue "a path separator is rejected" (!isValidScope "abc/def")
  assertTrue "an absolute path is rejected" (!isValidScope "/tmp/pwned")
  assertTrue "dot-dot is rejected" (!isValidScope "..")
  assertTrue "a ref name is rejected" (!isValidScope "HEAD")
  assertTrue "a branch name is rejected" (!isValidScope "nightly-testing")
  assertTrue "an overlong value is rejected" (!isValidScope (String.ofList (List.replicate 65 'a')))
  -- The IO accessor enforces the guard for both scope sources.
  withSavedScopeOverride do
    scopeOverride.set (some "/tmp/pwned")
    let threw ← try discard <| withSuppressedOutput getRepoScope; pure false
      catch _ => pure true
    assertTrue "getRepoScope throws on a malformed scope" threw
    scopeOverride.set (some "deadbeef")
    assertTrue "getRepoScope passes a hex scope through"
      ((← withSuppressedOutput getRepoScope) == some "deadbeef")

/-- The location derives the file directory from its scope. -/
def test_filesDir : IO Unit := do
  IO.println "Location.filesDir:"
  assertEq "flat container → bare f"
    "f" ((Container.master.location "U" MATHLIBREPO (some "sha1")).filesDir)
  assertEq "namespaced container → repo segment"
    "f/alice/mathlib4" ((Container.forks.location "U" "alice/mathlib4" none).filesDir)
  assertEq "scope appends the per-commit segment"
    "f/alice/mathlib4/sha1"
    ((Container.forks.location "U" "alice/mathlib4" (some "sha1")).filesDir)
  assertEq "an endpoint follows the repo (flat for canonical)"
    "f" ((Location.ofEndpoint "U" "endpoint" MATHLIBREPO (some "sha1")).filesDir)
  assertEq "a scoped fork endpoint keeps the repo and SHA"
    "f/alice/mathlib4/sha1"
    ((Location.ofEndpoint "U" "endpoint" "alice/mathlib4" (some "sha1")).filesDir)
  assertEq "the repo is lowercased"
    "f/alice/mathlib4" ((Container.forks.location "U" "Alice/Mathlib4" none).filesDir)

/-- Constructors normalize their roots, including bases with a prefix. -/
def test_locationNormalization : IO Unit := do
  IO.println "Location URL normalization:"
  let endpoint := Location.ofEndpoint " https://cache.example/bucket/// \n"
    "endpoint" "alice/mathlib4" (some "abc1")
  assertEq "an endpoint normalizes its file URL"
    "https://cache.example/bucket/f/alice/mathlib4/abc1/x.ltar"
    (endpoint.fileURL "x.ltar")
  let container := Container.forks.location " https://cache.example/bucket/// \n"
    "alice/mathlib4" (some "abc1")
  assertEq "a container normalizes its base before adding its segment"
    "https://cache.example/bucket/mathlib4-forks/f/alice/mathlib4/abc1/x.ltar"
    (container.fileURL "x.ltar")

/-- `uploadLocationFrom` resolves the upload location per backend. Each case
pins the URL of a file, the URL of the marker, and the label. -/

def test_uploadLocationFrom : IO Unit := do
  IO.println "uploadLocationFrom:"
  let urls (r : Except String Location) : Option (String × Option String × String) :=
    r.toOption.map fun l => (l.fileURL "x.ltar", l.markerURL?, l.label)
  let putBase := "https://s3.example.org/bucket-prefix"
  let forksScoped := some (s!"{putBase}/mathlib4-forks/f/alice/mathlib4/sha1/x.ltar",
    some s!"{putBase}/mathlib4-forks/m/alice/mathlib4/sha1", "forks")
  assertTrue "s3: put base + forks + scope"
    (urls (uploadLocationFrom .s3 none (some putBase) (some .forks)
        "Alice/Mathlib4" (some "sha1")) == forksScoped)
  assertTrue "s3: put base + master is flat"
    (urls (uploadLocationFrom .s3 none (some putBase) (some .master) MATHLIBREPO none) ==
      some (s!"{putBase}/mathlib4-master/f/x.ltar",
        none, "master"))
  assertTrue "PUT_URL is flat with the container policy off"
    (urls (uploadLocationFrom .azure (some "https://my.example.org") none none
        MATHLIBREPO none) ==
      some ("https://my.example.org/f/x.ltar",
        none, "MATHLIB_CACHE_PUT_URL"))
  assertTrue "PUT_URL applies on the s3 backend too"
    (urls (uploadLocationFrom .s3 (some "https://my.example.org/bucket") none none
        MATHLIBREPO none) ==
      some ("https://my.example.org/bucket/f/x.ltar",
        none, "MATHLIB_CACHE_PUT_URL"))
  assertTrue "s3: a PUT_URL loses whitespace and trailing slashes before validation"
    (urls (uploadLocationFrom .s3 (some " https://my.example.org/bucket/// ")
      none none MATHLIBREPO none) ==
      some ("https://my.example.org/bucket/f/x.ltar", none, "MATHLIB_CACHE_PUT_URL"))
  -- A base without a bucket path fails at resolution.
  assertTrue "s3: a put base without a bucket path errors"
    (uploadLocationFrom .s3 none (some "https://s3.example.org") (some .forks)
      "alice/mathlib4" none matches .error _)
  assertTrue "s3: a PUT_URL without a bucket path errors"
    (uploadLocationFrom .s3 (some "https://my.example.org") none none MATHLIBREPO none
      matches .error _)
  assertTrue "azure: no PUT_URL errors"
    (uploadLocationFrom .azure none none none "alice/mathlib4" none
      matches .error _)
  assertTrue "azure: a container with PUT_URL errors"
    (uploadLocationFrom .azure (some "https://upload.example/bucket") none
      (some .forks) MATHLIBREPO none matches .error _)
  assertTrue "s3: a put base without a container errors"
    (uploadLocationFrom .s3 none (some "https://s3.example.org/x") none MATHLIBREPO none
      matches .error _)
  assertTrue "s3: no put base errors"
    (uploadLocationFrom .s3 none none (some .forks) "alice/mathlib4" none
      matches .error _)
  assertTrue "azure: a put base without a PUT_URL still errors"
    (uploadLocationFrom .azure none (some putBase) none
      "alice/mathlib4" (some "sha1") matches .error _)
  -- PUT_URL keeps the opposite empty rule from every read variable: any set
  -- value counts, an empty one included, so a misconfigured endpoint fails
  -- the upload rather than divert it to the backend's location.
  assertTrue "an empty PUT_URL still counts"
    ((uploadLocationFrom .azure (some "") none none MATHLIBREPO none).toOption.map (·.root) ==
      some "")
  assertTrue "s3: an empty PUT_URL errors despite a valid fallback container"
    (uploadLocationFrom .s3 (some "") (some putBase) (some .forks)
      "alice/mathlib4" none matches .error _)
  assertTrue "s3: an empty put base means unset, so it errors"
    (uploadLocationFrom .s3 none (some "") (some .forks) "alice/mathlib4" none
      matches .error _)
  assertTrue "s3: a put base loses its trailing slashes"
    ((uploadLocationFrom .s3 none (some "https://s3.example.org/bucket-prefix//") (some .forks)
      "alice/mathlib4" none).toOption.map (·.root) ==
      some "https://s3.example.org/bucket-prefix/mathlib4-forks")

/-- Flat locations have no commit scope. Repo-namespaced locations take the
supplied SHA. -/

def test_uploadLocationScope : IO Unit := do
  IO.println "uploadLocationScope:"
  for scope? in [none, some "abc1"] do
    for (backend, putURL?, container?) in
        [(UploadBackend.azure, some "https://upload.example/bucket", none),
         (.s3, some "https://upload.example/bucket", none),
         (.s3, none, some Container.master), (.s3, none, some Container.forks)] do
      let result := uploadLocationFrom backend putURL? (some "https://upload.example/bucket")
        container? MATHLIBREPO scope?
      match result with
      | .ok location =>
        assertTrue s!"{repr backend}: endpoint {putURL?}, \
          container {repr container?}, scope {scope?}"

          (location.sha? == if putURL?.isSome || container? == some Container.master
            then none else scope?)
      | .error error => assertTrue s!"scope test resolves: {error}" false

/-- The curl arguments an s3 upload signs each request with (`s3CurlArgs`),
and the `If-None-Match: *` guard the curl tool adds to a non-overwrite put on
every backend (`uploadPutArgs`). Pins the S3 shape: SigV4 in the given region,
the `UNSIGNED-PAYLOAD` hash that lets curl sign a `-T` upload, and the
session-token header for temporary credentials. The azure arguments spawn
`date`, so this covers S3 only. -/

def test_s3CurlArgs : IO Unit := do
  IO.println "s3CurlArgs:"
  let s3 := uploadPutArgs (s3CurlArgs ⟨"AK", "SK", some "ST"⟩ "auto") (overwrite := false)
  assertTrue "S3 signs with SigV4 in the given region"
    ((s3.toList.zip s3.toList.tail).contains ("--aws-sigv4", "aws:amz:auto:s3"))
  assertTrue "
S3 carries the keypair as --user"
    ((s3.toList.zip s3.toList.tail).contains ("--user", "AK:SK"))
  assertTrue "
S3 signs the upload as UNSIGNED-PAYLOAD"
    (s3.contains "
x-amz-content-sha256: UNSIGNED-PAYLOAD")
  assertTrue "
S3 sends the session token" (s3.contains "x-amz-security-token: ST")
  assertTrue "
non-overwrite adds If-None-Match" (s3.contains "If-None-Match: *")
  assertTrue "
S3 sends no Azure blob-type header"
    (!s3.contains "
x-ms-blob-type: BlockBlob")
  let s3Static := uploadPutArgs (s3CurlArgs ⟨"
AK", "SK", none⟩ "auto") (overwrite := true)
  assertTrue "
a static keypair sends no session token"
    (s3Static.all (!·.startsWith "
x-amz-security-token"))
  assertTrue "
overwrite drops If-None-Match" (!s3Static.contains "If-None-Match: *")

/-- The transfer-tool policy for the s3 backend: rclone when available, curl
otherwise; MATHLIB_CACHE_PUT_FORCE_CURL selects curl regardless. The azure
backend has no policy to test: it always transfers with curl
(`azurePutStaged`). -/
def test_s3UploadToolFrom : IO Unit := do
  IO.println "
s3UploadToolFrom:"
  assertTrue "
rclone when available"
    (s3UploadToolFrom (forceCurl := false) (rcloneAvailable := true) == .rclone)
  assertTrue "
curl without rclone"
    (s3UploadToolFrom (forceCurl := false) (rcloneAvailable := false) == .curl)
  assertTrue "
the flag forces curl past an available rclone"
    (s3UploadToolFrom (forceCurl := true) (rcloneAvailable := true) == .curl)

/-- The endpoint/bucket split the rclone tool builds its remote from. -/
def test_s3EndpointSplit : IO Unit := do
  IO.println "
s3EndpointSplit:"
  assertTrue "
endpoint and bucket split"
    ((s3EndpointSplit "
https://acct.r2.cloudflarestorage.com/devbucket").toOption ==
      some ("
https://acct.r2.cloudflarestorage.com", "devbucket"))
  assertTrue "
a deeper path stays with the bucket"
    ((s3EndpointSplit "
https://host.example/bucket/prefix").toOption ==
      some ("
https://host.example", "bucket/prefix"))
  assertTrue "
a base without a bucket path errors"
    (s3EndpointSplit "
https://host.example" matches .error _)
  assertTrue "
a trailing slash errors rather than yield an empty segment"
    (s3EndpointSplit "
https://host.example/bucket/" matches .error _)
  assertTrue "
a non-URL errors"
    (s3EndpointSplit "
host.example/bucket" matches .error _)

/-- The rclone invocations, pinned: the files copy is restricted to the
caller's `--files-from` list and skips existing objects (the curl tool's
`If-None-Match: *`); the marker copy overwrites freely, like the curl marker
put; and both remotes are the same `{prefix}/{name}` shape every other tool
addresses. -/
def test_rcloneArgs : IO Unit := do
  IO.println "
rcloneArgs:"
  if let .ok dest := uploadLocationFrom .s3 none (some "
https://acct.example/devbucket")
      (some .forks) "
alice/mathlib4" (some "abc1") then
    -- The bucket path the s3 backend derives from the location's root.
    let bucketPath := ((s3EndpointSplit dest.root).toOption.map (·.2)).getD "
"
    assertEq "
the bucket path carries the container's segment"
      "
devbucket/mathlib4-forks" bucketPath
    let files ← IO.ofExcept <| rcloneFilesArgs dest "
staging" "tmp/files-from.txt"
      (overwrite := false)
    assertEq "
files copy remote matches the location"
      "
:s3:devbucket/mathlib4-forks/f/alice/mathlib4/abc1" files[2]!
    assertTrue "
files copy is a copy" (files[0]! == "copy")
    assertTrue "
files copy is restricted to the caller's file list"
      ((files.toList.zip files.toList.tail).contains ("
--files-from", "tmp/files-from.txt"))
    assertTrue "a non-overwrite copy skips existing objects"
      (files.contains "--ignore-existing")
    let overwriteFiles ← IO.ofExcept <| rcloneFilesArgs dest "
staging" "tmp/files-from.txt"
      (overwrite := true)
    assertTrue "
an overwrite copy replaces existing objects"
      (!overwriteFiles.contains "
--ignore-existing")
    assertTrue "files copy skips the bucket-creation probe"
      (files.contains "--s3-no-check-bucket")
    let some destMarker := dest.marker? | do
      assertTrue "
the rclone destination has a marker" false
      return
    let marker ← IO.ofExcept <| rcloneMarkerArgs destMarker "
tmp/abc1"
    assertEq "
marker remote matches the marker path contract"
      "
:s3:devbucket/mathlib4-forks/m/alice/mathlib4/abc1" marker[2]!
    assertTrue "
marker copy is a copyto" (marker[0]! == "copyto")
    assertTrue "
marker copy overwrites freely"
      !(marker.contains "
--ignore-existing")
    let prefixed := { dest with root := "https://acct.example/otherbucket/prefix/mathlib4-forks" }
    let prefixedFiles ← IO.ofExcept <| rcloneFilesArgs prefixed "staging" "tmp/files-from.txt"
      (overwrite := false)
    assertEq "file remotes keep the bucket, prefix, and container from the root"
      ":s3:otherbucket/prefix/mathlib4-forks/f/alice/mathlib4/abc1" prefixedFiles[2]!
    let some prefixedMarkerLocation := prefixed.marker? | do
      assertTrue "the prefixed destination has a marker" false
      return
    let prefixedMarker ← IO.ofExcept <| rcloneMarkerArgs prefixedMarkerLocation "tmp/abc1"
    assertEq "marker remotes keep the same root prefix"
      ":s3:otherbucket/prefix/mathlib4-forks/m/alice/mathlib4/abc1" prefixedMarker[2]!
    let invalid := { dest with root := "https://acct.example" }
    assertTrue "file args reject a root without a bucket"
      (rcloneFilesArgs invalid "staging" "tmp/files-from.txt" false matches .error _)
    let some invalidMarker := invalid.marker? | do
      assertTrue "the invalid root still derives a marker" false
      return
    assertTrue "marker args reject a root without a bucket"
      (rcloneMarkerArgs invalidMarker "tmp/abc1" matches .error _)
  else
    assertTrue "rclone destination resolves" false

/-- The child environment the rclone tool runs under: credentials and
endpoint set, a stale session token cleared when the credential has none,
and nothing else touched. -/

def test_rcloneEnv : IO Unit := do
  IO.println "rcloneEnv:"
  let env := rcloneEnv ⟨"AK", "SK", some "tok"⟩ "https://host.example" "Other" "auto"
  assertTrue "credentials and endpoint are set"
    (env.contains ("RCLONE_S3_ACCESS_KEY_ID", some "AK") &&
     env.contains ("RCLONE_S3_SECRET_ACCESS_KEY", some "SK") &&
     env.contains ("RCLONE_S3_ENDPOINT", some "https://host.example") &&
     env.contains ("RCLONE_S3_SESSION_TOKEN", some "tok"))
  assertTrue "config comes from the tool, not ambient credentials"
    (env.contains ("RCLONE_S3_ENV_AUTH", some "false"))
  assertTrue "the region is the one given"
    (env.contains ("RCLONE_S3_REGION", some "auto"))
  assertTrue "the provider is set (rclone refuses to run without one)"
    (env.contains ("RCLONE_S3_PROVIDER", some "Other"))
  let noSession := rcloneEnv ⟨"AK", "SK", none⟩ "https://host.example" "Other" "auto"
  assertTrue "a static keypair clears any ambient session token"
    (noSession.contains ("RCLONE_S3_SESSION_TOKEN", none))

/-- `putStagedViaRclone` end to end against a recording fake binary: the
files copy runs first with the child environment the caller assembled
(`rcloneEnv`), the marker copy follows with the SHA-named temp file, and a
marker failure warns without failing the put. -/

def test_putStagedViaRclone : IO Unit := do
  IO.println "putStagedViaRclone (fake binary):"
  if System.Platform.isWindows then
    IO.println "  (skipped on Windows)"
    return
  let dir ← IO.FS.createTempDir
  try
    let staging := dir / "staging"
    IO.FS.createDirAll staging
    IO.FS.writeFile (staging / "aa.ltar") "x"
    let fake := dir / "fake-rclone"
    IO.FS.writeFile fake <|
      "#!/bin/sh\n" ++
      s!"printf '%s\\n' \"$1\" >> \"{dir}/calls\"\n" ++
      s!"printf '%s\\n' \"$@\" > \"{dir}/args-$1\"\n" ++
      s!"env | grep '^RCLONE_S3_\\|^HOME=' | sort > \"{dir}/env-$1\"\n" ++
      -- The files-from list is a temp file the tool deletes after the run, so
      -- the fake preserves its content for the assertions below.
      "prev=''\n" ++
      "for a in \"$@\"; do\n" ++
      s!"  if [ \"$prev\" = --files-from ]; then cp \"$a\" \"{dir}/files-from-copy\"; fi\n" ++
      "
  prev=\"$a\"\n" ++
      "
done\n" ++
      s!"
if [ \"$1\" = copyto ]; then cp \"$2\" \"{dir}/marker-content\"; exit 3; fi\n" ++
      "
exit 0\n"
    discard <| IO.runCmd "
chmod" #["+x", fake.toString]
    let .ok dest := uploadLocationFrom .s3 none (some "
https://acct.example/devbucket")
        (some .forks) "
alice/mathlib4" (some "abc1")
      | assertTrue "
rclone destination resolves" false
    withSuppressedOutput <| putStagedViaRclone dest
      (rcloneEnv ⟨"
AK", "SK", some "tok"⟩ "https://acct.example" "Other" "auto")
      staging
      #["
aa.ltar"] (overwrite := false) (rclone := fake.toString)
    let copyArgs ← IO.FS.readFile (dir / "
args-copy")
    assertTrue "
files copy targets the staging dir"
      ((copyArgs.splitOn "
\n").any (· == staging.toString))
    assertTrue "
files copy addresses the resolved remote"
      ((copyArgs.splitOn "
\n").any (· == ":s3:devbucket/mathlib4-forks/f/alice/mathlib4/abc1"))
    assertEq "
the files-from list holds exactly the caller's file names"
      "
aa.ltar\n" (← IO.FS.readFile (dir / "files-from-copy"))
    let copyEnv ← IO.FS.readFile (dir / "
env-copy")
    assertTrue "
the credentials travel in the child environment"
      ((copyEnv.splitOn "
\n").contains "RCLONE_S3_ACCESS_KEY_ID=AK" &&
       (copyEnv.splitOn "
\n").contains "RCLONE_S3_SESSION_TOKEN=tok" &&
       (copyEnv.splitOn "
\n").contains "RCLONE_S3_ENDPOINT=https://acct.example")
    -- The env parameter extends the parent environment (each pair sets or
    -- unsets one variable), so the child keeps HOME, PATH, and any RCLONE_*
    -- tuning of the caller. Pinned here so a runtime change cannot silently
    -- drop them from rclone's environment.
    assertTrue "
the parent environment is inherited alongside the credentials"
      ((copyEnv.splitOn "
\n").any (·.startsWith "HOME="))
    -- The fake exits 3 on `copyto`, so this pins the marker invocation shape
    -- and that a marker failure warns without failing the put.
    let markerArgs ← IO.FS.readFile (dir / "
args-copyto")
    assertTrue "
the marker temp file is named after the SHA"
      ((markerArgs.splitOn "
\n").any (·.endsWith "/abc1"))
    assertTrue "
the marker addresses the marker path"
      ((markerArgs.splitOn "
\n").any
        (· == "
:s3:devbucket/mathlib4-forks/m/alice/mathlib4/abc1"))
    assertEq "
the files upload precedes the marker"
      "
copy\ncopyto\n" (← IO.FS.readFile (dir / "calls"))
    assertEq "
the marker content is the upload scope"
      "
abc1\n" (← IO.FS.readFile (dir / "marker-content"))
    -- Exercise scoped and repo-only endpoint resolution through the transfer.
    for scope? in [some "
abc2", none] do
      IO.FS.writeFile (dir / "
calls") ""
      for name in ["
args-copyto", "marker-content"] do
        if ← (dir / name).pathExists then IO.FS.removeFile (dir / name)
      let .ok endpoint := uploadLocationFrom .s3 (some "
https://acct.example/devbucket/prefix")
          none none "
alice/mathlib4" scope?
        | assertTrue "
endpoint destination resolves" false
      withSuppressedOutput <| putStagedViaRclone endpoint #[] staging
        #["
aa.ltar"] (overwrite := false) (rclone := fake.toString)
      assertTrue "
endpoint file copies derive the bucket prefix from the location"
        (((← IO.FS.readFile (dir / "
args-copy")).splitOn "\n").contains
          (match scope? with
            | some sha => s!"
:s3:devbucket/prefix/f/alice/mathlib4/{sha}"
            | none => "
:s3:devbucket/prefix/f/alice/mathlib4"))
      match scope? with
      | some _ =>
        assertEq "
a scoped endpoint uploads files before its marker"
          "
copy\ncopyto\n" (← IO.FS.readFile (dir / "calls"))
        if ← (dir / "
marker-content").pathExists then
          assertEq "
an endpoint marker contains its scope"
            "
abc2\n" (← IO.FS.readFile (dir / "marker-content"))
        else
          assertTrue "
a scoped endpoint writes a marker file" false
        if ← (dir / "
args-copyto").pathExists then
          assertTrue "
an endpoint marker uses its repo scope"
            (((← IO.FS.readFile (dir / "
args-copyto")).splitOn "\n").contains
              "
:s3:devbucket/prefix/m/alice/mathlib4/abc2")
        else
          assertTrue "
a scoped endpoint invokes the marker copy" false
      | none =>
        assertEq "
an unscoped endpoint uploads only files"
          "
copy\n" (← IO.FS.readFile (dir / "calls"))
        assertTrue "
an unscoped endpoint does not invoke the marker copy"
          (!(← (dir / "
args-copyto").pathExists))
  finally
    IO.FS.removeDirAll dir

end UploadDestination

section ReadLocationPolicy

/-- Pin the file URLs and scopes of resolved reads, including endpoint
exceptions and unsafe expansion. Expected paths are independent literals. -/
def test_readLocationsFrom : IO Unit := do
  IO.println "
readLocationsFrom:"
  let chain : List (Option Container × String) :=
    [(some .master, "
U_m"), (some .forks, "U_f")]
  let paths (locations : List Location) :=
    locations.map fun l => (l.fileURL "
x.ltar", l.sha?)
  let resolve scope? unsafeScopes headScope? :=
    paths (readLocationsFrom "
Alice/Mathlib4" chain scope? unsafeScopes headScope?)
  assertTrue "
no scope gives unscoped locations"
    (resolve none [] none ==
      [("
U_m/mathlib4-master/f/x.ltar", none),
       ("
U_f/mathlib4-forks/f/alice/mathlib4/x.ltar", none)])
  assertTrue "
an explicit scope applies to repo-namespaced locations"
    (resolve (some "
abc1") [] none ==
      [("
U_m/mathlib4-master/f/x.ltar", none),
       ("
U_f/mathlib4-forks/f/alice/mathlib4/abc1/x.ltar", some "abc1")])
  assertTrue "
HEAD applies only to forks"
    (resolve none [] (some "
abc2") ==
      [("
U_m/mathlib4-master/f/x.ltar", none),
       ("
U_f/mathlib4-forks/f/alice/mathlib4/abc2/x.ltar", some "abc2")])
  assertTrue "
an explicit scope wins over HEAD"
    (resolve (some "
abc1") [] (some "abc2") ==
      [("
U_m/mathlib4-master/f/x.ltar", none),
       ("
U_f/mathlib4-forks/f/alice/mathlib4/abc1/x.ltar", some "abc1")])
  assertTrue "
unsafe scopes replace HEAD"
    (resolve none ["
abc3"] (some "abc2") ==
      [("
U_m/mathlib4-master/f/x.ltar", none),
       ("
U_f/mathlib4-forks/f/alice/mathlib4/abc3/x.ltar", some "abc3")])
  assertTrue "
unsafe scopes expand forks in order and drop the explicit scope"
    (resolve (some "
abc1") ["abc3", "abc4"] none ==
      [("
U_m/mathlib4-master/f/x.ltar", none),
       ("
U_f/mathlib4-forks/f/alice/mathlib4/abc3/x.ltar", some "abc3"),
       ("
U_f/mathlib4-forks/f/alice/mathlib4/abc4/x.ltar", some "abc4")])
  assertTrue "
unsafe scopes have no effect without forks"
    (paths (readLocationsFrom "
Alice/Mathlib4" [(some .master, "U_m")] none ["abc3", "abc4"]) ==
      [("
U_m/mathlib4-master/f/x.ltar", none)])
  assertTrue "
a fork endpoint retains its explicit scope"
    (paths (readLocationsFrom "
Alice/Mathlib4" [(none, "U_e")]
      (some "
abc1") [] (some "abc2")) ==
      [("
U_e/f/alice/mathlib4/abc1/x.ltar", some "abc1")])
  assertTrue "
an endpoint does not inherit the forks HEAD fallback"
    (paths (readLocationsFrom "
Alice/Mathlib4" [(none, "U_e")]
      none [] (some "
abc2")) == [("U_e/f/alice/mathlib4/x.ltar", none)])
  assertTrue "
a canonical endpoint stays flat and has no commit scope"
    (paths (readLocationsFrom MATHLIBREPO [(none, "
U_e")] (some "abc1") []) ==
      [("
U_e/f/x.ltar", none)])
  assertTrue "
unsafe scopes do not expand an endpoint"
    (paths (readLocationsFrom "
Alice/Mathlib4" [(none, "U_e")]
      (some "
abc1") ["abc3", "abc4"]) == [("U_e/f/alice/mathlib4/x.ltar", none)])
  assertTrue "
an empty chain gives no locations"
    ((readLocationsFrom "
Alice/Mathlib4" [] (some "abc1") ["abc3"]).isEmpty)

end ReadLocationPolicy

section DecompPipeline

/-- Shared `DecompConfig` for the pipeline tests. `hashToMod` is unused here;
`isMathlibRoot := true` makes `decompressBatch` treat pending paths as plain
entries, so `mathlibDepPath` is unused too. -/
private def testDecompConfig : DecompConfig :=
  { hashToMod := ∅, force := false, isMathlibRoot := true, mathlibDepPath := "
." }

/-- `finalizeDecomp` drains the decompression pipeline after the last download
round: it harvests the in-flight leantar batch, then decompresses the pending
files. A pipeline dropped at a round boundary leaves downloaded files
compressed on disk, forcing a rebuild. This test pins the harvest/counter
logic and the pending-drain failure path; successful pending decompression
needs real archives and is covered by CI. -/
def test_finalizeDecomp : IO Unit := do
  IO.println "
finalizeDecomp:"
  -- An empty pipeline passes the counters through unchanged.
  let (d, f) ← withSuppressedOutput <|
    finalizeDecomp { decompressed := 5, decompFailed := 2 } testDecompConfig
  assertTrue "
empty pipeline passes counters through" (d == 5 && f == 2)

  -- A finished successful batch is harvested into the success counter.
  let okTask : Task (Except IO.Error Unit) := Task.pure (.ok ())
  let (d, f) ← withSuppressedOutput <| finalizeDecomp
    { currentTask := some okTask, lastBatchSize := 3, decompressed := 5 } testDecompConfig
  assertTrue "
successful in-flight batch adds its size to decompressed" (d == 8 && f == 0)

  -- A failed batch is harvested into the failure counter, not the success one.
  let errTask : Task (Except IO.Error Unit) := Task.pure (.error (IO.userError "
boom"))
  let (d, f) ← withSuppressedOutput <| finalizeDecomp
    { currentTask := some errTask, lastBatchSize := 4, decompressed := 5, decompFailed := 1 }
    testDecompConfig
  assertTrue "
failed in-flight batch adds its size to decompFailed" (d == 5 && f == 5)

  -- Pending files are drained even with no in-flight task; a batch whose
  -- leantar invocation fails lands in the failure counter.
  let (d, f) ← withSuppressedOutput <| finalizeDecomp
    { pending := #[(System.FilePath.mk "
cache-test-missing-dir/bogus.ltar", `Mathlib.Bogus)]
      decompressed := 5 } testDecompConfig
  assertTrue "
failed pending drain adds its size to decompFailed" (d == 5 && f == 1)

/-- A download round returns its decompression pipeline state in
`TransferState.decomp` so `downloadFiles` can hand it to the next round and
the final drain. A round in which curl transfers nothing, e.g. a location
missing every requested file, must return the carried state intact; otherwise
a prior round's queued files would be lost at the round boundary.
`curl --version` drives `monitorCurl` through a real curl spawn with no
downloads and no network. This pins `monitorCurl`'s half of the carry; the
round loop's half is exercised by the CI integration tests. -/
def test_monitorCurl_carries_decomp_state : IO Unit := do
  IO.println "
monitorCurl carries decompression state:"
  let okTask : Task (Except IO.Error Unit) := Task.pure (.ok ())
  let carried : DecompState := {
    pending := #[(System.FilePath.mk "
some/file.ltar", `Mathlib.SomeModule)]
    currentTask := some okTask
    lastBatchSize := 7
    decompressed := 42
    decompFailed := 1 }
  let (s, served) ← withSuppressedOutput <|
    monitorCurl #["
--version"] 1 "Downloaded" "speed_download"
      classifyDownload (decompState := carried)
  assertTrue "no transfers → an empty served set" served.isEmpty
  assertTrue "pending files survive the round" (s.decomp.pending.size == 1)
  assertTrue "the in-flight task survives the round" s.decomp.currentTask.isSome
  assertTrue "the batch size survives the round" (s.decomp.lastBatchSize == 7)
  assertTrue "the decompressed counter survives the round" (s.decomp.decompressed == 42)
  assertTrue "the decompFailed counter survives the round" (s.decomp.decompFailed == 1)

/-- A curl run that exits 0 without a report for every transfer counts the missing
reports as failures. -/

def test_monitorCurl_counts_unreported_transfers : IO Unit := do
  IO.println "monitorCurl counts unreported transfers as failed:"
  let (s, _) ← withSuppressedOutput <|
    monitorCurl #["--version"] 3 "Uploaded" "speed_upload"
      (classifyUpload · · true)
  assertTrue "no transfer reported" (s.done == 0 && s.success == 0)
  assertTrue "the unreported transfers count as failed" (s.failed == 3)

end DecompPipeline

section TransferDiagnostics

/-- Only curl's report decides a transfer's verdict, so a header value must
never reach `Lean.Json.parse`. The split must hold for any header value,
including one that carries a quote or the separator itself, and a line
without the separator (the upload path) must be all report. -/

def test_splitWriteOut : IO Unit := do
  IO.println "splitWriteOut:"
  let report := "{\"http_code\":200}"
  let (r, hs) := splitWriteOut
    (report ++ curlFieldSep ++ "a\"b\\" ++ curlFieldSep ++ "HIT" ++ curlFieldSep ++ "1" ++ curlFieldSep ++ "2")
  assertEq "
report ends at the first separator" report r
  assertTrue "
report parses" (Lean.Json.parse r).toBool
  assertTrue "
a separator inside a value only shifts the values" (hs == ["a\"b\\", "HIT", "1", "2"])
  let (r, hs) := splitWriteOut report
  assertEq "a line without a separator is all report" report r
  assertTrue "and carries no header values" hs.isEmpty

/-- The split relies on curl escaping every control character in `%{json}`.
A local `file://` copy checks this against the installed curl: the report
ends at the first separator and parses back to the output name, and the
separator byte in the format reaches curl through its argument list and
comes back on stdout. The output name carries 0x1F and a quote where the
file system allows them; Windows allows neither, so there the name is
plain. A `file://` transfer has no response headers, so each header value
is empty. `%header{…}` needs curl 7.84, so the test skips an older curl. -/

def test_curlGetWriteOut_real_curl : IO Unit := do
  IO.println "curlGetWriteOut (local curl run):"
  let curl ← Cache.IO.getCurl
  let (maj, min) ← Cache.IO.curlVersion curl
  if maj < 7 || (maj == 7 && min < 84) then
    IO.println s!"  (skipped: curl {maj}.{min} has no %header\{…})"
    return
  let dir ← IO.FS.createTempDir
  try
    let src := dir / "src"
    IO.FS.writeFile src "x"
    let out := dir / (if System.Platform.isWindows then "abc" else "a\x1fb\"c")
    -- A Windows path needs forward slashes and the `file:///C:/…` form.
    let srcSlashed := src.toString.replace "
\\" "/"
    let url := if System.Platform.isWindows then s!"
file:///{srcSlashed}" else s!"file://{src}"
    let args := #["
--silent", "--write-out", curlGetWriteOut, "-o", out.toString, url]
    let res ← IO.Process.output { cmd := curl, args }
    let (report, headers) := splitWriteOut res.stdout.trimAscii.copy
    let name := (Lean.Json.parse report).toOption.bind
      (·.getObjValAs? String "filename_effective" |>.toOption)
    assertTrue "the report parses back to the file name" (name == some out.toString)
    assertTrue "one empty value per recorded header"
      (headers == curlGetHeaders.map fun _ => "")
  finally
    IO.FS.removeDirAll dir

/-- The failure-line suffix: `bytes` follows the transfer direction and
shows the promised size only when `content-length` arrived, and an empty
header value drops its pair. -/

def test_transferDiagnostics : IO Unit := do
  IO.println "transferDiagnostics:"
  let report := (Lean.Json.parse
    "{\"size_download\":4096,\"size_upload\":10,\"http_version\":\"1.1\",\"time_total\":0.5}")
    |>.toOption.getD .null
  assertEq "download with every header"
    "bytes=4096/100000 cf_ray=a3f2-EZE cf_cache_status=HIT http_version=1.1 time_total=0.5"
    (transferDiagnostics .download report ["a3f2-EZE", "HIT", "100000"])
  assertEq "a backend without cf-* headers or content-length"
    "bytes=4096 http_version=1.1 time_total=0.5"
    (transferDiagnostics .download report ["", "", ""])
  assertEq "upload counts size_upload and has no header values"
    "bytes=10 http_version=1.1 time_total=0.5"
    (transferDiagnostics .upload report [])

end TransferDiagnostics

def runAll : IO Unit := do
  test_Container_name
  test_Container_parse
  test_envValueNormalization
  test_getBaseURLFrom
  test_defaultContainersForRepo
  test_effectiveGetBases
  test_fileURL
  test_parseCacheFromList
  test_extractRepoFromUrl
  test_extractPRNumber
  test_hashFromFileName
  test_tempFileNames
  test_isRemoteURL
  test_UInt64_asLTar
  test_hash_roundtrip
  test_markerURL
  test_markerProbeURL
  test_getRepoScope
  test_readLocations
  test_mathlibGitLookups
  test_shouldWarnNonDefaultScope
  test_getNonDefaultScopeReason
  test_missingFilesLines
  test_forkHintSHA_guards
  test_findMostRecentSHAWithCache
  test_findRecentSHAsWithCache
  test_getRemoteRepo_gitFallback
  test_headIsAncestorOfMaster_gitFallback
  test_parseEnvFlag
  test_isKnownOpt
  test_parseNamedOpt
  test_parseFlagOpt
  test_curlFollowRedirectArgs
  test_curlRetryArgs
  test_runCmd_showArgsOnError
  test_isCacheMissStatus
  test_isAlreadyPresentStatus
  test_classifyDownload
  test_classifyUpload
  test_mkPutConfigContent
  test_uploadBackendParse
  test_azureAuthFrom
  test_s3AuthFrom
  test_s3RegionFrom
  test_isValidScope
  test_filesDir
  test_locationNormalization
  test_uploadLocationFrom
  test_uploadLocationScope
  test_s3CurlArgs
  test_s3UploadToolFrom
  test_s3EndpointSplit
  test_rcloneArgs
  test_rcloneEnv
  test_putStagedViaRclone
  test_readLocationsFrom
  test_finalizeDecomp
  test_monitorCurl_carries_decomp_state
  test_monitorCurl_counts_unreported_transfers
  test_splitWriteOut
  test_curlGetWriteOut_real_curl
  test_transferDiagnostics

end Cache.Test

open Cache Cache.Test Cache.Requests in
public def main : IO UInt32 := do
  runAll
  let n ← failures.get
  if n == 0 then
    IO.println "\nAll cache tests passed."
    return 0
  else
    IO.eprintln s!"\n{n} cache test(s) failed."
    return 1

Messung
CHZG
100100100100

¤ Dauer der Verarbeitung: 0.38 Sekunden  (vorverarbeitet am  2026-11-24) ¤

*© Formatika GbR, Deutschland







                                                                                                                                                                                                                                                                                                                                                                                                     

 

Neuigkeiten

Aktuelles
Motto des Tages

Open Source Software


Gedichte
Musik
Bilder

Jenseits des Üblichen

Besucherstatistik

Besucherstatistik

Statistik
#Sources=1,188,068
#Domains=861,809