Phase 1: Upstream freshness checking and layer cache proxy tests¶
Part of PLAN-registry-proxy-future.md.
Planning effort¶
High. This phase turns on a design correction, not an
implementation detail: the master plan's original design for
freshness checking does not work, and the replacement has to reason
about manifest regeneration, multi-arch index resolution and the
Accept header's effect on which digest a registry returns. The
master plan's own guidance puts registry protocol corners and
caching behaviour at high effort.
Review effort: the master plan specifies none. High is appropriate for the same reason.
Scope¶
In scope:
- Recording the upstream manifest digest when the pull-through cache is filled, which requires exposing it from the registry input.
- A freshness check on downstream cache hits that compares a fresh upstream digest against the recorded one, with graceful degradation when upstream is unreachable.
--upstream-check-intervalto rate-limit that check.- Covering both the GET and HEAD manifest handlers.
- A
pull_cache_stalestatistic, reported at shutdown. - Unit tests for the above.
- The six layer cache proxy unit tests from the master plan's item 2, with their specifications corrected (see Decision 7).
- Documentation of the new option and behaviour in
docs/command-reference.mdanddocs/internals.md.
Explicitly out of scope:
- The pull-through functional tests and the second CI registry (the master plan's item 3). That is phase 2.
- Multi-architecture support. The proxy's push path rejects
manifest lists and will continue to. Tracked in
PLAN-compatibility.mdPriority 3. - containerd-snapshotter TLS /
--tls-cert. Still deferred, unchanged, and recorded in the master plan. - The pull path's silent platform resolution. The survey found
a real behaviour/documentation mismatch here (see What the
survey found, item 6). It is a pre-existing bug, it is not made
worse by this phase, and fixing it means deciding what the proxy
should do with a manifest list on the pull path -- which is the
multi-arch question, already owned by
PLAN-compatibility.md. This phase files an issue and moves on. - Persisting freshness state across proxy restarts. See Decision 2.
What the survey found¶
A survey sub-agent verified every factual claim in the master
plan's sections against the tree on develop at 3a2ef85. The
master plan was written 2026-06-20 and registered 2026-12-01, and
it is stale in ways that change the work. Findings, with
references:
-
The freshness design is wrong, not merely stale. The master plan says to compare the upstream
Docker-Content-Digestagainst the digest returned by the downstream GET. Downstream never holds the upstream bytes:RegistryWriterconstructs a fresh manifest dict and serialises it withjson.dumps(manifest, separators=(',', ':'))(occystrap/outputs/registry.py:539-550), always withmediaTypeset to Docker manifest V2. So the downstream digest differs from the upstream digest whenever the upstream is OCI, whenever the upstream is multi-arch (resolved to one platform byoccystrap/inputs/registry.py:171-261), whenever a filter changes a layer or config digest, and in practice whenever upstream serialises its JSON differently. The comparison would report stale on effectively every request, re-fetching every image every time and disabling the cache it was meant to validate. Corrected in the master plan at source. -
The master plan omits
_handle_head_manifest, and that omission would defeat the feature. That handler (occystrap/proxy.py:1154-1205) HEADs downstream and serves the result with no upstream involvement -- its docstring says "Does not trigger upstream fetch". A Docker client pulling an image it already has HEADs the manifest first and stops if the digest matches, so a GET-only freshness check never runs for the commonest case. Corrected in the master plan at source. -
The
mix_stderrknown issue is wrong as written. It says to useCliRunner(mix_stderr=False); Click 8.2 removed the parameter. The repository's actual convention is a_make_cli_runner()helper that triesmix_stderr=Falseand falls back onTypeError(occystrap/tests/test_check.py:22-31,occystrap/tests/test_quay.py:480-487).pyproject.toml:30pinsclick>=7.1.1with no upper bound, so both behaviours are permitted. Corrected in the master plan at source. -
The claim that both push and pull reject manifest lists is false for pull. The push path does reject them (
occystrap/proxy.py:650-657, a 400). The pull path has no such check; it resolves a list to a single platform silently. Corrected in the master plan at source. -
The size ratchet forbids the master plan's test placement.
tools/source-size-baselinepins2085 occystrap/tests/test_proxy.py, and thesource-size-ratchetpre-commit hook fails if a listed file grows.occystrap/tests/test_proxy.pyis exactly 2085 lines, so not one of the master plan's new tests can be added to it.occystrap/proxy.pyis 1400 lines against a 1500-line threshold, and has 9LOG.infocalls against the limit of 10 enforced bytools/check-log-levels.sh. See Decisions 4 and 5. -
filters_hashis not computed from filters alone._build_output_pipeline(occystrap/proxy.py:785-825) leavesfilters_hash = 'none'unlesslayer_cache is not None. The master plan'stest_filters_hash_computed("push with filters set, verify a sha256 hex string") would fail as specified, andtest_filters_hash_none_without_filterstests the wrong cause. See Decision 7. -
Items confirmed still open, as the master plan claims: no
upstream_check_interval,upstream_check_times,pull_cache_stale,_get_upstream_image,_upstream_manifest_urlor_check_upstream_freshnessexist anywhere;--upstream-check-intervalis not inoccystrap/main.py;TestLayerCacheProxyand all six of its named tests are absent, and the stringslayer_cache,filters_hashandLayerCacheappear nowhere inoccystrap/tests/test_proxy.py;deploy/occystrap_ci/tests/test_pull_through.pydoes not exist and.github/workflows/functional-tests.yml:176-178starts only the port-5000 registry. -
Items confirmed shipped, as the master plan claims:
--layer-cacheexists as a global CLI option (occystrap/main.py:118, read byproxy_cmdatoccystrap/main.py:1169),_ProxyState.layer_cacheexists (occystrap/proxy.py:71), andPipelineBuilder.build_output(self, uri_spec, image, tag, layer_cache=None, filters_hash='none')(occystrap/pipeline.py:135-136) takes both kwargs.dockerpush://does generate a self-signed certificate (occystrap/inputs/dockerpush.py:621-628), so the deferred TLS note is accurate. -
A constraint the master plan could not have known.
Image.get_manifest()(occystrap/inputs/registry.py:171-261) discards the digest: it readsr.json()and never retainsr.headers['Docker-Content-Digest']. See Decision 3.
The master plan's prose has been corrected at source for findings
1, 2, 3 and 4 as part of this phase's planning commit, and its
index.md row updated. A later step should not redo that.
Two further changes made at source: the master plan referred to
PLANS-registry-proxy-future.md, which does not exist, and its
flat Implementation Sequence has been replaced by the Execution
table the phase conventions require, since there was previously
nowhere to record a phase's status or merge commit.
Decisions¶
1. Compare a fresh upstream digest against the upstream digest recorded when the cache was filled -- never against downstream's digest.
This is the correction to finding 1. The downstream manifest is a regenerated artefact and its digest carries no information about upstream. The only sound question is "has upstream's answer for this tag changed since we last processed it?", and answering it requires remembering upstream's previous answer.
2. That record lives in memory in _ProxyState, and an absent
record means stale.
_ProxyState gains a single dict keyed 'repo:tag' holding the
recorded upstream digest and the timestamp of the last check. On a
cache hit with no record -- which after a restart is every tag --
the proxy cannot verify freshness, so it treats the entry as stale
and re-fetches once, which both serves correct content and
establishes the record.
Two alternatives were considered and rejected. A persistent sidecar
file would survive restarts, but it buys that with a new CLI
option, a second on-disk format and its own schema-versioning and
eviction questions, for a record that is cheap to rebuild.
(LayerCache is not a candidate host: it is optional, and keyed by
(diffid, filters_hash) for a different purpose with a different
lifecycle.) Writing a marker tag such as
repo:upstream-sha256-<hex> into the downstream registry would
also persist, and needs no new state at all, but it pollutes the
downstream tag list that occystrap info shows to users.
The cost of the in-memory choice is one redundant re-fetch per
repo:tag per proxy lifetime. The proxy is designed to be
long-lived, which amortises that to nothing, and the layer cache
makes the re-fetch cheap when it is configured.
This is the decision most likely to be argued with. The
counter-argument is that "absent means stale" makes a proxy restart
briefly expensive for a registry holding many tags, and that
"absent means fresh, then record" would be cheaper. We take the
conservative direction deliberately: the entire point of the
feature is to stop serving content whose freshness is unknown, and
a mode that serves unverified content on exactly the request after
a restart would be a surprising thing to have built on purpose. An
operator who prefers the cheap behaviour already has
--upstream-check-interval and can simply not enable checking.
3. Capture the upstream digest in occystrap/inputs/registry.py,
not with a second request from the proxy.
The digest is already in the response that get_manifest() reads
and throws away (finding 9). The alternative -- having
_pull_and_process issue its own HEAD afterwards to learn the
digest -- costs an extra round trip and is racy, because upstream
can change between the GET and the HEAD, which would record a
digest that never corresponded to what was cached. Fixing it at the
source of the information is the correct fix, and AGENTS.md's
preference for fixing callers rather than papering over at the
receiver points the same way.
For a multi-arch upstream the digest to record is the index
digest from the first response, not the platform manifest's digest
from the second. get_manifest() fetches the tag, and if the
answer is an index it then fetches the matching platform manifest
by digest (occystrap/inputs/registry.py:225-251). A later HEAD on
the tag returns the index digest, so recording the platform
digest would compare two different things and report stale forever.
4. The freshness logic goes in a new module,
occystrap/proxy_freshness.py.
occystrap/proxy.py is 1400 lines against the ratchet's 1500-line
threshold and carries 9 of the 10 permitted LOG.info calls, so
this feature does not fit there. The baseline file's own header
says that raising an entry is "a deliberate hand edit ... say in
the pull request description why the file should grow rather than
split", which is an invitation to justify splitting instead. The
freshness checker is a genuinely separable concern with a narrow
interface -- given a repo, a tag and the proxy state, say whether
the cache is fresh -- so splitting is the better answer on its
merits as well as the one the tooling wants. proxy.py keeps only
the call sites.
5. New tests go in new modules, not in
occystrap/tests/test_proxy.py.
Forced by finding 5: that file is pinned at its exact current
length. Freshness tests go in
occystrap/tests/test_proxy_freshness.py and the layer cache proxy
tests in occystrap/tests/test_proxy_layer_cache.py. Two modules
rather than one because they share no fixtures and test different
subjects; both will need the module-level helpers from
test_proxy.py, which should be imported rather than copied.
6. The check covers GET and HEAD manifest handlers, and
--upstream-check-interval keeps the master plan's name and
default of 0 (check every request).
Finding 2 makes HEAD coverage a correctness requirement rather than a nicety. Both handlers consult the same checker and the same state, so the interval applies to the pair of them -- a HEAD followed immediately by a GET performs one upstream check, not two -- but only when the interval is non-zero. At the default of 0, "check every request" means exactly that, and such a pair performs two checks. Corrected during implementation.
7. The layer cache test specifications are rewritten.
Per finding 6, filters_hash depends on the layer cache being
configured, not on filters being set. The corrected set is:
filters_hashis a 16 character hex digest when both a layer cache and filters are configured. It is a truncated sha256 --_compute_filters_hashreturnshexdigest()[:16]-- not the full 64 characters this plan previously said. Corrected during implementation.filters_hashis'none'when no layer cache is configured, even with filters set -- this is the behaviour the master plan got backwards, and it is worth a test precisely because it is surprising.filters_hashwith a layer cache and no filters depends on the compression type, because the hash covers that as well as the filter list. With a non-default type such aszstdit is computed; with the default gzip it is'none', because no filters plus gzip is the default pipeline, whose cache entries need nothing to tell them apart. This plan previously claimed it was computed in both cases. Corrected during implementation, and both sides now have a test.
Note for the implementer: the existing proxy tests patch
occystrap.proxy.PipelineBuilder wholesale
(occystrap/tests/test_proxy.py:1843), which also replaces
PipelineBuilder._compute_filters_hash with a mock. A test
asserting a real sha256 must therefore either patch only
build_output or use autospec. The master plan did not account
for this.
8. Upstream unreachable means serve the cache.
An upstream outage must not take the proxy's cached content with
it. A failed upstream HEAD is logged and treated as fresh. The log
call must be LOG.warning, not LOG.info: proxy.py's INFO
budget is nearly exhausted, and under
PLAN-structured-logging.md's rule INFO means milestones, which a
degraded-path warning is not.
Step plan¶
| Step | Effort | Model | Isolation | Brief for sub-agent |
|---|---|---|---|---|
| 1 | high | opus | none | Expose the upstream manifest digest from the registry input element. In occystrap/inputs/registry.py, get_manifest() (lines 171-261) fetches the tag's manifest and discards r.headers['Docker-Content-Digest']. Add self._manifest_digest = None beside self._manifest = None (line 80), clear it in the method that clears _manifest (lines 86-87), set it from the first response r (around line 197, before the media-type branching) and expose it as a read-only manifest_digest property. Critically: do not overwrite it from r2 in the manifest-list branch (lines 225-251) -- for a multi-arch image the digest that a later HEAD on the tag returns is the index digest from r, and recording the platform manifest's digest instead would make every later freshness comparison fail. Fall back to None when the header is absent (some registries omit it); callers must treat None as "cannot verify". Add unit tests in a new occystrap/tests/test_registry_input_digest.py covering: single-arch manifest records the header; manifest list records the index digest and not the platform digest; a missing header yields None; the cache-clearing method resets it. Follow the mocking style of occystrap/tests/test_info.py and test_check.py: there is no existing registry input test module, and test_registry_output.py covers the writer instead. Do not touch occystrap/tests/test_proxy.py -- it is length-pinned by tools/source-size-baseline. Commit subject: Expose upstream manifest digest from registry input. |
| 2 | high | opus | none | Write the new module occystrap/proxy_freshness.py containing a FreshnessChecker class, with no edits to occystrap/proxy.py in this step. It holds the per-tag record ('repo:tag' -> recorded upstream digest plus last-check timestamp) and the check interval, guards its own state with its own threading.Lock (do not reuse _ProxyState.lock; the checker must be independently testable), and offers: record(repo, tag, digest) to store the upstream digest observed at fill time; is_fresh(repo, tag, upstream_head_fn) returning True/False; and (dropped during implementation: a stale_count, which would double count against the pull_cache_stale the handlers own, since step 3's locked double-check consults is_fresh again). Semantics, all from the plan's Decisions: an absent record returns False (stale) -- see Decision 2; when the interval is non-zero and the last check was less than that many seconds ago, return True without calling upstream_head_fn; a recorded digest of None (registry omitted the header) returns False; if upstream_head_fn raises, log with LOG.warning and return True (Decision 8); on a real comparison, update the timestamp whether or not the digests matched. upstream_head_fn is injected rather than built here so the module stays free of HTTP concerns and the tests need no network. Use shakenfist_utilities.logs as the other modules do, single quotes, double-quoted docstrings, 120 columns. No LOG.info calls at all in this module. Commit subject: Add upstream freshness checker for the registry proxy. |
| 3 | high | opus | none | Wire the checker into occystrap/proxy.py. (a) _ProxyState.__init__ (lines 68-76) gains an upstream_check_interval=0 parameter, constructs a FreshnessChecker, and gains a pull_cache_stale = 0 counter beside the existing counters at lines 147-149. (b) _pull_and_process (lines 940-969) must record the upstream digest after the pipeline has run successfully, reading upstream_input.manifest_digest from step 1 -- recording before would record a digest for content that may have failed to cache. (c) _handle_pull_manifest (lines 993-1115): on each of the two downstream cache-hit branches (the unlocked check at lines 1038-1054 and the double-check inside pull_lock at lines 1058-1072), consult the checker before serving. Fresh means serve exactly as now. Stale means increment pull_cache_stale and fall through to the miss path instead of returning -- note the current hit branch returns from inside a try, so this needs restructuring rather than an inserted if; be careful that the unlocked branch falling through still acquires pull_lock, and that the locked branch's fall-through proceeds to the existing fetch block. (d) _handle_head_manifest (lines 1154-1205) gets the same check on its downstream hit; when stale it must not serve the downstream answer -- re-process via the same path the GET handler uses, then HEAD downstream again. This is the correctness requirement from Decision 6; a stale HEAD defeats the whole feature. (e) The upstream HEAD function passed to the checker must send the same four-type Accept header get_manifest() uses (occystrap/inputs/registry.py:191-199: Docker V2, Docker list V2, OCI manifest, OCI index). If it sends the narrower two-type header that _handle_pull_manifest uses for downstream, a registry may answer with a different manifest and a different digest, producing a permanent false-stale on every multi-arch image. (f) run_proxy (lines 1257-1264) gains upstream_check_interval=0, passes it through, and its shutdown log (lines 1380-1387) reports the stale count -- extend the existing single log call rather than adding one, as the file has 9 of 10 permitted LOG.info calls. Do not let proxy.py exceed 1500 lines; if it would, move more logic into proxy_freshness.py. Commit subject: Check upstream freshness on proxy cache hits. |
| 4 | medium | sonnet | none | Add the CLI option. In occystrap/main.py, proxy_cmd (lines 1092-1195) gains @click.option('--upstream-check-interval', default=0, type=int, help=...) alongside the existing --upstream* options, the parameter is added to the function signature, and it is passed to run_proxy. Help text should say that 0 checks on every request and that the option has no effect without --upstream. Note that --insecure and --layer-cache are global options on cli, not proxy options, so do not add anything near those. Follow the existing option ordering and help-string style in that command. Commit subject: Add --upstream-check-interval to the proxy command. |
| 5 | medium | sonnet | none | Write occystrap/tests/test_proxy_freshness.py. Two groups. First, direct unit tests of FreshnessChecker from occystrap/proxy_freshness.py with a stub upstream_head_fn, covering every rule in step 2's brief: absent record is stale; matching digest is fresh; differing digest is stale; a second call inside a non-zero interval skips the stub entirely (assert the call count); a raising stub yields fresh and increments nothing; a recorded None is stale. Second, handler-level tests through the proxy, reusing the module-level helpers in occystrap/tests/test_proxy.py by importing them (_start_test_proxy, _no_proxy_session, _make_test_image, _upload_blob) rather than copying -- read occystrap/tests/test_proxy.py:30-140 and TestPullThrough at line 1290 for the established pattern, which patches occystrap.proxy.input_registry.Image and sets mock_resp.headers including Docker-Content-Digest. Cover: a GET cache hit with a matching upstream digest serves from cache; a differing digest re-fetches and increments pull_cache_stale; a HEAD with a differing upstream digest does not serve the stale downstream answer; an upstream HEAD raising serves the cache. Use plain unittest.TestCase as test_proxy.py does, not testtools. occystrap/tests/test_proxy.py is length-pinned and must not be edited. Commit subject: Add unit tests for proxy upstream freshness checking. |
| 6 | medium | sonnet | none | Write occystrap/tests/test_proxy_layer_cache.py, implementing the master plan's item 2 with the specifications corrected by Decision 7 -- read that decision before starting, because three of the master plan's six tests are wrong as written. Cover: build_output receives a non-None layer_cache when _ProxyState.layer_cache is set; it receives layer_cache=None when it is not; filters_hash is a 16 character hex digest when a layer cache and filters are both configured; filters_hash is 'none' when no layer cache is configured even with filters set; filters_hash is computed (not 'none') with a layer cache and no filters; two pushed images receive the same LayerCache instance; and the pull-through path passes the layer cache too. The subject is _build_output_pipeline at occystrap/proxy.py:809-848 (785-825 before step 3 moved it). Mirror TestBuildOutputPipeline (occystrap/tests/test_proxy.py:1845) for the push-path mechanics, capturing kwargs via mock_builder.build_output.call_args.kwargs. Important: that class patches occystrap.proxy.PipelineBuilder wholesale, which also mocks _compute_filters_hash, so any test asserting a real sha256 must patch only build_output or use autospec -- Decision 7 explains this. Import shared helpers from occystrap/tests/test_proxy.py; do not edit that file. Commit subject: Add unit tests for proxy layer cache wiring. |
| 7 | medium | sonnet | none | Documentation. In docs/command-reference.md, add --upstream-check-interval to the proxy options table (lines 163-172) and describe freshness checking in the behaviour list (lines 185-205), including that an unreachable upstream serves cached content and that a proxy restart causes one re-fetch per tag. While there, fix the false statement at line 187 that manifest lists are rejected: that is true of the push path only, and the pull path resolves a list to a single platform silently (survey finding 4). In docs/internals.md, extend the proxy section (from line 235, pull-through at line 328) with how freshness works and why the comparison is against the recorded upstream digest rather than the downstream one -- the regenerated-manifest reasoning in What the survey found item 1 is the thing a future reader most needs. Mention the new occystrap/proxy_freshness.py module. Per this repository's documentation policy, README.md and AGENTS.md should not change (no new convention, no new command), and ARCHITECTURE.md gets at most a one-line component-inventory entry for the new module -- judge whether even that is warranted. Commit subject: Document proxy upstream freshness checking. |
Risks and mitigations¶
| Risk | Mitigation |
|---|---|
The Accept header mismatch (step 3e) silently produces a permanent false-stale on multi-arch images, re-fetching every request. This is the most likely way to ship a broken feature that still passes naive tests. |
Step 5's handler tests must include a manifest-list case where the upstream HEAD returns the index digest. The management session checks, by reading step 3's diff, that the HEAD call sends all four media types -- not by trusting the sub-agent's summary. |
| Recording the platform manifest digest instead of the index digest in step 1 has the same effect and is an easy mistake. | Step 1's brief names it explicitly, and its unit tests assert that a manifest list records the index digest and not the platform digest. Management session re-reads the assertion rather than the summary. |
Restructuring the two cache-hit branches of _handle_pull_manifest (step 3c) could break the locking, letting two threads fetch the same tag, or deadlock by re-acquiring pull_lock. |
Step 3 is opus at high effort for this reason. TestConcurrentManifests (occystrap/tests/test_proxy.py:909) already exercises the concurrency and must still pass; the management session runs tox -epy3 and reads the lock structure in the diff. |
occystrap/proxy.py crosses the 1500-line ratchet threshold, forcing an unplanned hand edit to tools/source-size-baseline. |
Decision 4 moves the bulk of the logic out of proxy.py to begin with; step 3's brief caps the file and says to move more into proxy_freshness.py if needed. pre-commit run --all-files catches it either way, before the commit. |
| The HEAD re-processing path (step 3d) duplicates the GET handler's fetch logic, producing two copies of the lock-and-fetch sequence that later drift apart. | Step 3 should factor the shared sequence into one helper used by both handlers. The management session rejects the step if it reads as copy-paste. |
| Treating an absent record as stale makes a restart expensive for a proxy serving many tags, and someone will object. | Documented in step 7 as a known behaviour, with the reasoning in Decision 2, and --upstream-check-interval offers the escape. Revisit with real numbers rather than pre-emptively. |
Definition of done¶
Falsifiable items:
-
pre-commit run --all-filespasses, which includessource-size-ratchet,check-log-levels,tox -eflake8andtox -epy3. - Revised during implementation. This item originally
required
occystrap/tests/test_proxy.pyto be unchanged at 2085 lines withtools/source-size-baselineunmodified. That turned out to be impossible: two existing tests inTestPullThroughassert that a cache hit is served without consulting upstream, which Decision 2 deliberately makes untrue for a tag whose upstream digest was never recorded, so they fail until each records one. The revised requirement is that the file grows by no more than those two lines, to 2087, with the baseline entry raised to match and justified in the pull request. No new test is added to it. Verify withwc -l occystrap/tests/test_proxy.pyreporting 2087 and the baseline entry reading2087 occystrap/tests/test_proxy.py. -
wc -l occystrap/proxy.pyreports fewer than 1500 lines. -
grep -c 'LOG\.info(' occystrap/proxy.pyreports no more than 10, andgrep -c 'LOG\.info(' occystrap/proxy_freshness.pyreports 0. -
occystrap proxy --helplists--upstream-check-interval. - The upstream HEAD issued by the freshness check sends all
four manifest media types. Verify with
grep -n 'MEDIA_TYPE' occystrap/proxy_freshness.py-- the probe lives there, not inproxy.pyas this plan assumed -- and by reading the assertion in the multi-arch handler test. - A test exists that fails if
_handle_head_manifestserves a downstream answer whose upstream digest has changed. Verify by inverting the staleness condition in the handler and confirming that specific test fails. - A test exists asserting
filters_hash == 'none'when filters are set but no layer cache is configured. -
docs/command-reference.mdno longer claims that the pull path rejects manifest lists. - No fact about freshness behaviour is stated differently in
docs/command-reference.mdanddocs/internals.md. - An issue exists for the pull path's silent platform resolution, referenced from the master plan's deferred work.
The two inversion checks above are deliberate: a test that passes
whether or not the code works is the specific failure mode this
phase is most exposed to, because the feature's visible symptom
(an image is served) is identical in the working and broken cases.
Consider running the mutation-check skill over steps 3 and 5
rather than relying on the inversions alone.
Back brief¶
Before executing any step, back brief the operator on the understanding of this plan and how the intended work aligns with it.
Gate before step 3. Steps 1 and 2 are additive and cheap to
redo. Step 3 restructures the locking in _handle_pull_manifest
and adds a re-processing path to _handle_head_manifest, which is
cheap to propose and expensive to redo once steps 4 to 7 are built
on it. Agree the shape of the shared fetch helper and the two
handlers' control flow with the operator before editing, rather
than after.
Execution notes¶
Implemented 2026-12-02 (AEDT), one sub-agent per step, all seven run
sequentially: every step writes to the same worktree and most run
tox or pre-commit, which cannot overlap in one tree. Each step was
reviewed in the management session against its diff rather than its
report, and committed there.
Back brief answers. Decision 2 stands as written: an absent record means stale. The step 3 gate was taken before step 1 began, since the handlers' control flow does not depend on steps 1 and 2; the shared read path, the two handlers' error semantics and the counter ownership were agreed then. The platform-resolution issue was filed, the mutation-check skill was run over steps 3 and 5, and this session was given permission to push and open the pull request once the definition of done passed.
Two decisions the plan did not cover, settled at the gate. A HEAD
on a cache miss keeps its existing behaviour: 404, and no upstream
fetch. Only a stale HEAD re-processes, which is what Decision 6
actually requires; making a HEAD miss fetch would have been tidier
code but a silent scope expansion and a changed handler contract. And
a HEAD-triggered re-fetch increments only pull_cache_stale, leaving
images_pulled and the hit and miss counts keyed to GET requests, so
HEAD traffic cannot inflate the pull statistics.
pull_cache_stale is not a subset of pull_cache_misses. That
follows from the decision above and was written down wrongly at first,
in proxy.py's comment, in the shutdown message and in both
documents. A GET's stale re-fetch is counted as a miss as well; a
HEAD's is not, so under HEAD-heavy traffic the stale count can exceed
the misses. Corrected in all four places in step 7's commit.
The freshness rules are ordered, and the order matters. The plan
listed them without saying which applies first. Interval before
recorded-None is the correct order: the other way round, a registry
that omits Docker-Content-Digest would re-fetch on every single
request however high the interval was set, which defeats the cache
rather than merely checking more often than asked. The
recorded-None branch therefore advances the check time too.
Step 3 exceeded the file size cap and the read path moved. With
the shared read path inline, occystrap/proxy.py reached 1621 lines
against the ratchet's 1500. FreshCacheReadMixin and
UpstreamManifestProbe consequently live in
occystrap/proxy_freshness.py beside the checker, which Decision 4
anticipated in general terms; proxy.py finished at 1395 lines, below
where it started. The module docstring describes all three classes
rather than the checker alone.
Mutation testing. Twelve mutants over the freshness code and the
digest capture, one per claim the change makes. Eleven were killed by
the expected test on the first run. The survivor was the line which
advances the check time when upstream never reported a digest:
deleting it broke nothing in 377 tests, although it is what lets the
interval rate-limit such a registry. A test was added and the mutant
is now killed. The mutants are at
scratchpad/mutants.yaml in the session scratch directory, which is
not durable; the twelve claims are listed in the pull request.
Two of the plan's own facts were wrong and are corrected at source.
Decision 7's claim that filters_hash is computed with a layer cache
and no filters holds only for a non-default compression type, and the
digest is 16 characters rather than a full sha256. Decision 6's claim
that a HEAD followed by a GET performs one upstream check holds only
when the interval is non-zero. Step 1's brief pointed at registry
input tests which do not exist, and the step was redirected to
test_info.py and test_check.py before it ran.
A coverage gap found in review rather than by a failing test.
Every step 5 handler test patches _pull_and_process, so its fake did
the recording and nothing exercised the real recording the pull path
performs. Had that line been absent, every request would have
re-fetched for ever and the suite would still have passed.
TestRecordingAfterPull now drives the real path.
Line numbers. The plan's citations into occystrap/proxy.py are
from before step 3 and have all moved. The step 6 row's two citations
are corrected above; the rest are left, since they will drift again.
CI. Recorded on the pull request.
Review round 1 (2026-12-02). The automated reviewer raised two
fix items, both real and both taken: the exception path of
is_fresh() never advanced the check time, so an upstream outage cost
a probe and a warning on every single request rather than one per tag
per interval; and the probe's Image inherited util.MAX_RETRIES, so
each of those probes spent seconds of backoff sleeps inside a handler
thread. Three consider items about code this phase added were taken
as well: the probe is now built lazily and only when --upstream is
set, a HEAD failure is logged and counted instead of being
indistinguishable from a tag which does not exist, and
--upstream-check-interval rejects a negative value rather than
silently behaving like 0. The round's one documentation correction
was the shutdown summary's causal claim: pull_cache_stale counts
every re-fetch the check provoked, including the unverifiable ones,
not only the tags upstream had really changed.
The round's substantive gap was a test one. Nothing exercised the
restructured read path under concurrency, which the risk table names
as the failure mode, and the suite would have passed with the
re-probe taken under the pull lock deleted entirely. The mutant set
is now fifteen rather than twelve, all killed by the expected test,
and includes both that deletion and dropping the lock itself. The
mutants are at scratchpad/mutants-round1.json in the session
scratch directory, which is not durable; the fifteen claims are
listed in the pull request.
Review round 2 (2026-12-02). One fix item, and the sharpest one of
the phase: the read path asked is_fresh() a second time under the pull
lock to find out whether the thread which had held it had already
re-fetched, and is_fresh() is rate limited. With any non-zero
--upstream-check-interval the second call landed inside the interval the
first had just refreshed, so a tag the first call found stale was reported
fresh, served stale, and never counted or re-fetched -- for the life of the
record, because each detection refreshed the timestamp again. The mode the
documentation recommends for a latency-sensitive workload therefore
disabled the feature it was rate-limiting. Decision 6 already recorded that
a HEAD followed by a GET performs one upstream check only when the interval
is non-zero; this is the other half of that observation, which the plan did
not draw.
Staleness is now decided once per request, before the lock. Each record
carries a revision which record() changes and a check never does, and the
thread holding the lock compares the revision it captured rather than
asking again. That is the question the second check was really asking --
"did whoever held the lock do this work" -- and it costs one upstream HEAD
per stale request instead of two.
The structural lesson for later phases is about where the test coverage was, not about the locking. Every handler test ran at the default interval of 0, which is the one value at which the bug does not appear, so the suite covered the feature's two modes as though they were one. The fixture is now shared between an interval-0 class and an interval-60 class rather than written for the default and assumed to generalise.
Four other consider items about code this phase added were taken: an
unreadable read-back after a successful fetch is a distinct verdict and is
counted in images_failed rather than producing a 502 or a 404 no
statistic records; _parse_v2_path() validates the repository and
reference against the registry grammar, because httpx resolves dot
segments before sending and the new freshness probe is a credentialed
request built from those two halves; is_fresh() rejects a None upstream
callable instead of reporting it as an outage; and the probe's Image is
built under the lock rather than raced for and discarded, which leaked the
loser's thread pool and httpx clients. The fifth was cosmetic:
test_registry_input_digest.py now uses unittest like the modules beside
it.
Declined, with reasons on the pull request: a non-zero default for the
interval (a behaviour change, and the trade-off is documented with its
mitigation), a status_code property on APIException (a pre-existing
convention whose value is in migrating call sites outside this diff), a
test-visible accessor for the record layout (the refactor did not in fact
disturb the tests which read it), and collapsing the two documents'
overlapping freshness prose (both copies are accurate and both were
updated).
Eleven mutants over this round's changes, each with the test expected to
catch it; all killed by that test. Three of round 1's fifteen mutated the
read path's second freshness check and no longer have a line to mutate.
The mutants are at scratchpad/mutants-round2.json in the session scratch
directory, which is not durable; the eleven claims are listed on the pull
request.
Review round 3 (2026-12-02). Two fix items, both consequences of
earlier rounds' own additions rather than of the original change -- which
is the shape the loop is supposed to catch, and what made the round worth
running.
The first is a lesson about sentinels. Round 2 added _parse_v2_path()
validation and expressed a rejection as ('unknown', 'unknown'),
reasoning that the sentinel had to be a pair the grammar itself admits so
that a rejected path could not build a URL nothing else could. That
reasoning is sound about the probe and wrong about the callers:
unknown is also a repository a client may legitimately ask for, so no
caller could tell a rejection from a real request for it. The manifest PUT
therefore pushed a grammar-rejected image into downstream under that name
and answered 201, where before the validation existed the raw name reached
downstream and was refused -- a security check left the push path less
safe than it found it. The rejection is now (None, None), not a name at
all, and each of the five handlers answers it before anything is asked of
downstream or upstream: 400 from the PUT, 404 from the manifest and blob
GET and HEAD. The generalisable rule: a sentinel drawn from the value
space it signals about cannot be distinguished from a legitimate value, so
make it unrepresentable rather than merely unlikely.
The second is an asymmetry round 1 introduced. Round 1 wrapped the HEAD
handler's call to the shared read path in a try/except so a failure is
logged and counted rather than silently rendered as "this tag does not
exist", and left the GET handler calling the same helper bare. A non-404
failure from either downstream probe therefore escaped do_GET to
ThreadingHTTPServer, which the client saw as a dropped connection rather
than the 502 the handler intends, and images_failed did not account for
it -- contradicting what docs/internals.md says that counter covers. The
GET path now guards the same region.
Three consider items about code this phase added were taken. A manifest
requested by digest rather than by tag is no longer freshness checked at
all: a digest names immutable content, so a downstream hit on one is a hit
by definition, where before it spent an upstream probe that could never
report a change and -- on the first request for each digest, which has no
record -- re-fetched the whole image. containerd and Kubernetes request
manifests by digest routinely, so that was a regression against the
pre-change behaviour for a common client rather than a latency nicety. The
path regexes anchor with \Z rather than $, which in Python also
matches before a trailing newline, and the whole repository name is now
bounded at the 255 characters the registry spec gives. And the read-back's
clear_manifest_cache() call was removed: it resets only the fields
get_manifest() consults, which the proxy never calls on a downstream
Image, so the call could not affect what the read-back saw and the test
asserting it pinned a no-op as though it were the mechanism.
The documentation item was taken as one sentence: AGENTS.md's pull-through
bullet is a factual description of the proxy's control flow, and after
round 1 it described a cache hit as unconditional and did not mention
proxy_freshness.py at all.
Declined, with a reason on the pull request: the upstream_probe setter's
asymmetry with its getter, which is cosmetic and has no production caller.
The round's changes took proxy.py to 1,557 lines, over the ratchet's
1,500-line threshold, so the V2 path grammar and its parser moved to
occystrap/proxy_paths.py as V2PathMixin -- the same answer round 2 gave
when the freshness code did this, and for the same reason: the module is a
coherent unit (the whole answer to "is this a path this proxy will act
on?") rather than an arbitrary cut to buy lines. proxy.py finished at
1,461, below the 1,485 it started this round at, so the baseline still
needs no entry for it.
Eleven mutants over this round's changes. One survived first time, and is the
round's own lesson about enumerating a class rather than an instance:
reverting the grammar rejection to a placeholder name was caught, but
reverting the split-count rejection -- the parser's other return, for a
path with no separator or with two of them -- was not, because every
handler-level test used a grammar-rejected path. A second separator does
reach a handler, since the router dispatches on /manifests/ appearing
anywhere in the path, so the gap was reachable. Both shapes are now driven
through all five handlers, both are logged, and the mutant is killed. The
rig is at scratchpad/mutate.sh in the session scratch directory, which is
not durable; the eleven claims are listed on the pull request.