Skip to content

Commit 5a89572

Browse files
committed
fix: scope installation-missing cache per repository
1 parent 0ac82e6 commit 5a89572

6 files changed

Lines changed: 109 additions & 13 deletions

File tree

‎docs/proof/reconcile-throttle-resilience/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Production run 31634514031-era evidence showed `inspected_targets=3`, `skipped_t
44

55
The code investigation found that parked REST checks, standard REST checks, and batched GraphQL canonical discovery all selected `GITHUB_TOKEN`. In the scheduled workflow that variable was `${{ github.token }}`, the same repository Actions credential used by the prior-artifact download and stuck-run Actions API remediation. Round 1 moved those reads to one OpenClaw installation token, which would have failed every target owned outside that installation.
66

7-
The owner decision preserves cross-owner recovery. The operator now reuses the Worker's canonical GitHub App plumbing—`githubAppCredentials`, `signGithubAppJwt`, `githubAppInstallationId`, and `createGithubAppTokenFor`—to mint a read-only contents/issues/pull-request token for each target owner. Tokens and rejected setup promises are cached per owner for the cycle, and GraphQL batches are owner-homogeneous. A genuinely missing or revoked installation is a per-target `installation_missing` skip with a bounded sample; it never aborts the cycle. Repository artifact and Actions-run operations remain on `${{ github.token }}`.
7+
The owner decision preserves cross-owner recovery. The operator now reuses the Worker's canonical GitHub App plumbing—`githubAppCredentials`, `signGithubAppJwt`, `githubAppInstallationId`, and `createGithubAppTokenFor`—to mint a read-only contents/issues/pull-request token for each target owner. Successful tokens and setup-throttle rejections are cached per owner for the cycle, while `installation_missing` rejections are cached per repository so a selected-repositories installation can still reach an accessible sibling repository. GraphQL batches are owner-homogeneous. A genuinely missing or revoked installation is a per-target `installation_missing` skip with a bounded sample; it never aborts the cycle. Repository artifact and Actions-run operations remain on `${{ github.token }}`.
88

99
Round 4 closes the rollout boundary: the operator defaults target reads to `github-app` mode and validates the App ID/private-key pair synchronously at startup. A missing ID, missing key, or missing pair is a hard error naming exactly the absent field. The repository Actions token is usable for target reads only through the explicit `EXACT_REVIEW_TARGET_TOKEN_MODE=actions` opt-in. Both checked-in operator workflows select `github-app`, and the scheduled steps pass the referenced private-key secret; the repository currently exposes that secret name.
1010

‎docs/proof/reconcile-throttle-resilience/behavior-contract.md‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
Exact-review dead-letter reconciliation in `github-app` target-token mode requires a complete App ID/private-key pair at process startup. Key-only, ID-only, and entirely absent App credentials fail before any queue or GitHub request and name the missing field; complete credentials proceed. The repository Actions token can never become an implicit fallback and remains available only through the explicit `actions` mode.
66

7-
With complete App credentials, reconciliation mints target-read credentials from each target owner's GitHub App installation, caches both successful tokens and rejected setup promises per owner for the cycle, and uses successful tokens for public target REST and owner-homogeneous GraphQL reads. A missing or revoked installation becomes an `installation_missing` skip for that target while other owners continue. One isolated GitHub-confirmed rate-limit or abuse 403, or any 429, during installation lookup, token minting, or a target read skips only the affected target, owner, or GraphQL batch, so later owners and targets can still be inspected and recovered. A cached setup rejection contributes only one actual call to the shared three-consecutive-throttle fuse. Three distinct consecutive confirmed throttles stop further inspection in that phase, preserving a bounded per-cycle request budget. App-setup skips are structured as `github_throttled scope=app_setup`; genuine 401 and non-throttle 403 setup failures retain the conservative abort behavior.
7+
With complete App credentials, reconciliation mints target-read credentials from each target owner's GitHub App installation and uses successful tokens for public target REST and owner-homogeneous GraphQL reads. Successful installation-scoped tokens and rejected setup throttles are cached per owner for the cycle; `installation_missing` rejections are cached per repository. A missing selected repository therefore becomes an `installation_missing` skip while a later accessible repository under the same owner is still looked up and recovered. One isolated GitHub-confirmed rate-limit or abuse 403, or any 429, during installation lookup, token minting, or a target read skips only the affected target, owner, or GraphQL batch, so later owners and targets can still be inspected and recovered. A cached setup-throttle rejection contributes only one actual call to the shared three-consecutive-throttle fuse. Three distinct consecutive confirmed throttles stop further inspection in that phase, preserving a bounded per-cycle request budget. App-setup skips are structured as `github_throttled scope=app_setup`; genuine 401 and non-throttle 403 setup failures retain the conservative abort behavior.
88

99
## Exercised surface
1010

@@ -21,13 +21,14 @@ With complete App credentials, reconciliation mints target-read credentials from
2121
5. Ordinary authorization 403s in serial REST discovery, GraphQL discovery, and recovery revalidation abort the remaining phase and recover nothing.
2222
6. Every target REST and GraphQL request carries the synthetic target-App token while the workflow YAML retains `${{ github.token }}` for repository Actions work.
2323
7. Two targets under different owners exercise real App JWT signing and loopback installation/token endpoints. The installed owner recovers with its minted token; the absent owner reports one `installation_missing` skip and sample; the cycle completes.
24-
8. Three targets under one valid installation mint one owner token. An ordinary authorization 403 on the first target remains fail-closed and aborts the untouched targets.
25-
9. Token minting for owner A returns 429 or a confirmed rate-limit 403. Three owner-A targets report structured `github_throttled scope=app_setup stage=token_mint` skips, the rejected mint is requested once, owner B mints successfully, and the cycle recovers owner B.
26-
10. Installation lookup for owner A returns a confirmed rate-limit 403. Owner A skips with `stage=installation_lookup`, owner B recovers, and the cycle completes.
27-
11. One throttled owner spans three owner-homogeneous GraphQL batches. The cached rejection skips all 81 owner targets but counts once toward the fuse; the later healthy owner is inspected and recovered.
28-
12. Three distinct owners return setup throttles. The shared fuse stops before a fourth owner's lookup or mint, bounding setup traffic to three calls.
29-
13. Installation lookup and token minting each return genuine 401 and non-throttle 403 responses. Every variant keeps the fail-closed abort, while a 404 race between lookup and mint retains the prior bounded `installation_missing` behavior.
30-
14. The real operator process runs the App-credential startup matrix: private-key only fails naming the App ID, App ID only fails naming the private key, neither fails naming both, and both proceed. The same credential-less fixture succeeds only after explicitly selecting `actions` mode. The scheduled and manual workflow YAML both select `github-app` and pass the private-key secret while retaining `${{ github.token }}` solely for repository-owned work.
24+
8. Two repositories under one selected-repositories installation are checked in one cycle. Repository A returns an installation 404 and is skipped as `installation_missing`; repository B receives its own lookup, mints successfully, and recovers.
25+
9. Three targets under one valid installation mint one owner token. An ordinary authorization 403 on the first target remains fail-closed and aborts the untouched targets.
26+
10. Token minting for owner A returns 429 or a confirmed rate-limit 403. Three owner-A targets report structured `github_throttled scope=app_setup stage=token_mint` skips, the rejected mint is requested once, owner B mints successfully, and the cycle recovers owner B.
27+
11. Installation lookup for owner A returns a confirmed rate-limit 403. Owner A skips with `stage=installation_lookup`, owner B recovers, and the cycle completes.
28+
12. One throttled owner spans three owner-homogeneous GraphQL batches. The cached rejection skips all 81 owner targets but counts once toward the fuse; the later healthy owner is inspected and recovered.
29+
13. Three distinct owners return setup throttles. The shared fuse stops before a fourth owner's lookup or mint, bounding setup traffic to three calls.
30+
14. Installation lookup and token minting each return genuine 401 and non-throttle 403 responses. Every variant keeps the fail-closed abort, while a 404 race between lookup and mint retains the prior bounded `installation_missing` behavior.
31+
15. The real operator process runs the App-credential startup matrix: private-key only fails naming the App ID, App ID only fails naming the private key, neither fails naming both, and both proceed. The same credential-less fixture succeeds only after explicitly selecting `actions` mode. The scheduled and manual workflow YAML both select `github-app` and pass the private-key secret while retaining `${{ github.token }}` solely for repository-owned work.
3132

3233
## Command and environment
3334

‎docs/proof/reconcile-throttle-resilience/red-green.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,17 @@ workflow target-token mode: expected github-app, actual undefined
7373
The green path makes `github-app` the default target-token mode, validates the App ID/private-key pair synchronously at startup, and returns the repository token only when `EXACT_REVIEW_TARGET_TOKEN_MODE=actions` is explicit. Key-only fails naming the missing App ID, ID-only fails naming the missing private key, neither fails naming both, and both proceeds. The scheduled and manual workflows now select `github-app`; repository settings expose the referenced private-key secret, so the inspected scheduled lane was fully configured, while any future missing secret will fail the cycle visibly instead of recreating the throttle.
7474

7575
The focused workflow/matrix selection passed 3/3 and the complete operator file passed 79/79 on Node 24. The final Docker receipt and full gate results are recorded in `receipt.json` and the PR body.
76+
77+
## Round 5: repository-scoped installation-missing cache
78+
79+
The round-5 red phase taught the loopback fixture to resolve installations by full `owner/repo` when supplied, then added one cycle containing a missing repository followed by an accessible repository under the same owner. Against the owner-level rejected-promise cache, the new regression failed while both existing owner-throttle cases remained green:
80+
81+
```text
82+
tests 3
83+
pass 2
84+
fail 1
85+
86+
AssertionError: expected recovered_targets 1, actual 0
87+
```
88+
89+
The green implementation keeps in-flight and rejected installation-missing mints under a normalized repository key. Only a successful installation token or a confirmed setup throttle is promoted to the owner cache. The same selection passed 3/3, including both 429 and confirmed-403 owner-throttle cases, and the complete operator file passed 80/80 on Node 24.

‎docs/proof/reconcile-throttle-resilience/run-proof.sh‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ corepack pnpm install --frozen-lockfile
2020

2121
echo "PROOF_PHASE=loopback"
2222
node --experimental-strip-types --test \
23-
--test-name-pattern='dead-letter workflow is manual|scheduled, bounded|target-read App mode|serial canonical discovery|serial recovery revalidation|100-target reconciliation|batched canonical discovery|multi-owner reconciliation|throttled owner token mint|throttled installation lookup|installation removed before token mint|batched discovery skips a throttled owner setup|cached setup throttle spanning three batches|ordinary installation_lookup|ordinary token_mint|persistent setup throttling|valid owner installation|operator previews' \
23+
--test-name-pattern='dead-letter workflow is manual|scheduled, bounded|target-read App mode|serial canonical discovery|serial recovery revalidation|100-target reconciliation|batched canonical discovery|multi-owner reconciliation|missing selected repository|throttled owner token mint|throttled installation lookup|installation removed before token mint|batched discovery skips a throttled owner setup|cached setup throttle spanning three batches|ordinary installation_lookup|ordinary token_mint|persistent setup throttling|valid owner installation|operator previews' \
2424
test/exact-review-dead-letter-operator.test.ts
2525

2626
echo "PROOF_PHASE=content"

‎scripts/exact-review-dead-letter-operator.mjs‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ class TargetReadTokenCache {
9595
}
9696
this.fallbackToken = String(env.GH_TOKEN || "").trim() || String(env.GITHUB_TOKEN || "").trim();
9797
this.tokensByOwner = new Map();
98+
this.mintsByRepository = new Map();
9899
if (this.mode === "actions") {
99100
if (!this.fallbackToken) {
100101
throw new Error(
@@ -136,12 +137,29 @@ class TargetReadTokenCache {
136137
return this.fallbackToken;
137138
}
138139
const ownerKey = owner.toLowerCase();
140+
const repositoryKey = `${owner}/${repo}`.toLowerCase();
141+
// Successful tokens and setup throttles are installation-scoped, so they remain owner-cached.
142+
// Selected-repository installations still authorize each repo on its own REST/GraphQL read,
143+
// whose 403/404 handling fails closed. An installation-missing 404 is repository-specific,
144+
// so keep the in-flight/rejected mint under the repository key until its outcome is known.
139145
let token = this.tokensByOwner.get(ownerKey);
146+
if (token) return token;
147+
148+
token = this.mintsByRepository.get(repositoryKey);
140149
if (!token) {
141150
token = this.mintForOwner(`${owner}/${repo}`);
142-
this.tokensByOwner.set(ownerKey, token);
151+
this.mintsByRepository.set(repositoryKey, token);
152+
}
153+
try {
154+
const mintedToken = await token;
155+
this.tokensByOwner.set(ownerKey, Promise.resolve(mintedToken));
156+
return mintedToken;
157+
} catch (error) {
158+
if (error instanceof TargetAppSetupThrottleError) {
159+
this.tokensByOwner.set(ownerKey, token);
160+
}
161+
throw error;
143162
}
144-
return token;
145163
}
146164

147165
async mintForOwner(targetRepo) {

‎test/exact-review-dead-letter-operator.test.ts‎

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2631,6 +2631,65 @@ test("multi-owner reconciliation recovers installed targets and reports missing
26312631
);
26322632
});
26332633

2634+
test("a missing selected repository does not hide an accessible repository under the same owner", async () => {
2635+
const { privateKey } = generateKeyPairSync("rsa", {
2636+
modulusLength: 2048,
2637+
privateKeyEncoding: { type: "pkcs8", format: "pem" },
2638+
publicKeyEncoding: { type: "spki", format: "pem" },
2639+
});
2640+
const scenario = await automaticReconcileScenario({
2641+
rows: [
2642+
row(
2643+
"missing",
2644+
"publication:missing",
2645+
1,
2646+
"retry_exhausted",
2647+
true,
2648+
"eligible",
2649+
"selected-owner/missing#1",
2650+
),
2651+
row(
2652+
"accessible",
2653+
"publication:accessible",
2654+
2,
2655+
"retry_exhausted",
2656+
true,
2657+
"eligible",
2658+
"selected-owner/accessible#2",
2659+
),
2660+
],
2661+
targetInstallations: new Map([
2662+
["selected-owner/missing", null],
2663+
["selected-owner/accessible", { id: 124, token: "selected-owner-token" }],
2664+
]),
2665+
operatorEnv: {
2666+
GH_TOKEN: "",
2667+
EXACT_REVIEW_TARGET_TOKEN_MODE: "github-app",
2668+
CLAWSWEEPER_APP_CLIENT_ID: "Iv23selectedrepos",
2669+
CLAWSWEEPER_APP_PRIVATE_KEY: privateKey,
2670+
},
2671+
});
2672+
2673+
assert.equal(scenario.first.code, 0, scenario.first.stderr);
2674+
const summary = JSON.parse(scenario.first.stdout);
2675+
assert.equal(summary.recovered_targets, 1);
2676+
assert.equal(summary.skipped_targets, 1);
2677+
assert.deepEqual(summary.skip_reasons, { installation_missing: 1 });
2678+
assert.deepEqual(
2679+
scenario.recoveries.map((recovery) => recovery.ids),
2680+
[["accessible"]],
2681+
);
2682+
assert.deepEqual(scenario.installationRequests, [
2683+
"selected-owner/missing",
2684+
"selected-owner/accessible",
2685+
]);
2686+
assert.deepEqual(scenario.tokenMintRequests, [124]);
2687+
assert.deepEqual(
2688+
new Set(scenario.targetReadAuthorizations),
2689+
new Set(["Bearer selected-owner-token"]),
2690+
);
2691+
});
2692+
26342693
for (const failedStatus of [429, 403]) {
26352694
test(`throttled owner token mint ${failedStatus} skips that owner's targets and recovers another owner`, async () => {
26362695
const { privateKey } = generateKeyPairSync("rsa", {
@@ -3336,7 +3395,11 @@ async function automaticReconcileScenario(options) {
33363395
);
33373396
return;
33383397
}
3339-
const installation = options.targetInstallations.get(owner.toLowerCase());
3398+
const repositoryKey = `${owner}/${repo}`.toLowerCase();
3399+
const installationKey = options.targetInstallations.has(repositoryKey)
3400+
? repositoryKey
3401+
: owner.toLowerCase();
3402+
const installation = options.targetInstallations.get(installationKey);
33403403
if (!installation) {
33413404
response.writeHead(404, { "content-type": "application/json" });
33423405
response.end(JSON.stringify({ message: "Not Found" }));

0 commit comments

Comments
 (0)