mirror of
https://github.com/agent0ai/a0-plugins.git
synced 2026-12-04 03:18:07 +00:00
Make plugin index publication recoverable
Stage and validate the next index before replacing the public asset, retain the previous index for recovery, and check GitHub state after uncertain mutations. Allow the downloader to use recovery assets while keeping invalid indexes out. Add an explicit full-rebuild workflow option that ignores selection filters and checks the complete catalog before publishing. Document recovery and add an offline regression check for publication failures and full rebuilds. Validated the failure scenarios and a full rebuild of 185 eligible plugins, workflow YAML and shell syntax, Python syntax, and git diff --check. Refs #575
This commit is contained in:
1 parent
4af36e230c
commit
581001338f
5 files changed
+308
-42
No files matched your search
@@ -8,6 +8,11 @@ on:
|
||||
- "authors/**"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
rebuild_index:
|
||||
description: "Rebuild the complete index without downloading the current release; ignores selection and cleanup inputs"
|
||||
type: boolean
|
||||
required: false
|
||||
default: false
|
||||
max_plugins:
|
||||
description: "Max number of plugins to process"
|
||||
required: false
|
||||
@@ -74,6 +79,7 @@ jobs:
|
||||
python -m pip install pyyaml pillow
|
||||
|
||||
- name: Download current index.json
|
||||
if: ${{ github.event.inputs.rebuild_index != 'true' }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ steps.bot-app-token.outputs.token }}
|
||||
INDEX_RELEASE_TAG: generated-index
|
||||
@@ -81,7 +87,7 @@ jobs:
|
||||
python scripts/download_index_release.py
|
||||
|
||||
- name: Resolve orphan plugin names
|
||||
if: ${{ github.event.inputs.cleanup_orphans == 'true' }}
|
||||
if: ${{ github.event.inputs.cleanup_orphans == 'true' && github.event.inputs.rebuild_index != 'true' }}
|
||||
id: orphan_names
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ steps.bot-app-token.outputs.token }}
|
||||
@@ -93,13 +99,33 @@ jobs:
|
||||
- name: Sync plugin state
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ steps.bot-app-token.outputs.token }}
|
||||
REBUILD_INDEX: ${{ github.event.inputs.rebuild_index || 'false' }}
|
||||
MAX_PLUGINS: ${{ github.event.inputs.max_plugins || '1000' }}
|
||||
START_FROM: ${{ github.event.inputs.start_from || '0' }}
|
||||
PLUGIN_NAMES: ${{ github.event.inputs.cleanup_orphans == 'true' && steps.orphan_names.outputs.plugin_names || github.event.inputs.plugin_names || '' }}
|
||||
BEFORE_SHA: ${{ github.event.inputs.cleanup_orphans == 'true' && github.sha || github.event.inputs.before_sha || github.event.before || '' }}
|
||||
AFTER_SHA: ${{ github.event.inputs.cleanup_orphans == 'true' && github.sha || github.event.inputs.after_sha || github.sha || '' }}
|
||||
run: |
|
||||
if [ "$REBUILD_INDEX" = "true" ]; then
|
||||
rm -f index.json
|
||||
export PLUGIN_NAMES="" BEFORE_SHA="" AFTER_SHA="$GITHUB_SHA" START_FROM="0"
|
||||
fi
|
||||
python scripts/sync_plugin_state.py
|
||||
if [ "$REBUILD_INDEX" = "true" ]; then
|
||||
python - <<'PY'
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
expected = {
|
||||
path.parent.name for path in Path("plugins").glob("*/index.yaml")
|
||||
if not path.parent.name.startswith("_") and not (path.parent / "blocked.md").exists()
|
||||
}
|
||||
actual = set(json.loads(Path("index.json").read_text())["plugins"])
|
||||
if actual != expected:
|
||||
raise SystemExit(f"Incomplete rebuild: missing={sorted(expected - actual)}, extra={sorted(actual - expected)}")
|
||||
print(f"Verified complete index: {len(actual)} plugins")
|
||||
PY
|
||||
fi
|
||||
|
||||
- name: Publish index.json to Release (replace asset)
|
||||
env:
|
||||
|
||||
@@ -134,3 +134,11 @@ Use tags from [`TAGS.md`](./TAGS.md) where possible (recommended: up to 5 tags):
|
||||
By contributing to this repository, you agree that your submission must not contain malicious content.
|
||||
|
||||
If we detect malicious behavior (including but not limited to malware, credential theft, obfuscation intended to hide harmful behavior, or supply-chain attacks), the submission will be removed and **we will report it** to the relevant platforms and/or authorities. **Legal action may be taken if needed.**
|
||||
|
||||
## Index maintenance
|
||||
|
||||
The `generated-index` release serves `index.json`. The shared publisher uploads and verifies `index.json.next` before renaming the current index to `index.json.previous` and promoting the new index. The previous copy is retained for recovery. These renames are not atomic; the downloader can use a completed recovery asset if the main file is missing, and the next publisher restores it before continuing. Keep the existing workflow serialization enabled.
|
||||
|
||||
If the release or all usable index assets are missing, manually run **Generate Plugin State** on `main` with **rebuild_index** enabled. This starts a complete index from repository metadata, ignores plugin/diff/offset/cleanup selections, and verifies that all eligible plugins are included before publishing. `max_plugins` remains a safety limit and must cover the whole catalog. Normal runs still require a valid existing index. Rebuilds also sync plugin discussions; repository statistics are refreshed by the existing stats workflow.
|
||||
|
||||
After recovery, check the public [index download](https://github.com/agent0ai/a0-plugins/releases/download/generated-index/index.json). Run the offline publication regression check with `python scripts/test_index_release.py`.
|
||||
@@ -121,17 +121,28 @@ def main() -> int:
|
||||
_fail("Release response missing assets")
|
||||
|
||||
download_url: str | None = None
|
||||
for a in assets:
|
||||
if not isinstance(a, dict):
|
||||
continue
|
||||
if a.get("name") == asset_name and isinstance(a.get("browser_download_url"), str):
|
||||
download_url = cast(str, a.get("browser_download_url"))
|
||||
for name in (asset_name, f"{asset_name}.next", f"{asset_name}.previous"):
|
||||
for a in assets:
|
||||
if not isinstance(a, dict):
|
||||
continue
|
||||
if a.get("name") == name and a.get("state") == "uploaded" and isinstance(a.get("browser_download_url"), str):
|
||||
download_url = cast(str, a.get("browser_download_url"))
|
||||
if name != asset_name:
|
||||
print(f"WARN: {asset_name} missing; downloading recovery asset {name}")
|
||||
break
|
||||
if download_url:
|
||||
break
|
||||
|
||||
if not download_url:
|
||||
_fail(f"Release '{tag}' does not contain asset '{asset_name}'")
|
||||
|
||||
content = _download_bytes(download_url)
|
||||
try:
|
||||
index = json.loads(content)
|
||||
except ValueError as e:
|
||||
_fail(f"Invalid index JSON: {e}")
|
||||
if not isinstance(index, dict) or not isinstance(index.get("plugins"), dict) or not index["plugins"]:
|
||||
_fail("Downloaded index must contain a non-empty plugins object")
|
||||
INDEX_PATH.write_bytes(content)
|
||||
print(f"Downloaded {asset_name} -> {INDEX_PATH.relative_to(REPO_ROOT)}")
|
||||
return 0
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
@@ -165,7 +166,7 @@ def _create_release(owner: str, repo: str) -> dict[str, Any]:
|
||||
return rel
|
||||
|
||||
|
||||
def _upload_asset(owner: str, repo: str, release: dict[str, Any], asset_name: str, content: bytes) -> None:
|
||||
def _upload_asset(owner: str, repo: str, release: dict[str, Any], asset_name: str, content: bytes) -> dict[str, Any]:
|
||||
upload_url_tmpl = release.get("upload_url")
|
||||
if not isinstance(upload_url_tmpl, str) or "{" not in upload_url_tmpl:
|
||||
_fail("Release upload_url missing")
|
||||
@@ -189,9 +190,6 @@ def _upload_asset(owner: str, repo: str, release: dict[str, Any], asset_name: st
|
||||
with urllib.request.urlopen(req, timeout=60) as resp:
|
||||
payload = resp.read().decode("utf-8", errors="replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code == 422:
|
||||
# Asset already exists (common when two publishers race). Caller can delete and retry.
|
||||
raise
|
||||
msg = e.read().decode("utf-8", errors="replace") if hasattr(e, "read") else str(e)
|
||||
_fail(f"Asset upload failed ({e.code}) POST {url}: {msg}")
|
||||
except Exception as e:
|
||||
@@ -199,21 +197,47 @@ def _upload_asset(owner: str, repo: str, release: dict[str, Any], asset_name: st
|
||||
|
||||
try:
|
||||
parsed = json.loads(payload)
|
||||
except Exception:
|
||||
parsed = None
|
||||
except ValueError as e:
|
||||
_fail(f"Asset upload returned invalid JSON: {e}")
|
||||
|
||||
if isinstance(parsed, dict) and parsed.get("name") == asset_name:
|
||||
print(f"Uploaded asset: {asset_name}")
|
||||
return
|
||||
if (
|
||||
not isinstance(parsed, dict)
|
||||
or not isinstance(parsed.get("id"), int)
|
||||
or parsed.get("name") != asset_name
|
||||
or parsed.get("state") != "uploaded"
|
||||
or parsed.get("size") != len(content)
|
||||
):
|
||||
_fail(f"Asset upload was not complete: {asset_name}")
|
||||
|
||||
print(f"Uploaded asset: {asset_name}")
|
||||
return parsed
|
||||
|
||||
|
||||
def _delete_asset(owner: str, repo: str, asset_id: int) -> None:
|
||||
_request_nojson(
|
||||
"DELETE",
|
||||
f"https://api.github.com/repos/{owner}/{repo}/releases/assets/{asset_id}",
|
||||
)
|
||||
url = f"https://api.github.com/repos/{owner}/{repo}/releases/assets/{asset_id}"
|
||||
try:
|
||||
_request_nojson("DELETE", url)
|
||||
except PublishReleaseError:
|
||||
if _request_json_allow_404("GET", url) is not None:
|
||||
raise
|
||||
|
||||
|
||||
def _rename_asset(owner: str, repo: str, asset_id: int, name: str) -> None:
|
||||
url = f"https://api.github.com/repos/{owner}/{repo}/releases/assets/{asset_id}"
|
||||
for attempt in range(3):
|
||||
try:
|
||||
# A failed response may still have changed the name on GitHub.
|
||||
asset = _request_json("GET", url)
|
||||
if asset.get("name") == name:
|
||||
return
|
||||
asset = _request_json("PATCH", url, {"name": name})
|
||||
if asset.get("name") != name:
|
||||
_fail(f"Asset rename did not return the expected name: {name}")
|
||||
return
|
||||
except PublishReleaseError:
|
||||
if attempt == 2:
|
||||
raise
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -226,6 +250,12 @@ def main() -> int:
|
||||
return 0
|
||||
|
||||
content = INDEX_PATH.read_bytes()
|
||||
try:
|
||||
index = json.loads(content)
|
||||
except ValueError as e:
|
||||
_fail(f"Invalid index JSON: {e}")
|
||||
if not isinstance(index, dict) or not isinstance(index.get("plugins"), dict) or not index["plugins"]:
|
||||
_fail("Refusing to publish an index without a non-empty plugins object")
|
||||
|
||||
release_opt = _get_latest_release(owner, repo)
|
||||
if not release_opt:
|
||||
@@ -241,31 +271,38 @@ def main() -> int:
|
||||
# Fetch full release payload (assets can be truncated/absent depending on endpoint used)
|
||||
release = _get_release(owner, repo, rid)
|
||||
|
||||
def _delete_existing_assets(release_payload: dict[str, Any]) -> None:
|
||||
assets = release_payload.get("assets")
|
||||
if not isinstance(assets, list):
|
||||
return
|
||||
for a in assets:
|
||||
if not isinstance(a, dict):
|
||||
continue
|
||||
if a.get("name") != asset_name:
|
||||
continue
|
||||
aid = a.get("id")
|
||||
if isinstance(aid, int):
|
||||
print(f"Deleting existing asset: {asset_name} (id={aid})")
|
||||
_delete_asset(owner, repo, aid)
|
||||
assets = {a["name"]: a for a in release.get("assets", [])}
|
||||
next_name = f"{asset_name}.next"
|
||||
previous_name = f"{asset_name}.previous"
|
||||
current = assets.get(asset_name)
|
||||
|
||||
# Finish an interrupted publication before replacing any recovery assets.
|
||||
if current is None:
|
||||
for name in (next_name, previous_name):
|
||||
asset = assets.get(name)
|
||||
if asset and asset.get("state") == "uploaded" and asset.get("size", 0) > 0:
|
||||
_rename_asset(owner, repo, asset["id"], asset_name)
|
||||
current = assets.pop(name)
|
||||
break
|
||||
|
||||
if next_name in assets:
|
||||
_delete_asset(owner, repo, assets[next_name]["id"])
|
||||
staged = _upload_asset(owner, repo, release, next_name, content)
|
||||
|
||||
if current and previous_name in assets:
|
||||
_delete_asset(owner, repo, assets[previous_name]["id"])
|
||||
|
||||
# Safer replacement strategy: try upload first; if it already exists (422), delete and retry.
|
||||
try:
|
||||
_upload_asset(owner, repo, release, asset_name, content)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code != 422:
|
||||
raise
|
||||
print(f"Asset already exists ({asset_name}); deleting and retrying")
|
||||
_delete_existing_assets(release)
|
||||
# Refresh release assets after deletion
|
||||
release = _get_release(owner, repo, rid)
|
||||
_upload_asset(owner, repo, release, asset_name, content)
|
||||
if current:
|
||||
_rename_asset(owner, repo, current["id"], previous_name)
|
||||
_rename_asset(owner, repo, staged["id"], asset_name)
|
||||
except PublishReleaseError:
|
||||
if current:
|
||||
try:
|
||||
_rename_asset(owner, repo, current["id"], asset_name)
|
||||
except PublishReleaseError as e:
|
||||
print(f"WARN: Unable to restore {asset_name}; recovery assets retained: {e}")
|
||||
raise
|
||||
|
||||
html = release.get("html_url")
|
||||
if isinstance(html, str):
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Offline regression check: python scripts/test_index_release.py."""
|
||||
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
from contextlib import redirect_stdout
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import download_index_release as download
|
||||
import publish_index_release as publish
|
||||
|
||||
|
||||
OLD = b'{"version":1,"plugins":{"kept":{},"removed":{}}}'
|
||||
NEW = b'{"version":1,"plugins":{"kept":{}}}'
|
||||
|
||||
|
||||
def check(initial: dict[str, bytes], fault: str = "", content: bytes = NEW) -> None:
|
||||
assets = {}
|
||||
contents = {}
|
||||
faults = []
|
||||
mutations = []
|
||||
serial = 0
|
||||
|
||||
def add(name: str, data: bytes) -> dict:
|
||||
nonlocal serial
|
||||
serial += 1
|
||||
asset = {"id": serial, "name": name, "state": "uploaded", "size": len(data)}
|
||||
assets[serial] = asset
|
||||
contents[serial] = data
|
||||
return asset
|
||||
|
||||
for name, data in initial.items():
|
||||
add(name, data)
|
||||
|
||||
def error(request, code: int) -> None:
|
||||
raise urllib.error.HTTPError(request.full_url, code, "Injected failure", {}, io.BytesIO(b'{}'))
|
||||
|
||||
def request(request, timeout):
|
||||
url = urllib.parse.urlparse(request.full_url)
|
||||
method = request.get_method()
|
||||
if method != "GET":
|
||||
mutations.append(method)
|
||||
if url.hostname == "download.test":
|
||||
return io.BytesIO(contents[int(url.path.strip("/"))])
|
||||
if "/releases/assets/" in url.path:
|
||||
asset_id = int(url.path.rsplit("/", 1)[1])
|
||||
if asset_id not in assets:
|
||||
error(request, 404)
|
||||
asset = assets[asset_id]
|
||||
if method == "DELETE":
|
||||
assert asset["name"] != "index.json", "The current index must never be deleted"
|
||||
del assets[asset_id]
|
||||
del contents[asset_id]
|
||||
if fault == "delete_502" and not faults:
|
||||
faults.append(fault)
|
||||
error(request, 502)
|
||||
return io.BytesIO()
|
||||
if method == "PATCH":
|
||||
name = json.loads(request.data)["name"]
|
||||
if fault == "promotion_failure" and asset["name"] == "index.json.next":
|
||||
faults.append(fault)
|
||||
error(request, 502)
|
||||
assert all(a["id"] == asset_id or a["name"] != name for a in assets.values())
|
||||
asset["name"] = name
|
||||
if fault == "rename_502" and not faults:
|
||||
faults.append(fault)
|
||||
error(request, 502)
|
||||
return io.BytesIO(json.dumps(asset).encode())
|
||||
if method == "POST" and url.hostname == "uploads.github.com":
|
||||
assert "index.json" not in urllib.parse.parse_qs(url.query)["name"]
|
||||
if fault == "upload_failure":
|
||||
faults.append(fault)
|
||||
error(request, 502)
|
||||
asset = add(urllib.parse.parse_qs(url.query)["name"][0], request.data)
|
||||
if fault == "incomplete_upload":
|
||||
faults.append(fault)
|
||||
asset["state"] = "starter"
|
||||
return io.BytesIO(json.dumps(asset).encode())
|
||||
assert method == "GET", (method, url.path)
|
||||
payload = {
|
||||
"id": 1,
|
||||
"upload_url": "https://uploads.github.com/repos/test/repo/releases/1/assets{?name,label}",
|
||||
"assets": [dict(a, browser_download_url=f'https://download.test/{a["id"]}') for a in assets.values()],
|
||||
}
|
||||
return io.BytesIO(json.dumps(payload).encode())
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
index = root / "index.json"
|
||||
with (
|
||||
patch.dict(os.environ, {"GITHUB_REPOSITORY": "test/repo", "GITHUB_TOKEN": "test"}, clear=True),
|
||||
patch.object(publish, "INDEX_PATH", index),
|
||||
patch.object(download, "INDEX_PATH", index),
|
||||
patch.object(download, "REPO_ROOT", root),
|
||||
patch("urllib.request.urlopen", request),
|
||||
patch("time.sleep"),
|
||||
redirect_stdout(io.StringIO()),
|
||||
):
|
||||
if initial:
|
||||
assert download.main() == 0
|
||||
expected = next(initial[name] for name in ("index.json", "index.json.next", "index.json.previous") if name in initial)
|
||||
assert index.read_bytes() == expected
|
||||
index.write_bytes(content)
|
||||
failed = False
|
||||
try:
|
||||
assert publish.main() == 0
|
||||
except publish.PublishReleaseError:
|
||||
failed = True
|
||||
assert failed == (fault not in ("", "rename_502", "delete_502")), fault
|
||||
current = next(a for a in assets.values() if a["name"] == "index.json")
|
||||
assert contents[current["id"]] == (OLD if failed else content), fault
|
||||
if fault == "invalid_index":
|
||||
assert not mutations
|
||||
elif fault:
|
||||
assert faults, f"Fault was not exercised: {fault}"
|
||||
if not failed:
|
||||
assert download.main() == 0
|
||||
assert index.read_bytes() == content
|
||||
|
||||
|
||||
def check_rebuild() -> None:
|
||||
import yaml
|
||||
|
||||
repo = Path(__file__).resolve().parents[1]
|
||||
workflow = yaml.safe_load((repo / ".github/workflows/generate-plugin-state.yml").read_text())
|
||||
script = next(step["run"] for step in workflow["jobs"]["refresh"]["steps"] if step["name"] == "Sync plugin state")
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / "plugins").symlink_to(repo / "plugins", target_is_directory=True)
|
||||
(root / "scripts").mkdir()
|
||||
(root / "scripts/sync_plugin_state.py").write_text(
|
||||
"import sys\nfrom pathlib import Path\n"
|
||||
f"sys.path.insert(0, {str(repo / 'scripts')!r})\n"
|
||||
"import sync_plugin_state as sync\n"
|
||||
"sync.INDEX_JSON_PATH = Path('index.json')\n"
|
||||
"sync._get_repo_and_category = lambda *args: ('repo', 'category')\n"
|
||||
"sync._sync_existing_plugin = lambda *args: ('updated', 'https://example.com/discussion')\n"
|
||||
"sync._sync_deleted_plugin = lambda *args: 'missing'\n"
|
||||
"raise SystemExit(sync.main())\n"
|
||||
)
|
||||
(root / "index.json").write_text('{"plugins":{"removed_plugin":{}}}')
|
||||
env = {
|
||||
"PATH": str(Path(sys.executable).parent) + os.pathsep + os.defpath,
|
||||
"REBUILD_INDEX": "true",
|
||||
"GITHUB_REPOSITORY": "test/repo",
|
||||
"GITHUB_SHA": subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=repo, text=True).strip(),
|
||||
"PLUGIN_NAMES": "does_not_exist",
|
||||
"BEFORE_SHA": "invalid-sha",
|
||||
"AFTER_SHA": "invalid-sha",
|
||||
"START_FROM": "9999",
|
||||
"MAX_PLUGINS": "1000",
|
||||
}
|
||||
result = subprocess.run(["bash", "-e", "-c", script], cwd=root, env=env, capture_output=True, text=True)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
rebuilt = json.loads((root / "index.json").read_text())["plugins"]
|
||||
assert "removed_plugin" not in rebuilt
|
||||
assert rebuilt
|
||||
print(result.stdout.splitlines()[-1])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
check({"index.json": OLD})
|
||||
check({"index.json": OLD}, "rename_502")
|
||||
check({"index.json": OLD}, "upload_failure")
|
||||
check({"index.json": OLD}, "incomplete_upload")
|
||||
check({"index.json": OLD}, "promotion_failure")
|
||||
check({"index.json": OLD, "index.json.previous": OLD}, "delete_502")
|
||||
check({"index.json.next": NEW, "index.json.previous": OLD})
|
||||
check({"index.json.previous": OLD})
|
||||
check({})
|
||||
check({"index.json": OLD}, "invalid_index", b'{"error":"Not Found"}')
|
||||
check({"index.json": OLD}, "invalid_index", b'{"plugins":{}}')
|
||||
check_rebuild()
|
||||
print("Index publication and recovery checks passed.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user