From 44847151f5a91dfe16ff87b8f87e0638271dbbd4 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:17:10 +0000 Subject: [PATCH 01/20] docs(openspec): plan the shared listing snapshot and tool facts in Valkey Plan #4668 as the OpenSpec change 4668-share-the-listing-snapshot-in-valkey. The memory bound of valkey-devops is --maxmemory 256mb inside a 384Mi limit. The bound has a validator command and a live check as its proof, and no test. ADR 0023 does not change: its line already names 256 MB. --- .../.openspec.yaml | 3 + .../design.md | 60 +++++++++ .../proposal.md | 72 +++++++++++ .../specs/project-brain/shared-cache/spec.md | 116 ++++++++++++++++++ .../tasks.md | 87 +++++++++++++ 5 files changed, 338 insertions(+) create mode 100644 openspec/changes/4668-share-the-listing-snapshot-in-valkey/.openspec.yaml create mode 100644 openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md create mode 100644 openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md create mode 100644 openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md create mode 100644 openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/.openspec.yaml b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/.openspec.yaml new file mode 100644 index 0000000000..08df51bc72 --- /dev/null +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-11-21 +skip_specs: false diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md new file mode 100644 index 0000000000..ac9d53ee4e --- /dev/null +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md @@ -0,0 +1,60 @@ +# Design + +## Decisions + +- **The memory bound of `valkey-devops` is `--maxmemory 256mb` inside a container limit of `384Mi`.**: The owner comment of 2026-11-19 on #4668 found four targets that do not agree (ADR 0023 line 134, #4624 item 6, the refined design of #4624, and the body of #4668). Only 256mb inside 384Mi keeps the owner decision 6 of #4624 (256 MB) and the rule of `openspec/specs/llm-valkey/spec.md` that `--maxmemory` is at most three quarters of the limit: 256 MiB is two thirds of 384Mi. The pull request comment on #4668 names this target and says that 240mb/320Mi and 256MB/320Mi in the bodies are replaced. The bodies of #4668 and #4624 stay as they are. +- **ADR 0023 does not change.**: Its line 134 already says that the item raises the `maxmemory` of `valkey-devops` from 96 MB to 256 MB, which is the decided bound, and it names no limit. `docs/adr/README.md` forbids an edit of the body of an accepted record, and `tests/invariants/test_adr_records.py` fails on a changed body hash. A Status History line is only for a fact that a change makes wrong, and no fact of the record becomes wrong. The limit is a value of the manifest and of the spec of this change, as the length rule of the ADR README asks. +- **The memory bound has a validator command and a live check as its proof, and no test.**: `docs/TESTING.md` forbids a test that asserts a value of a manifest, and the `test-tree` row refuses one (`tests/gate/tree_checks/config_values.py`). The proof is `uv run devops ci --check --only k8s` before the merge, and after the Argo CD sync `kubectl -n llm get deployment valkey-devops -o jsonpath=...` (the `--maxmemory 256mb` argument and the `384Mi` limit) and `redis_config_maxmemory{job="valkey-devops"}` at 268,435,456. +- **`TieredMapping` is a `MutableMapping` over a `cachetools.TTLCache` and the `ValkeyCacheTier`.**: No library gives a mapping over an in-process LRU and a Valkey tier with a breaker, a codec, a bound for each value and a schema check. As a `MutableMapping`, it plugs into `cachetools.cached`, so `_read_pypi` and `_linked_packages` keep their bodies and get a decorator. `__iter__` and `__len__` cover the in-process tier only, because a scan of the shared tier for each call has no use. +- **A read goes memory, then Valkey, then the source, and a hit fills the tiers above it.**: ADR 0023 section 2 sets this order for content-addressed data. A write goes to Valkey and then to memory. A failed Valkey write is a later miss, never an error of the caller. +- **The mapping encodes each value through a pydantic `TypeAdapter` of its value type, and stores the schema key of that type with the value.**: A reader that finds another schema key, or a key of an older kind version, treats it as a miss, reads the source and writes the value under the current key. This is the rule of T6. The schema key is the first 16 hex characters of the sha256 of the JSON schema of the type, as `LISTING_SCHEMA_KEY` already does for the snapshot. +- **A value over 1 MiB stays in the in-process tier.**: The mapping measures the encoded value before it sends it. Over the bound, it sends no command, keeps the value in memory and counts `devops_cli_brain_writes_total{result="oversize"}`. ADR 0023 section 2 says that a value over 1 MiB stays local. `cachetools.cached` ignores a `ValueError` on a write, so the mapping does not raise one. +- **Each key has a TTL.**: Each write of the mapping sends `SET ... EX `, and each write of the snapshot store ends with `EXPIRE` in the same MULTI/EXEC. The facts get 24 hours (`DEFAULT_BRAIN_FACT_TTL_SECONDS`) and the snapshot 7 days (`DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS`). A temporary key of a full write gets 600 s, so a killed writer leaves no key without an end. +- **`ValkeySnapshotStore` is the Valkey implementation of the `SnapshotStore` protocol.**: The protocol of #4552 is the seam that `IncrementalListing` reads, so no caller changes. `FileSnapshotStore` keeps one JSON file and cannot hold a shared copy. The hash `valkey:roadmap:v1:snapshot:/` holds the field `meta` (`schema`, `full_at`, `watermark`) and one zlib JSON `IssueRecord` for each issue number. One field for each record keeps each value under the bound: the snapshot of devops-cli is 14.13 MB with zlib, and its largest record is 23,700 B with zlib. +- **`TieredSnapshotStore` combines the local and the shared store.**: ADR 0023 section 2 says that a reader loads the local and the shared copy, drops a copy with another schema or a full read older than 24 hours, and takes the copy with the newer watermark. The rule needs both copies at one place, so it is a store of its own and not a change of `IncrementalListing`. A save writes the shared tier first and then the local file, the order of ADR 0023 section 2. +- **The newest watermark wins.**: A writer WATCHes the snapshot key, reads `meta`, and writes in one MULTI/EXEC only when its watermark is not older than the stored one, or when the stored copy has another schema. An EXEC that another client made fail writes nothing, and the writer does not retry: the other writer is newer or equal. This is the safe stop of ADR 0023 section 4. +- **A save writes only the changed fields when it can, and a full write goes through a temporary key and RENAME.**: The store keeps a digest of each record that it loaded from or wrote to the shared tier in this process. When the stored `meta` is the `meta` that the store last saw, it sends `HSET` for the changed records, `HDEL` for the removed ones and the new `meta`. In every other case (a full read, no shared copy in this process, or a changed `meta`) it writes all records to `:next:` in pipelined batches and then, under the WATCH of the snapshot key, RENAMEs the temporary key onto it and sets its TTL. A full read so removes each issue that left the repository. +- **A load reads `meta` first, then the records with `HSCAN COUNT 500`, within a budget of 20 s.**: The budget (`DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`) is checked between two scans. Past it, the load is a miss: the reader takes the local copy or reads GitHub, and the store counts `devops_cli_valkey_cache_errors_total{op="hscan",error="budget"}`. Each command keeps the 2 s bound of `valkey.timeout`, which is shorter than the budget, as ADR 0023 section 2 asks. The values come back as bytes through `NEVER_DECODE`. +- **The shared tier holds data of public repositories only.**: ADR 0023 section 8 keeps a private repository in the local tier until `valkey-devops` has role ACL users (#4704). `TieredSnapshotStore` asks a visibility check before it uses the shared tier for a repository. The check reads `isPrivate` through the GraphQL query of `is_private_args`, once for each repository and process in each hour (`DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS`). A failed read counts as private and is not kept. The store reads the visibility only after the shared tier answered the read of `meta`, so a run with no reachable Valkey, such as a workstation, sends no visibility read. For a private repository the store drops what that read gave, reads no record, writes no key and counts `result="private"`. +- **The fact cache reads public sources only.**: PyPI and deps.dev answer the same text to each client. The key is `valkey:brain:v1:fact:pypi:` with the name in the canonical form of `packaging.utils.canonicalize_name` (ADR 0023 section 6), and `valkey:brain:v1:fact:deps-dev:` with the deps.dev project key in lower case. An answer of "no such package" is a fact too, with the same TTL. A failed read raises as before and keeps nothing. +- **The tier commands that this item needs go into `ValkeyClient` and `ValkeyCacheTier`.**: `hget`, `hset`, `hdel`, `hscan`, `expire`, `unlink`, `rename` and `watch_and_write`. The tier keeps one client, one pool and one breaker for each process, so the new stores share the cooldown of the embeddings and the threat-intel caches: while Valkey is down, the process makes one connection attempt in each cooldown. +- **The read of a binary value uses `NEVER_DECODE`.**: The pool of `ValkeyClient` decodes each reply as UTF-8 with `encoding_errors="replace"`, which spoils zlib bytes. valkey-py gives the per-command option `NEVER_DECODE`, and fakeredis 2.40.0 honours it. A write of bytes needs no option, because the encoder sends bytes as they are. +- **Four counters, each with bounded labels.**: `devops_cli_brain_reads_total{store,result}` with `store` in `snapshot`, `fact` and `result` in `memory`, `shared`, `source`, `fallback`, `private`. `devops_cli_brain_writes_total{store,result}` with `result` in `shared`, `skipped`, `oversize`, `older`, `private`. `devops_cli_valkey_cache_errors_total{op,error}` with `op` the command and `error` in `timeout`, `connection`, `auth`, `reply`, `open`, `budget`. `devops_cli_brain_github_requests_saved_total{store}` with `store` in `snapshot`: a load that takes the shared copy when the local copy is missing or unfit adds the page count of the full read that it saves (the record count over `DEFAULT_GH_REST_PER_PAGE`, rounded up). The body names three counters. The fourth counts the skipped writes that the body asks to count ("each write is skipped and counted"). +- **The error counter has no label `instance`.**: The collector sets the labels `job` and `instance` from the resource after it copies the attributes, so an attribute `instance` never reaches Prometheus, and `test_no_emit_sends_an_attribute_that_the_resource_sets` (`tests/telemetry/test_telemetry_instruments.py:480`, #3240) refuses an `emit` that sends one. Each process has one cache tier, so the label would hold one value. +- **The load time of the shared snapshot is measured against a temporary Valkey pod.**: The build starts a hardened pod of `valkey/valkey:9.1.4-alpine` (the image tag of the live `valkey-devops`) in namespace `llm`, with `activeDeadlineSeconds`, forwards a loopback port to it, writes the 6,571 records of the local devops-cli snapshot through `ValkeySnapshotStore`, and times a cold load. Then it deletes the pod and stops the port-forward. It never reads or writes the live `valkey-devops`. The same pod records the new contract scenarios. +- **The live drill waits for the release.**: The drill (`valkey-devops` at 0 replicas for 10 minutes; no job fails; the share of `result="fallback"` shows in Prometheus) needs the merged code in the cluster. The pull request body names it as the live check after the release, and `tasks.md` names it as a check for a person. + +## Rejected alternatives + +- **The bound 240mb inside 320Mi (the refined design of #4668).**: It breaks the owner decision 6 of #4624, which sets 256 MB. +- **The bound 256mb inside 320Mi (#4624 item 6).**: 256 MiB is 80 % of 320Mi, over the three-quarters rule of `openspec/specs/llm-valkey/spec.md:20`. +- **Keep 96mb inside 128Mi.**: The old pod peaked at 95.97 MiB and evicted 3,600 keys in 7 days before this item adds about 15 MB of snapshots. +- **Edit line 134 of ADR 0023.**: `docs/adr/README.md` ("An accepted record does not change") forbids it, and the body hash test fails on it. +- **One JSON value for the whole snapshot.**: 14.13 MB with zlib, over the bound of 1 MiB. +- **One key for each issue.**: A load of 6,571 keys costs 6,571 commands or one MGET of 6,571 keys with no TTL for the set, and a full read cannot remove a gone issue in one step. A hash reads 500 fields in each `HSCAN` and renames as one key. +- **Base64 text in place of bytes.**: It adds a third to each value (14.13 MB to about 18.8 MB) and to each load. `NEVER_DECODE` gives the bytes with no second pool. +- **A second connection pool with `decode_responses=False`.**: It doubles the connections and splits the breaker of the process. +- **`Valkey.transaction()` of valkey-py.**: It retries on `WatchError`. An older writer must lose, not retry. +- **A Lua script for the watermark check.**: ADR 0023 section 4 names WATCH, MULTI/EXEC and RENAME, and a script would carry the 14 MB of a full write as its arguments. +- **A `SET NX` lock key for the writer.**: A killed pod leaves the lock, and its TTL can end while a writer holds it. +- **The last writer wins.**: A pod that started earlier can write over a newer snapshot and lose issues. +- **Change `IncrementalListing` to read two stores.**: The protocol of #4552 already isolates the place of the snapshot. A store that implements it keeps every caller and the tests of `IncrementalListing` as they are. +- **Replace `FileSnapshotStore`.**: The local tier is the fallback when Valkey is down, and a workstation has the local tier only. +- **hishel as the cache of the GitHub answers.**: It is a shared cache by default, and the GitHub answers are private with `Vary: Authorization` (ADR 0023, Considered Options). +- **Page ETags for the listing.**: Each new issue changes the ETag of every page (#4552). +- **Search and page caches on the mapping in this item.**: SearXNG (`search.searxng_url`) and Crawl4AI (`crawl4ai.url`) run in the cluster and count no request against a quota, and `DEFAULT_SEARCH_PROVIDERS` asks SearXNG first. #4672 records that SearXNG carries the check and that Firecrawl answered 0 searches in 7 days. A shared cache of their answers saves no counted request. +- **Caches of GitHub answers (the SBOM of the inventory, the ADR index, the repository facts) on the mapping.**: ADR 0023 section 2 keeps the stored GitHub answers in the process until the two-token probe of ADR 0021 section 6 passes. The conditional item of #4624 holds them. +- **A per-process LRU only for the facts.**: Each release restarts the Service, and each Job is a new process, so an LRU alone is cold at each start. +- **The label `instance` on `devops_cli_valkey_cache_errors_total`.**: The collector replaces it with the label of the resource, and the test of #3240 refuses it, as the decision above says. + +## Unchanged references + +- `src/devops_cli/commands/roadmap.py` (`intake_listing(full=full)`): The factory keeps its signature and gives the tiered store. +- `src/devops_cli/roadmap/run.py` (`intake_listing(state_dir)`, `lane_listing(state_dir, lane)`): The factories keep their signatures. Each lane keeps its own local file, and the lanes of one repository share one shared copy under the newest-watermark rule. +- `src/devops_cli/server/routes/webhooks.py` (`intake_listing(state_dir)`): The scoped intake keeps its call. +- `src/devops_cli/roadmap/stores/github_store.py` (`IncrementalListing.read`): The store keeps its call of `read(repo, read_issues)`. +- `src/devops_cli/ai/rag/embeddings.py`, `src/devops_cli/ai/rag/library_store.py`, `src/devops_cli/security/vulnerability_lookup.py` (`ValkeyCacheTier.get`, `set`): They keep the two methods that they use, and share the breaker with the new commands. + +## Security + +The shared tier gets the listing records of public repositories and the facts of public packages. Each client of `valkey-devops` uses one password and the default user until #4704 adds the role ACL users. So the store writes no key of a private repository and never uses a shared copy of one: it reads only the `meta` field of the key before the visibility check, and drops it. A failed visibility read counts as private. `test_no_key_of_a_private_repository_is_written` fails if this guard widens. The keys hold the repository name and the package name, never a token, a body of a private issue or a hostname. The values that a reader loads are untrusted: each one goes through the pydantic model of its type, and a value that does not parse is a miss. A person must confirm that the visibility check fails closed and that the store sends no write and no record read for a private repository. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md new file mode 100644 index 0000000000..02bf519d3e --- /dev/null +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md @@ -0,0 +1,72 @@ +# Proposal: #4668 + +## Why + +#4668 shares the listing snapshot of #4552 and the tool facts of the alternatives check in the cache Valkey `valkey-devops`, behind the circuit breaker of the cache tier. ADR 0023 section 2 sets the two tiers, and tracker #4624 lists the item as child 7. + +- Each process that reads the listing with no local snapshot reads the full listing: 66 pages of 100 for the 6,571 issues and pull requests of devops-cli. The intake pods of #4567 start with an empty home, so each pod pays this read. A shared snapshot gives a cold process the newest copy, and the process then reads only the changes since its watermark. +- `_read_pypi` (`src/devops_cli/roadmap/alternatives.py:298`) opens a new HTTP client for each read and keeps no answer. `_linked_packages` (`src/devops_cli/roadmap/inventory.py:186`) does the same for deps.dev. The same tools come back on many items, and each release of the Service starts a new process with no fact in memory. + +## What Changes + +- `src/devops_cli/valkey/client.py`: `ValkeyClient` gets the hash commands `hget`, `hset`, `hdel` and `hscan`, and `expire`, `unlink` and `rename`. A read of a binary value uses the `NEVER_DECODE` option of valkey-py, so a zlib value comes back as bytes. A new method `watch_and_write` runs one WATCH, a check of the current value, and one MULTI/EXEC, and it says when another client changed the key first. It does not retry. +- `src/devops_cli/valkey/cache.py`: `ValkeyCacheTier` gets the same commands behind its circuit breaker. A command that fails, or that the open breaker does not send, is a miss or a skipped write, and the tier counts it in `devops_cli_valkey_cache_errors_total`. +- `src/devops_cli/valkey/tiered.py` (new): `TieredMapping`, a `MutableMapping` over an in-process `cachetools.TTLCache` and the shared `ValkeyCacheTier`. It has a key prefix, a value codec (JSON, or JSON and zlib) over a pydantic `TypeAdapter`, a TTL for each key, a bound of 1 MiB for each value, and the read and write counters. A read from the shared tier fills the in-process tier. A value of another schema is a miss. +- `src/devops_cli/roadmap/stores/listing_shared.py` (new): `ValkeySnapshotStore` and `TieredSnapshotStore` behind the `SnapshotStore` protocol. The snapshot of a repository is one hash, `valkey:roadmap:v1:snapshot:/`, with the field `meta` and one zlib JSON `IssueRecord` for each issue, and a TTL of 7 days. A load reads the hash with `HSCAN COUNT 500` within a budget of 20 s. A writer writes only when its watermark is not older than the stored one, in one WATCH and MULTI/EXEC. A full read writes a temporary key and RENAMEs it. The store uses the shared copy and writes a key only for a public repository. +- `src/devops_cli/roadmap/stores/listing_snapshot.py`: `intake_listing` and `lane_listing` give `IncrementalListing` a `TieredSnapshotStore` over the `FileSnapshotStore` of today and the shared tier of the process. The callers of the two factories do not change. +- `src/devops_cli/roadmap/alternatives.py` and `src/devops_cli/roadmap/inventory.py`: the PyPI and deps.dev reads go through one fact `TieredMapping`, `valkey:brain:v1:fact::`, with a TTL of 24 hours. A miss reads the source. +- `src/devops_cli/telemetry/instruments.py`: four counters with bounded labels: `devops_cli_brain_reads_total{store,result}`, `devops_cli_brain_writes_total{store,result}`, `devops_cli_valkey_cache_errors_total{op,error}` and `devops_cli_brain_github_requests_saved_total{store}`. +- `src/devops_cli/config/defaults.py` and `src/devops_cli/config/constants.py`: the TTLs, the load budget, the value bound, the HSCAN count, the size of the in-process tier, the key prefixes and the label values. +- `k8s/llm/valkey-devops.yaml`: `--maxmemory 256mb` in place of `96mb`, and a container limit of `384Mi` in place of `128Mi`. 256 MiB is two thirds of 384Mi, so the rule of `openspec/specs/llm-valkey/spec.md` (at most three quarters of the limit) holds, and so does the owner decision 6 of #4624 (256 MB). +- The contract suite of #4557 gets scenarios for WATCH with a lost transaction, `HSCAN` of binary values, `RENAME` of a hash with a TTL, `EXPIRE` and `UNLINK`, recorded from a real `valkey-server` of the image of `valkey-devops`. +- Documents: `k8s/README.md` (the memory bound and the new keys of `valkey-devops`), `docs/roadmap/intake.md` (the shared copy of the snapshot), `docs/roadmap/alternatives.md` (the fact cache) and the generated `docs/TELEMETRY.md`. +- The change adds service behavior that a consumer observes (the keys, the counters, the fallback and the memory bound), so it has a spec delta: the new nested capability `project-brain/shared-cache`, as ADR 0023 requires for each item of #4624. +- The change fits one pull request. + +Out of scope, with the reason: + +- The search and page caches that the body lists: the searches go to SearXNG and the pages to Crawl4AI, which run in the cluster and count no request against a quota. #4672 says that SearXNG carries the check and that Firecrawl answered 0 searches in 7 days. +- The GitHub answers (the SBOM of the inventory, the ADR index, the repository facts): ADR 0023 section 2 keeps the stored GitHub answers in the process. The conditional item of #4624 ("share stored GitHub answers through Valkey") holds them until the two-token probe of ADR 0021 section 6 passes. +- The live drill (`valkey-devops` at 0 replicas for 10 minutes) needs the merged code in the cluster. It is a check for a person after the release. + +## Capabilities + +### New Capabilities + +- `project-brain/shared-cache`: the shared tier of the listing snapshot and the tool facts in `valkey-devops`: the read path, the fallback, the newest watermark, the value bound and the TTL, the key kinds, the private repositories, the load budget, the counters and the memory bound. + +### Modified Capabilities + +None. + +## Impact + +- Code: `src/devops_cli/valkey/client.py`, `src/devops_cli/valkey/cache.py`, `src/devops_cli/valkey/tiered.py`, `src/devops_cli/roadmap/stores/listing_shared.py`, `src/devops_cli/roadmap/stores/listing_snapshot.py`, `src/devops_cli/roadmap/alternatives.py`, `src/devops_cli/roadmap/inventory.py`, `src/devops_cli/telemetry/instruments.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/config/constants.py` +- Manifests: `k8s/llm/valkey-devops.yaml` +- Documents: `k8s/README.md`, `docs/roadmap/intake.md`, `docs/roadmap/alternatives.md`, `docs/TELEMETRY.md` +- Tests: `tests/valkey/test_tiered.py`, `tests/valkey/test_valkey_cache_tier.py`, `tests/valkey/test_valkey_contract.py`, `tests/support/valkey_scenarios.py`, `tests/fixtures/valkey/recorded_exchanges.json`, `tests/support/fakes/valkey.py`, `tests/roadmap/stores/test_listing_shared.py`, `tests/roadmap/test_roadmap_alternatives.py`, `tests/roadmap/test_roadmap_alternatives_project_facts.py`, `tests/conftest.py` +- Runtime: about 15 MB more data in `valkey-devops` for the public repositories, and 256 MiB more memory limit for its container. A workstation with no reachable Valkey makes one connection attempt of at most 0.25 s for each cooldown of 60 s. + +## Feasibility + +Each premise was checked on 2026-11-21 against `origin/main` at ddad1a45e and the live systems: + +- The seam exists: `git grep -n "class SnapshotStore" origin/main -- src` gives `src/devops_cli/roadmap/stores/listing_snapshot.py:88`, with `FileSnapshotStore` at `:102` and `IncrementalListing` at `:161`. `IncrementalListing` calls only `load` and `save`. +- `ValkeyCacheTier` exists at `src/devops_cli/valkey/cache.py:70`. It offers `get` and `set` only, behind pybreaker (`fail_max=1`, a cooldown of 60 s, `ValkeyCommandError` excluded). `shared_cache_tier()` gives one tier for each process with a connect timeout of 0.25 s and the command timeout `valkey.timeout` (2 s, `src/devops_cli/config/defaults.py:723`). +- `ValkeyClient` builds its pool with `decode_responses=True` and `encoding_errors="replace"` (`src/devops_cli/valkey/client.py:196`), which would spoil a zlib value. valkey-py 6.2.0 has the per-command option `NEVER_DECODE` (`valkey/client.py:58`). A probe through fakeredis 2.40.0 gave `HSCAN k 0 COUNT 500` with `NEVER_DECODE` as `[b'0', [b'f', b'x\x9c...']]`, and `zlib.decompress` read the value back. +- #3670 and #4557 are closed as completed. #4552 is closed. #4704 (role ACL users of `valkey-devops`) is open. +- `_read_pypi` still opens `http_client(EgressLevel.PUBLIC)` for each read (`src/devops_cli/roadmap/alternatives.py:302`). +- No pull request names 4668 (`search/issues?q=repo:dan-petty/devops-cli+is:pr+4668` gives none), and no Job of the `devops` namespace names 4668. +- Visibility: `repos/dan-petty/devops-cli` gives `private=false`. Of the 8 repositories of `service.repos` in the live ConfigMap `devops-cli-config`, `homelab` and `danielpetty.com` are private. The other 6 are public. So the shared snapshot applies to devops-cli, and the store keeps the 2 private repositories in the local tier. +- The size of the snapshot, measured in the body on 2026-11-11: 4,615 records, 23.31 MB raw and 9.21 MB with zlib, p99 28,340 B and max 65,177 B for one record. Measured again on 2026-11-21 from the local snapshot of devops-cli (full read at 2026-11-20T22:13Z): 6,571 records, 37.54 MB raw, 14.13 MB with zlib for each record apart, p99 29,598 B and max 65,177 B raw, and max 23,700 B with zlib. Each record is far under the bound of 1 MiB, and the whole snapshot is over it, so the snapshot needs one field for each record. +- The memory of `valkey-devops`, from the owner comment of 2026-11-19: `redis_config_maxmemory{job="valkey-devops"}` is 100,663,296 (96 MiB). The old pod peaked at 95.97 MiB and evicted 3,600 keys in 7 days, with a hit ratio of 98.9 %. The new pod held 40.9 MiB in 2,871 keys with 0 evictions. The live Deployment runs `valkey/valkey:9.1.4-alpine` with a 128Mi limit. The snapshots of the 6 public repositories add about 15 MB, so 256 MiB keeps the embeddings, the snapshots and the facts with room to spare. +- The value of the shared snapshot comes with #4567, which is open. Today the Service runs intake in its own pod and keeps the snapshots on the volume `roadmap-service-home`, a PersistentVolumeClaim (`k8s/devops/roadmap-service/deployment.yaml:210`), so its rounds already read only the changes. The intake pods of #4567 start with no snapshot. The fact caches give value at once: the Service restarts at each release, and each restart empties the memory of the process. +- The load time of the shared devops-cli snapshot is measured in the build against a temporary Valkey pod of `valkey/valkey:9.1.4-alpine`, never against the live `valkey-devops`. The result and its command go into the pull request. + +## Existing Tool Considered + +- valkey-py 6.2.0 (in `uv.lock`) gives the client, the hash commands, `NEVER_DECODE` and the WATCH pipeline. pybreaker 1.4.1 gives the circuit breaker, which `ValkeyCacheTier` already wraps. cachetools 8.0.2 gives the in-process `TTLCache` and the `cached` decorator, which accepts any `MutableMapping` as its cache. The change uses each of them and adds no dependency. +- The `SnapshotStore` protocol of #4552 is the seam: the two new stores implement it, and `IncrementalListing` and its callers do not change. +- No tool gives a mapping over an LRU and a Valkey tier with a breaker, a codec, a value bound and a schema check, or a snapshot store with a watermark guard. hishel is rejected: it is a shared cache by default, and the GitHub answers are private with `Vary: Authorization`. Page ETags are rejected for the listing: each new issue changes the ETag of every page (#4552). +- The change builds about 450 lines of code (the mapping, the two stores and the tier commands) and about 600 lines of tests. Cost, from the body: about 220,000 tokens and 6 hours to build. It keeps about 5,000 tokens a month and about 30,000 tokens for each fix. +- Internal code that the change deletes: none. `FileSnapshotStore` stays as the local tier. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md new file mode 100644 index 0000000000..ff9e3c1dd7 --- /dev/null +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md @@ -0,0 +1,116 @@ +## Purpose +The shared tier of the project brain in the cache Valkey `valkey-devops` (ADR 0023 section 2): the listing snapshot of each public repository and the tool facts that the alternatives check reads, over the in-process tier, with a fallback to the local tier or the source when Valkey is slow or down, and the memory bound of the cache Valkey that holds them. + +## ADDED Requirements + +### Requirement: A cold process reads the shared listing snapshot +When a process has no local snapshot of a public repository and the shared tier holds a fit snapshot of it, the listing read SHALL start from the shared snapshot and read only the issues changed since its watermark, and SHALL count the full read that it saved in `devops_cli_brain_github_requests_saved_total{store="snapshot"}`. + +#### Scenario: Warm shared snapshot, cold process +- **WHEN** a test saves a snapshot of 250 issues of a public repository through one `TieredSnapshotStore` on the `valkey_server` fake, and a new `TieredSnapshotStore` with an empty local directory reads the listing of that repository through `IncrementalListing` while GitHub lists 3 issues as changed +- **THEN** the read sends at most 2 listing requests, each with `since=`, it returns 250 issues with the new title of each changed issue, the local file holds the new snapshot, and `devops_cli_brain_github_requests_saved_total{store="snapshot"}` rises by 3 + +#### Scenario: The newer of the two copies +- **WHEN** the local file holds a snapshot with the watermark 09:00 and the shared tier holds one with the watermark 10:00, both with the current schema key and a full read of less than 24 hours +- **THEN** the listing read sends `since=` with the watermark 10:00 + +### Requirement: A read of the shared tier fills the in-process tier +A `TieredMapping` read that misses the in-process tier and hits the shared tier SHALL put the value in the in-process tier, and the next read of the key SHALL send no command to Valkey. + +#### Scenario: T1 read fills the in-process tier +- **WHEN** one `TieredMapping` writes a fact on the `valkey_server` fake, and a second `TieredMapping` with an empty in-process tier reads the key twice +- **THEN** both reads return the fact, the fake receives one read command for the key, and `devops_cli_brain_reads_total{store="fact"}` counts one `shared` and one `memory` + +### Requirement: The tiers fall back while the shared tier is down +While the shared tier fails or its breaker is open, a read SHALL return the value of the in-process tier, the local tier or the source, a write SHALL stay in the in-process tier or the local file, and the counters SHALL count `fallback` and `skipped`. After one failed command the process SHALL send no command to Valkey until the cooldown of 60 s ends. + +#### Scenario: T2 disconnected tier +- **WHEN** the `valkey_server` fake has `connected = False` and a listing round and two fact reads run within one cooldown +- **THEN** the round returns the issues that GitHub lists, the local file holds the new snapshot, each fact read returns the source value, the fake receives no second command after the first failure, `devops_cli_brain_reads_total{result="fallback"}` and `devops_cli_brain_writes_total{result="skipped"}` rise, and no error reaches the caller + +#### Scenario: T3 silent shared tier +- **WHEN** the shared tier is a loopback listener that accepts the connection and answers no command, and `valkey.timeout` is 0.05 s +- **THEN** the tier's client has a connect timeout of at most 0.25 s, the first read ends with `devops_cli_valkey_cache_errors_total{error="timeout"}` and returns the source value, the breaker opens, and the next read sends nothing to the listener + +### Requirement: A trial after the cooldown and the newest watermark +After the cooldown the first command SHALL be a trial that closes the breaker when it succeeds. A writer of the shared snapshot SHALL write only when its watermark is not older than the stored watermark or the stored copy has another schema key, and a writer whose WATCH transaction another client made fail SHALL write nothing and SHALL NOT retry. + +#### Scenario: T4 trial, newer local copy and lost WATCH +- **WHEN** the breaker is open with a shared snapshot of watermark 09:00, the `clock` fixture passes the cooldown, a process saves a snapshot of watermark 10:00, and then a second writer with watermark 09:30 loses its WATCH transaction to a write of watermark 10:30 by another client +- **THEN** the trial closes the breaker, the shared snapshot has watermark 10:00 after the first save, the second writer's transaction writes nothing, the shared snapshot keeps watermark 10:30, and `devops_cli_brain_writes_total{result="older"}` rises by one + +#### Scenario: An older writer +- **WHEN** the shared snapshot has watermark 10:00 and a writer saves a snapshot with watermark 09:00 and the same schema key +- **THEN** the shared snapshot keeps watermark 10:00 and its records, and the local file holds the snapshot with watermark 09:00 + +### Requirement: A full read replaces the shared snapshot whole +A save of a snapshot whose last full read is newer than the stored one SHALL write the records to a temporary key with a TTL and RENAME it onto the snapshot key in one transaction, so the shared snapshot holds no issue that the full read did not list. + +#### Scenario: An issue left the repository +- **WHEN** the shared snapshot holds issues 1, 2 and 3, and a full read lists issues 1 and 3 +- **THEN** the shared snapshot holds issues 1 and 3 only, and no temporary key stays + +### Requirement: Each value has a bound and each key a TTL +The shared tier SHALL NOT receive a value whose encoded form is over 1 MiB; such a value SHALL stay in the in-process tier and count `devops_cli_brain_writes_total{result="oversize"}`. Each key that the mapping or the snapshot store writes SHALL have a TTL: 24 hours for a fact and 7 days for a snapshot. + +#### Scenario: T5 oversize value +- **WHEN** a `TieredMapping` stores a value whose encoded form is 1 MiB and one byte, and then a value of 1 KiB +- **THEN** no command carries the first value, a read in the same process returns it from the in-process tier, the shared tier holds the second value, and each key on the `valkey_server` fake has a TTL above 0 + +### Requirement: A value of another kind or schema is a miss +A reader SHALL treat a shared value under an older key version, or with another schema key, as a miss, SHALL read the source, and SHALL write the value under the current key. + +#### Scenario: T6 old kind +- **WHEN** the shared tier holds a PyPI fact under an older key version and a fact under the current key with another schema key +- **THEN** each read returns the value of the source, and the shared tier then holds the source value under the current key with the current schema key + +### Requirement: No key of a private repository +The snapshot store SHALL write no key of a repository that the visibility check does not give as public, SHALL NOT use a shared copy of it, and SHALL count `result="private"`. A failed visibility read SHALL count as private. + +#### Scenario: Private repository +- **WHEN** a listing round runs for a repository whose visibility read gives `isPrivate: true`, and a second round runs for a repository whose visibility read fails +- **THEN** the `valkey_server` fake holds no key that names either repository, each round reads the local file or GitHub, and `devops_cli_brain_writes_total{store="snapshot",result="private"}` rises by two + +#### Scenario: No visibility read without the shared tier +- **WHEN** the `valkey_server` fake has `connected = False` and a listing round runs +- **THEN** the round sends no visibility read to GitHub + +### Requirement: A shared load has a budget +A load of a shared snapshot SHALL stop when it passes `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS` (20 s), SHALL count `devops_cli_valkey_cache_errors_total{op="hscan",error="budget"}`, and the reader SHALL take the local copy or read GitHub. + +#### Scenario: Slow shared tier +- **WHEN** the `clock` fixture moves 21 s during the second `HSCAN` of a shared load of 1,200 records +- **THEN** the load sends no third `HSCAN`, the reader returns the local snapshot, and the budget counter rises by one + +### Requirement: The tool facts come from the shared cache +A second read of the same PyPI package or the same deps.dev project within the TTL SHALL come from the shared or the in-process tier and SHALL send no request to PyPI or deps.dev. A failed source read SHALL keep nothing. + +#### Scenario: PyPI fact reuse across processes +- **WHEN** two `pypi_package` calls for `Scanner` and `scanner` run with an empty in-process tier between them on one `valkey_server` fake +- **THEN** the `web` fake receives one request to PyPI, and both calls return the same facts + +#### Scenario: deps.dev fact reuse +- **WHEN** two inventory reads link the packages of `github.com/example/tool` with an empty in-process tier between them +- **THEN** the `web` fake receives one request to deps.dev + +#### Scenario: A failed PyPI read +- **WHEN** PyPI answers 503 for a package, and then 200 +- **THEN** the first call answers the failure as text, and the second call sends a request and returns the facts + +### Requirement: The brain counters have bounded labels +The counters `devops_cli_brain_reads_total`, `devops_cli_brain_writes_total`, `devops_cli_valkey_cache_errors_total` and `devops_cli_brain_github_requests_saved_total` SHALL take each label value from a fixed set in the source, and SHALL NOT hold a repository name, a key, an issue number or a package name. + +#### Scenario: The labels of a round +- **WHEN** a test runs a listing round and two fact reads on the OTLP fake, one with the shared tier up and one with it down +- **THEN** each exported data point of the four counters has only the labels `store`, `result`, `op` or `error`, each value is one of the fixed values, and no value names the repository or the package + +### Requirement: The cache Valkey keeps its data bound below its limit +The valkey container of the Deployment `valkey-devops` SHALL start valkey-server with `--maxmemory 256mb` under a container memory limit of `384Mi`, so its data bound is two thirds of its limit. + +#### Scenario: Manifest bound +- **WHEN** a person runs `uv run devops ci --check --only k8s` on the pull request +- **THEN** the `k8s` row renders `k8s/llm` with no error + +#### Scenario: Live memory bound +- **WHEN** a person runs `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].command}{.spec.template.spec.containers[0].resources.limits.memory}'` after the Argo CD sync, and reads `redis_config_maxmemory{job="valkey-devops"}` in Prometheus +- **THEN** the command holds `--maxmemory 256mb` and the limit is `384Mi`, and the metric is 268435456 diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md new file mode 100644 index 0000000000..a9a5488a1c --- /dev/null +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -0,0 +1,87 @@ +# Tasks + +## 1. Record the Valkey behavior that the shared tier needs in the contract suite + +Kind: other. Reads: `tests/support/valkey_scenarios.py`, `tests/support/valkey_recording.py`, `tests/support/valkey_replay.py`, `tests/valkey/test_valkey_contract.py`, `tests/fixtures/valkey/recorded_exchanges.json`. Changes: `tests/support/valkey_scenarios.py`, `tests/valkey/test_valkey_contract.py`, `tests/fixtures/valkey/recorded_exchanges.json`. + +- [ ] 1.1 Add the scenarios `watch_lost` (one client WATCHes a hash and reads a field, a second client writes the hash, and the first client's MULTI/EXEC raises `WatchError` and writes nothing), `hscan_bytes` (HSET of zlib bytes, then `HSCAN COUNT 500` with `NEVER_DECODE` gives the same bytes and the end cursor), `rename_hash_ttl` (a temporary hash with `EXPIRE 600` RENAMEd onto a hash that exists replaces it and keeps a TTL), and `expire_hdel_unlink` (`EXPIRE` sets a TTL, `HDEL` removes a field, `UNLINK` counts the removed keys) to `tests/support/valkey_scenarios.py`, each with its own key prefix and a delete of its keys at the end. Add their expected tuples to `EXPECTED` and the new commands to the "Covered" list of the docstring of `tests/valkey/test_valkey_contract.py` +- [ ] 1.2 Record the replies of a real server: start a temporary pod `valkey-contract-record` of the image that `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].image}'` gives (`valkey/valkey:9.1.4-alpine` on 2026-11-21) in namespace `llm` from the hardened pod spec of #4557 (non-root, read-only root, `activeDeadlineSeconds`, `--save ''`, `--appendonly no`), forward the loopback port 6390 to it, run `record_scenarios(6390)` of `tests/support/valkey_recording.py`, then stop the port-forward and delete the pod. Never forward to the live `valkey-devops` + - Verification: `$ uv run devops ci test tests/valkey/test_valkey_contract.py` passes, over the fake and over the record + +## 2. Give the cache tier the hash, TTL, rename and WATCH commands behind its breaker + +Kind: behavior. Reads: `src/devops_cli/valkey/client.py`, `src/devops_cli/valkey/cache.py`, `src/devops_cli/telemetry/instruments.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/exceptions/valkey.py`, `tests/valkey/test_valkey_cache_tier.py`, `tests/support/fakes/valkey.py`, `tests/support/fakes/otlp.py`, `tests/telemetry/test_telemetry_instruments.py`. Changes: `src/devops_cli/valkey/client.py`, `src/devops_cli/valkey/cache.py`, `src/devops_cli/telemetry/instruments.py`, `src/devops_cli/config/constants.py`, `tests/valkey/test_valkey_cache_tier.py`, `tests/support/fakes/valkey.py`. +Adds: `ValkeyClient.hget`, `ValkeyClient.hset`, `ValkeyClient.hdel`, `ValkeyClient.hscan`, `ValkeyClient.expire`, `ValkeyClient.unlink`, `ValkeyClient.rename`, `ValkeyClient.watch_and_write`, the same eight methods on `ValkeyCacheTier`, `BRAIN_READS_TOTAL`, `BRAIN_WRITES_TOTAL`, `VALKEY_CACHE_ERRORS_TOTAL`, `BRAIN_GITHUB_REQUESTS_SAVED_TOTAL`, the `silent_valkey` fixture + +- [ ] 2.1 Write in `tests/valkey/test_valkey_cache_tier.py`: `test_the_cache_tier_keeps_a_binary_hash_with_a_ttl` (HSET of zlib bytes, HSCAN gives the same bytes, EXPIRE gives a TTL above 0, HDEL, RENAME and UNLINK, on the `valkey_server` fake); `test_a_writer_whose_watched_key_changed_writes_nothing` (two clients on one fake; `watch_and_write` returns False and the hash keeps the other client's value); `test_a_failed_tier_command_counts_its_command_and_error` (with `connected = False` on the OTLP fake, the first HSCAN adds `devops_cli_valkey_cache_errors_total{op="hscan",error="connection"}`, and an HSET in the cooldown adds `error="open"` and sends nothing); and `test_a_silent_valkey_times_out_and_opens_the_breaker` for the scenario `T3 silent shared tier`: add the fixture `silent_valkey` to `tests/support/fakes/valkey.py`, a loopback listener that accepts and never answers, set `DEVOPS_CLI_VALKEY_TIMEOUT=0.05`, and assert the connect timeout of at most 0.25 s, the counted `timeout`, the open breaker and no second connection to the listener, with no bound on the elapsed time + - Verification: `$ uv run devops ci test tests/valkey/test_valkey_cache_tier.py` fails on the base +- [ ] 2.2 Add the eight commands to `ValkeyClient` in `src/devops_cli/valkey/client.py`. `hget` of a value and `hscan` send `NEVER_DECODE` and return bytes. `watch_and_write(key, decide)` runs WATCH, gives `decide` the reply of `HGET key meta`, sends the commands that `decide` returns in one MULTI/EXEC, and returns False with no retry on `WatchError` or when `decide` returns nothing. Add the same methods to `ValkeyCacheTier` in `src/devops_cli/valkey/cache.py` through `_send`, and make `_send` add one `VALKEY_CACHE_ERRORS_TOTAL` for each failed command and each command that the open breaker does not send, with `op` the command and `error` one of `timeout`, `connection`, `auth`, `reply`, `open`. Declare the four counters in `src/devops_cli/telemetry/instruments.py`, add them to `INSTRUMENTS` and `__all__`, and put their label values in `src/devops_cli/config/constants.py` + - Verification: `$ uv run devops ci test tests/valkey/test_valkey_cache_tier.py tests/telemetry/test_telemetry_instruments.py` passes + +## 3. Add the tiered mapping over the in-process tier and the shared tier + +Kind: behavior. Reads: `src/devops_cli/valkey/cache.py`, `src/devops_cli/core/clock.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/telemetry/instruments.py`, `tests/conftest.py`, `tests/support/fakes/valkey.py`, `tests/support/fakes/otlp.py`. Changes: `src/devops_cli/valkey/tiered.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/config/constants.py`, `tests/valkey/test_tiered.py`, `tests/conftest.py`. +Adds: `TieredMapping`, `reset_tiered_mappings`, `DEFAULT_BRAIN_VALUE_MAX_BYTES`, `DEFAULT_BRAIN_MEMORY_ENTRIES`, `DEFAULT_BRAIN_FACT_TTL_SECONDS` + +- [ ] 3.1 Write `tests/valkey/test_tiered.py`: `test_a_shared_read_fills_the_memory_tier` (T1); `test_a_down_shared_tier_gives_the_source_value_and_keeps_the_write_in_memory` (T2: `connected = False`, two reads through `cachetools.cached` within one cooldown, one command reaches the fake, `result="fallback"` and `result="skipped"` counted); `test_an_oversize_value_stays_in_memory_and_each_key_has_a_ttl` (T5: an encoded value of 1 MiB and one byte sends no command, and each key on the fake has a TTL above 0); `test_a_value_of_an_old_kind_or_schema_is_read_from_the_source` (T6); and `test_the_brain_counters_send_only_fixed_labels` for the requirement `The brain counters have bounded labels`, on the OTLP fake + - Verification: `$ uv run devops ci test tests/valkey/test_tiered.py` fails on the base +- [ ] 3.2 Add `TieredMapping` to the new `src/devops_cli/valkey/tiered.py`: a `MutableMapping` with a key prefix, a pydantic `TypeAdapter` of its value type, a codec (`json` or `json+zlib`), a TTL, an in-process `cachetools.TTLCache` of `DEFAULT_BRAIN_MEMORY_ENTRIES`, and the tier of `shared_cache_tier()`, built on first use. Each value in Valkey holds the schema key of its type (the first 16 hex characters of the sha256 of its JSON schema); another schema key is a miss. A read counts `BRAIN_READS_TOTAL` and a write `BRAIN_WRITES_TOTAL`; a value over `DEFAULT_BRAIN_VALUE_MAX_BYTES` (1 MiB) stays in memory and counts `oversize`. `__iter__` and `__len__` cover the in-process tier. Each mapping joins a registry that `reset_tiered_mappings` clears, and `tests/conftest.py` adds `"devops_cli.valkey.tiered": ("reset_tiered_mappings",)` to `_PROCESS_STATE_RESETS`. Add the defaults and the key prefixes `valkey:brain:v1` and `valkey:roadmap:v1` + - Verification: `$ uv run devops ci test tests/valkey/test_tiered.py` passes + +## 4. Share the listing snapshot through the shared tier + +Kind: behavior. Reads: `src/devops_cli/roadmap/stores/listing_snapshot.py`, `src/devops_cli/roadmap/stores/github_store.py`, `src/devops_cli/roadmap/stores/store.py`, `src/devops_cli/valkey/cache.py`, `src/devops_cli/valkey/tiered.py`, `src/devops_cli/core/clock.py`, `src/devops_cli/commands/roadmap.py`, `src/devops_cli/roadmap/run.py`, `src/devops_cli/server/routes/webhooks.py`, `tests/roadmap/stores/test_listing_snapshot.py`, `tests/roadmap/stores/test_roadmap_store_install.py`, `tests/roadmap/test_roadmap_run_lanes.py`, `tests/roadmap/test_roadmap_run_scoped_update.py`, `tests/server/test_server_service.py`, `tests/conftest.py`. Changes: `src/devops_cli/roadmap/stores/listing_shared.py`, `src/devops_cli/roadmap/stores/listing_snapshot.py`, `src/devops_cli/config/defaults.py`, `tests/roadmap/stores/test_listing_shared.py`, `tests/conftest.py`. +Adds: `ValkeySnapshotStore`, `TieredSnapshotStore`, `repository_is_public`, `reset_repository_visibility`, `DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS`, `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`, `DEFAULT_BRAIN_SNAPSHOT_SCAN_COUNT`, `DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS` + +- [ ] 4.1 Write `tests/roadmap/stores/test_listing_shared.py` on the `valkey_server` fake, the `clock` fixture and a GitHub listing fake: `test_a_cold_process_reads_the_shared_snapshot_and_at_most_two_pages` (scenario `Warm shared snapshot, cold process`, with the saved-requests counter); `test_the_newer_copy_of_the_two_tiers_gives_the_watermark`; `test_a_round_with_the_shared_tier_down_reads_the_local_file` (T2 for the snapshot); `test_a_trial_after_the_cooldown_lets_the_newer_snapshot_replace_the_older` and `test_an_older_writer_loses_its_watch_transaction` (T4); `test_an_older_watermark_does_not_replace_the_shared_snapshot`; `test_a_full_read_replaces_the_shared_snapshot_whole`; `test_no_key_of_a_private_repository_is_written` (a private answer and a failed visibility read); `test_no_visibility_read_without_the_shared_tier`; and `test_a_shared_load_past_its_budget_falls_back` + - Verification: `$ uv run devops ci test tests/roadmap/stores/test_listing_shared.py` fails on the base +- [ ] 4.2 Add `ValkeySnapshotStore` and `TieredSnapshotStore` to the new `src/devops_cli/roadmap/stores/listing_shared.py`, each with `load` and `save` of the `SnapshotStore` protocol. The key is `valkey:roadmap:v1:snapshot:/`, a hash with `meta` (`schema`, `full_at`, `watermark`) and one zlib JSON `IssueRecord` for each issue number, with a TTL of `DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS` (7 days). A load reads `meta`, then the records with `HSCAN COUNT 500`, and stops at `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS` (20 s) on `devops_cli.core.clock.monotonic`. A save writes the changed fields under `watch_and_write` when the stored `meta` is the one that the store last saw, else all records to `:next:` with a TTL of 600 s and a RENAME under the WATCH; it writes only when its watermark is not older or the stored schema key differs. `TieredSnapshotStore` takes the fit copy with the newer watermark (the rule of ADR 0023 section 2), saves the shared tier first and then the local file, and uses the shared tier for a repository only when `repository_is_public` says so after the shared tier answered. `repository_is_public` reads `isPrivate` through `is_private_args` once for each repository and hour, keeps no failed read, and counts a failed read as private; `tests/conftest.py` adds `"devops_cli.roadmap.stores.listing_shared": ("reset_repository_visibility",)`. Make `intake_listing` and `lane_listing` in `src/devops_cli/roadmap/stores/listing_snapshot.py` give a `TieredSnapshotStore` over their `FileSnapshotStore` and `shared_cache_tier()`, and say so in the module docstring. The callers in `src/devops_cli/commands/roadmap.py`, `src/devops_cli/roadmap/run.py` and `src/devops_cli/server/routes/webhooks.py` do not change + - Verification: `$ uv run devops ci test tests/roadmap/stores/test_listing_shared.py tests/roadmap/stores/test_listing_snapshot.py tests/roadmap/stores/test_roadmap_store_install.py tests/roadmap/test_roadmap_run_lanes.py tests/roadmap/test_roadmap_run_scoped_update.py tests/server/test_server_service.py` passes + +## 5. Read the PyPI and deps.dev facts through the shared fact cache + +Kind: behavior. Reads: `src/devops_cli/roadmap/alternatives.py`, `src/devops_cli/roadmap/inventory.py`, `src/devops_cli/valkey/tiered.py`, `tests/roadmap/test_roadmap_alternatives.py`, `tests/roadmap/test_roadmap_alternatives_project_facts.py`, `tests/support/fakes/http.py`. Changes: `src/devops_cli/roadmap/alternatives.py`, `src/devops_cli/roadmap/inventory.py`, `tests/roadmap/test_roadmap_alternatives.py`, `tests/roadmap/test_roadmap_alternatives_project_facts.py`. + +- [ ] 5.1 Write `test_a_second_pypi_read_of_one_package_sends_no_request` (scenario `PyPI fact reuse across processes`: `Scanner` then `scanner`, with `reset_tiered_mappings` between them, one request on the `web` fake) and `test_a_failed_pypi_read_keeps_nothing` (503 then 200) in `tests/roadmap/test_roadmap_alternatives.py`, and `test_a_second_deps_dev_read_of_one_project_sends_no_request` in `tests/roadmap/test_roadmap_alternatives_project_facts.py`. Check each existing test of these two files that reads one package or project twice with two answers, and give it two names + - Verification: `$ uv run devops ci test tests/roadmap/test_roadmap_alternatives.py tests/roadmap/test_roadmap_alternatives_project_facts.py` fails on the base +- [ ] 5.2 Decorate `_read_pypi` in `src/devops_cli/roadmap/alternatives.py` with `cachetools.cached` over a `TieredMapping` of `_PyPIPackage | None` with the prefix `valkey:brain:v1:fact:pypi` and the key `packaging.utils.canonicalize_name(name)`, and `_linked_packages` in `src/devops_cli/roadmap/inventory.py` with a `TieredMapping` of `frozenset[str]` with the prefix `valkey:brain:v1:fact:deps-dev` and the project key in lower case, each with the TTL `DEFAULT_BRAIN_FACT_TTL_SECONDS` (24 hours). A raised read keeps nothing. Say in each docstring that the read goes through the fact cache + - Verification: `$ uv run devops ci test tests/roadmap/test_roadmap_alternatives.py tests/roadmap/test_roadmap_alternatives_project_facts.py` passes + +## 6. Raise the memory bound of valkey-devops + +Kind: other. Reads: `k8s/llm/valkey-devops.yaml`, `openspec/specs/llm-valkey/spec.md`. Changes: `k8s/llm/valkey-devops.yaml`. + +- [ ] 6.1 Set `--maxmemory 256mb` in place of `--maxmemory 96mb` and the memory limit of the valkey container to `384Mi` in place of `128Mi` in `k8s/llm/valkey-devops.yaml`. Change the comment above `command`: Valkey keeps at most 256 MiB of data, two thirds of the 384Mi limit, which keeps the three-quarters rule of the llm Valkeys (#711); the embeddings, the listing snapshots of the public repositories and the tool facts share the bound, and at the bound Valkey evicts the least recently used key. Change the header comment to name the snapshots and the facts beside the embeddings and the threat-intelligence reads + - Verification: `$ uv run devops ci --check --only k8s` passes + - Verification: `$ ! git grep -n -F 96mb k8s/llm/valkey-devops.yaml` passes + +## 7. Measure the shared load of the devops-cli snapshot + +Kind: other. Reads: `src/devops_cli/roadmap/stores/listing_shared.py`, `k8s/llm/valkey-devops.yaml`. Changes: none; the result goes into the pull request body. + +- [ ] 7.1 Start a temporary pod `valkey-snapshot-load` of the image that `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].image}'` gives (`valkey/valkey:9.1.4-alpine` on 2026-11-21) in namespace `llm` from the hardened pod spec of group 1, with `--maxmemory 256mb` and a memory limit of `384Mi`, and forward a loopback port to it. With a script under `.data/agent/scratch/`, read the local snapshot of devops-cli, save it through `ValkeySnapshotStore` on a client of that port, then time five cold loads with a new store each. Write the record count, the bytes in Valkey (`MEMORY USAGE` of the key) and the median and the maximum of the load times into the pull request body. Stop the port-forward and delete the pod. Never connect to the live `valkey-devops` + - Verification: each of the five loads ends under 20 s, and `kubectl -n llm get pod valkey-snapshot-load` finds no pod after the step + +## 8. Update the documents that the change makes wrong + +Kind: other. Reads: `k8s/README.md`, `docs/roadmap/intake.md`, `docs/roadmap/alternatives.md`, `docs/TELEMETRY.md`, `docs/SERVICE_PATTERNS.md`, `CONTEXT.md`, `ARCHITECTURE.md`, `src/devops_cli/ai/knowledge_base/it_domains/tools/valkey.md`. Changes: `k8s/README.md`, `docs/roadmap/intake.md`, `docs/roadmap/alternatives.md`, `docs/TELEMETRY.md`. + +- [ ] 8.1 In `k8s/README.md`, change the paragraph of `valkey-devops`: it holds the embeddings, the threat-intelligence reads, the listing snapshots of the public repositories and the tool facts, keeps at most 256 MiB of data, two thirds of its 384Mi limit, and holds no key of a private repository until #4704. In `docs/roadmap/intake.md`, say that the intake and the lanes keep their local file and share one copy of each public repository in `valkey-devops`, where the newest watermark wins, in place of "the seam for a store that the pods of the Service can share (#4517)". In `docs/roadmap/alternatives.md`, say that the PyPI and deps.dev facts come from the shared fact cache for 24 hours. Run `git grep -n -e 96mb -e "96 MiB" -e 128Mi -e SnapshotStore -e ValkeyCacheTier -- docs k8s/README.md CONTEXT.md ARCHITECTURE.md openspec/specs src/devops_cli/ai/knowledge_base`, and fix each other line that the change makes wrong; the ADRs are records and do not change + - Verification: `$ ! git grep -n -F "96 MiB" k8s/README.md` passes +- [ ] 8.2 Regenerate `docs/TELEMETRY.md` with `uv run devops docs generate` for the four new counters. Change no text of the page by hand + - Verification: `$ uv run devops ci docs` passes + +## Criteria + +- Group 4: A test: a cold process with a warm shared snapshot reads at most 2 listing pages. +- Groups 3 and 4: A test: with `connected = False`, a round reads the local tier or GitHub, counts `fallback`, and sends no second command in the 60 s cooldown. +- Group 3: A test: a value over 1 MiB is not sent. +- Group 4: A test: no key of a private repository is written. +- Group 7: The shared load time of the devops-cli snapshot is measured against a temporary Valkey pod and stays under 20 s. +- Group 6: `uv run devops ci --check --only k8s` passes with `--maxmemory 256mb` and the `384Mi` limit. + +## Workflow follow-up + +- Pending a person: after the Argo CD sync, `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].command}{.spec.template.spec.containers[0].resources.limits.memory}'` shows `--maxmemory 256mb` and `384Mi`, and `redis_config_maxmemory{job="valkey-devops"}` is 268435456. +- Pending a person: the live drill after the release: `valkey-devops` at 0 replicas for 10 minutes, through git or with the self-heal of its Argo CD application paused; no job fails, and `devops_cli_brain_reads_total{result="fallback"}` shows the share of the fallback reads in Prometheus. Then the Deployment goes back to 1 replica. +- Pending a person: review the diff in tuicr (tuicr -r ..HEAD). From 6b3503f96ec5855e24063ae71b7ab95e6533a0c0 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:25:48 +0000 Subject: [PATCH 02/20] test(valkey): add the contract scenarios of the shared tier The four scenarios watch_lost, hscan_bytes, rename_hash_ttl and expire_hdel_unlink, and binary words and replies in the replay record. They fail until a real valkey-server records them. Failed tests: - tests/valkey/test_valkey_contract.py::test_the_record_is_of_the_locked_valkey_py - tests/valkey/test_valkey_contract.py::test_the_fake_answers_each_scenario_as_the_recorded_server[watch_lost] - tests/valkey/test_valkey_contract.py::test_the_fake_answers_each_scenario_as_the_recorded_server[hscan_bytes] - tests/valkey/test_valkey_contract.py::test_the_fake_answers_each_scenario_as_the_recorded_server[rename_hash_ttl] - tests/valkey/test_valkey_contract.py::test_the_fake_answers_each_scenario_as_the_recorded_server[expire_hdel_unlink] --- tests/support/valkey_recording.py | 5 +- tests/support/valkey_replay.py | 13 +++-- tests/support/valkey_scenarios.py | 82 +++++++++++++++++++++++++++- tests/valkey/test_valkey_contract.py | 11 +++- 4 files changed, 102 insertions(+), 9 deletions(-) diff --git a/tests/support/valkey_recording.py b/tests/support/valkey_recording.py index 741a6110ab..30aaed3e9c 100644 --- a/tests/support/valkey_recording.py +++ b/tests/support/valkey_recording.py @@ -61,6 +61,7 @@ LOOPBACK, RECORD, SHUTDOWN_POLL_SECONDS, + TEXT_ERRORS, pack_command, read_command, read_reply, @@ -116,7 +117,9 @@ def handle(self) -> None: reply = read_reply(replies) # The exchange is kept before the client reads the reply, so the record is # complete once the client has its last reply. - self.server.exchanges.append({"command": command, "reply": reply.decode()}) + self.server.exchanges.append( + {"command": command, "reply": reply.decode(errors=TEXT_ERRORS)} + ) self.wfile.write(reply) diff --git a/tests/support/valkey_replay.py b/tests/support/valkey_replay.py index 341fb2f1a4..1ae94211f1 100644 --- a/tests/support/valkey_replay.py +++ b/tests/support/valkey_replay.py @@ -7,7 +7,9 @@ took, so a test sees a client that sends other commands than the record holds. An exchange holds the command, as the words of its RESP array, and the reply, as the RESP2 text -that the server sent. valkey-py speaks RESP2 unless a client asks for RESP3. The port is bound on +that the server sent. A byte that is not UTF-8, as in a zlib value, is kept as a lone surrogate +(`surrogateescape`), which JSON writes as a `\\udcXX` escape, so the replay sends the same bytes +(#4668). valkey-py speaks RESP2 unless a client asks for RESP3. The port is bound on 127.0.0.1 in the test's process, which the hermetic floor allows. The RESP framing is the project's own, in about 30 lines. valkey-py and fakeredis keep their @@ -30,6 +32,8 @@ # How often a server's loop looks for its shutdown; `serve_forever` waits half a second by default. SHUTDOWN_POLL_SECONDS = 0.01 _CRLF = b"\r\n" +# How a byte that is not UTF-8 is kept in the text of a word or a reply. +TEXT_ERRORS = "surrogateescape" def load_record() -> dict[str, Any]: @@ -64,7 +68,8 @@ def read_command(stream: BinaryIO) -> list[str] | None: size = _line(stream) if not size.startswith(b"$"): raise ValueError(f"a command word is not a bulk string: {size!r}") - words.append(stream.read(int(size[1:]) + len(_CRLF))[: -len(_CRLF)].decode()) + word = stream.read(int(size[1:]) + len(_CRLF))[: -len(_CRLF)] + words.append(word.decode(errors=TEXT_ERRORS)) return words @@ -87,7 +92,7 @@ def pack_command(words: Sequence[str]) -> bytes: """A command as valkey-py sends it: an array of bulk strings.""" parts = [b"*%d\r\n" % len(words)] for word in words: - data = word.encode() + data = word.encode(errors=TEXT_ERRORS) parts.append(b"$%d\r\n%s\r\n" % (len(data), data)) return b"".join(parts) @@ -142,7 +147,7 @@ def answer(self, command: list[str]) -> bytes: if expected and expected["command"] == command: self._next += 1 reply: str = expected["reply"] - return reply.encode() + return reply.encode(errors=TEXT_ERRORS) self.unexpected.append(" ".join(command)) # The error names only the command, since a word of its arguments can hold a CRLF. return b"-ERR no recorded reply for %s\r\n" % " ".join(command[:1]).encode() diff --git a/tests/support/valkey_scenarios.py b/tests/support/valkey_scenarios.py index b9efcefde3..e13f4c7ae9 100644 --- a/tests/support/valkey_scenarios.py +++ b/tests/support/valkey_scenarios.py @@ -10,17 +10,20 @@ The request bytes do not change between runs: a `Lock` gets an explicit token and timeout, and `SET EXAT` a fixed time. Each scenario uses its own key prefix and deletes its keys at the end. A scenario that runs Lua sends `SCRIPT FLUSH` first, so valkey-py meets `NOSCRIPT` and loads the -script on both sides in each order in which the cases run. +script on both sides in each order in which the cases run. A binary value is a fixed zlib text, +so its bytes do not change between runs either. """ from __future__ import annotations +import zlib from collections.abc import Callable from dataclasses import dataclass from typing import Any import valkey -from valkey.exceptions import LockNotOwnedError, ResponseError +from valkey.client import NEVER_DECODE +from valkey.exceptions import LockNotOwnedError, ResponseError, WatchError from devops_cli.exceptions.valkey import ValkeyCommandError from devops_cli.valkey.client import ValkeyClient @@ -45,6 +48,12 @@ SET_AND_GET_SCRIPT = "redis.call('SET', KEYS[1], ARGV[1]); return redis.call('GET', KEYS[1])" STATUS_SCRIPT = "return redis.status_reply('DONE')" ERROR_SCRIPT = "return redis.error_reply('devops contract refusal')" +# A zlib value, as the shared listing snapshot keeps each record: bytes that are not UTF-8. +BINARY_VALUE = zlib.compress(b'{"number": 1, "title": "devops contract"}' * 4) +# How many fields one `HSCAN` asks for, as the shared listing snapshot reads them. +SCAN_COUNT = 500 +# The TTL of the temporary key of a full write of the shared listing snapshot. +TEMPORARY_TTL_SECONDS = 600 def _key(scenario: str, name: str) -> str: @@ -197,6 +206,71 @@ def eval_through_the_project_client(client: valkey.Valkey) -> tuple[Any, ...]: ) +def _watch_refusal(call: Callable[[], Any]) -> str: + """The class of the error that a transaction raises when a watched key changed.""" + try: + call() + except WatchError as exc: + return type(exc).__name__ + return "none" + + +def watch_lost(client: valkey.Valkey) -> tuple[Any, ...]: + """A transaction whose watched hash another client changed writes nothing (#4668).""" + key = _key("watch_lost", "hash") + client.hset(key, "meta", "first") + with client.pipeline(transaction=True) as pipe: + pipe.watch(key) + seen = pipe.hget(key, "meta") + # The client sends this on a second connection, as another writer does. + client.hset(key, "meta", "other") + pipe.multi() + pipe.hset(key, "meta", "mine") + lost = _watch_refusal(pipe.execute) + return seen, lost, client.hget(key, "meta"), client.delete(key) + + +def hscan_bytes(client: valkey.Valkey) -> tuple[Any, ...]: + """`HSCAN` with `NEVER_DECODE` gives the bytes of a binary value to a decoding client (#4668).""" + key = _key("hscan_bytes", "hash") + written = client.hset(key, mapping={"1": BINARY_VALUE, "2": BINARY_VALUE}) + cursor, fields = client.execute_command( + "HSCAN", key, 0, "COUNT", SCAN_COUNT, **{NEVER_DECODE: True} + ) + field = client.execute_command("HGET", key, "1", **{NEVER_DECODE: True}) + return written, cursor, sorted(fields.items()), field, client.delete(key) + + +def rename_hash_ttl(client: valkey.Valkey) -> tuple[Any, ...]: + """`RENAME` of a temporary hash with a TTL replaces a hash that exists and keeps a TTL (#4668).""" + key, temporary = _key("rename_hash_ttl", "hash"), _key("rename_hash_ttl", "next") + client.hset(key, mapping={"1": "old", "2": "old"}) + client.hset(temporary, mapping={"1": "new"}) + client.expire(temporary, TEMPORARY_TTL_SECONDS) + renamed = client.rename(temporary, key) + ttl = client.ttl(key) + return ( + renamed, + 0 < ttl <= TEMPORARY_TTL_SECONDS, + client.hgetall(key), + client.exists(temporary), + client.delete(key), + ) + + +def expire_hdel_unlink(client: valkey.Valkey) -> tuple[Any, ...]: + """`EXPIRE` sets a TTL, `HDEL` removes the fields that exist, `UNLINK` counts its keys (#4668).""" + key, other = _key("expire_hdel_unlink", "hash"), _key("expire_hdel_unlink", "other") + client.hset(key, mapping={"meta": "m", "1": "a", "2": "b"}) + client.set(other, "x") + expired = client.expire(key, TTL_SECONDS) + ttl = client.ttl(key) + removed = client.hdel(key, "2", "3") + fields = sorted(client.hkeys(key)) + unlinked = client.unlink(key, other, _key("expire_hdel_unlink", "missing")) + return expired, 0 < ttl <= TTL_SECONDS, removed, fields, unlinked, client.exists(key) + + @dataclass(frozen=True) class ValkeyScenario: """A scenario: its name and its calls.""" @@ -214,4 +288,8 @@ class ValkeyScenario: ValkeyScenario("lock_lost", lock_lost), ValkeyScenario("registered_script", registered_script), ValkeyScenario("eval", eval_through_the_project_client), + ValkeyScenario("watch_lost", watch_lost), + ValkeyScenario("hscan_bytes", hscan_bytes), + ValkeyScenario("rename_hash_ttl", rename_hash_ttl), + ValkeyScenario("expire_hdel_unlink", expire_hdel_unlink), ) diff --git a/tests/valkey/test_valkey_contract.py b/tests/valkey/test_valkey_contract.py index 3da1f6e9a7..90f25adf89 100644 --- a/tests/valkey/test_valkey_contract.py +++ b/tests/valkey/test_valkey_contract.py @@ -9,8 +9,10 @@ Covered: `SET NX EX`; `SET EXAT`, `KEEPTTL` and an expiry in the past; `HINCRBY` and its refusal of a field that holds no integer; `ZADD` with a trim by score and by rank; a valkey-py `Lock` acquired, refused to a second holder, extended, owned and released, and a `Lock` that another -holder took; a script from `register_script`, which meets `NOSCRIPT` and loads itself; and `EVAL` -through the project's `ValkeyClient`. +holder took; a script from `register_script`, which meets `NOSCRIPT` and loads itself; `EVAL` +through the project's `ValkeyClient`; a `WATCH` transaction that another client made fail; `HSCAN` +and `HGET` of binary values with `NEVER_DECODE`; `RENAME` of a temporary hash with a TTL onto a +hash that exists; and `EXPIRE`, `HDEL` and `UNLINK` (#4668). Not recorded: the moving window of `limits`, which #4563 adds with the `limits` dependency; RESP3; a server that fails or stops in the middle of a session. @@ -26,6 +28,7 @@ from tests.support.valkey_replay import RecordedValkey, load_record, scenario_exchanges from tests.support.valkey_scenarios import ( + BINARY_VALUE, FAR_EXPIRY, INTRUDER_TOKEN, SCENARIOS, @@ -56,6 +59,10 @@ ("ValkeyCommandError", "devops contract refusal"), 1, ), + "watch_lost": ("first", "WatchError", "other", 1), + "hscan_bytes": (2, 0, [(b"1", BINARY_VALUE), (b"2", BINARY_VALUE)], BINARY_VALUE, 1), + "rename_hash_ttl": (True, True, {"1": "new"}, 0, 1), + "expire_hdel_unlink": (True, True, 1, ["1", "meta"], 2, 0), } From c8749573952676f6629c169a305cc389459a091a Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:27:02 +0000 Subject: [PATCH 03/20] test(valkey): give the cache tier the commands of the shared tier The tier keeps a binary hash with a TTL, a lost WATCH transaction writes nothing, a failed command counts its command and error, and a silent Valkey host opens the breaker after one timeout (T3). The fixtures shared_valkey and silent_valkey come with them. Failed tests: - tests/valkey/test_valkey_cache_tier.py::test_the_cache_tier_keeps_a_binary_hash_with_a_ttl - tests/valkey/test_valkey_cache_tier.py::test_a_writer_whose_watched_key_changed_writes_nothing - tests/valkey/test_valkey_cache_tier.py::test_a_failed_tier_command_counts_its_command_and_error - tests/valkey/test_valkey_cache_tier.py::test_a_silent_valkey_times_out_and_opens_the_breaker --- tests/support/fakes/valkey.py | 75 ++++++++++++- tests/valkey/test_valkey_cache_tier.py | 144 ++++++++++++++++++++++++- 2 files changed, 216 insertions(+), 3 deletions(-) diff --git a/tests/support/fakes/valkey.py b/tests/support/fakes/valkey.py index 8f0e0ab038..71e9825c31 100644 --- a/tests/support/fakes/valkey.py +++ b/tests/support/fakes/valkey.py @@ -10,7 +10,9 @@ `valkey-server` (#4557). fakeredis runs Lua through its `lua` extra (`lupa`), and holds its server to Valkey's behaviour in its own test suite. It answers no INFO, and holds a silent or slow server only as a connection that fails; a test of a timeout binds a -loopback listener that never answers, as the floor's `refusing_port` does for a refused port. +loopback listener that never answers (`silent_valkey`), as the floor's `refusing_port` does for a +refused port. `shared_valkey` installs a cache tier over the fake as the one tier of the process, +which the shared tier of the project brain reads (#4668). The pool is the fake's own, so a test of what the client's own password, the database of its endpoint and its decoding send and read binds a loopback listener that records the commands it receives. That @@ -35,6 +37,7 @@ from tests.support.waits import POLL_INTERVAL_SECONDS, THREAD_HANDOFF_BOUND_SECONDS if TYPE_CHECKING: + from devops_cli.valkey.cache import ValkeyCacheTier from devops_cli.valkey.endpoint import ValkeyEndpoint @@ -89,6 +92,76 @@ def valkey(valkey_server: Any) -> Iterator[Any]: client.close() +@pytest.fixture +def shared_valkey(valkey_server: FakeServer) -> Iterator[ValkeyCacheTier]: + """A cache tier over `valkey_server`, installed as the one tier of the process. + + `shared_cache_tier()` gives it, so each cache of the process reads and writes the fake. The + imports are local, so the fail-to-pass replay can load this plugin on a base without the seam. + """ + from devops_cli.valkey.cache import ( + ValkeyCacheTier, + install_shared_cache_tier, + reset_shared_cache_tier, + ) + + client = valkey_client_on(valkey_server) + tier = ValkeyCacheTier(client) + install_shared_cache_tier(tier) + try: + yield tier + finally: + reset_shared_cache_tier() + client.close() + + +class SilentValkey: + """A loopback listener that accepts each connection and never answers: a silent Valkey host. + + `port` is its port, and `connections` counts the connections that it accepted. + """ + + def __init__(self, listener: socket.socket) -> None: + self._listener = listener + self._held: list[socket.socket] = [] + self._ended = threading.Event() + self.port: int = listener.getsockname()[1] + self._thread = threading.Thread(target=self._accept, daemon=True) + self._thread.start() + + @property + def connections(self) -> int: + return len(self._held) + + def _accept(self) -> None: + self._listener.settimeout(POLL_INTERVAL_SECONDS) + while not self._ended.is_set(): + try: + connection, _ = self._listener.accept() + except TimeoutError: + continue + self._held.append(connection) + + def close(self) -> None: + self._ended.set() + self._thread.join(timeout=THREAD_HANDOFF_BOUND_SECONDS) + for connection in self._held: + connection.close() + + +@pytest.fixture +def silent_valkey() -> Iterator[SilentValkey]: + """A loopback Valkey host that accepts a connection and answers no command.""" + with socket.socket() as listener: + listener.bind(("127.0.0.1", 0)) + listener.listen(8) + silent = SilentValkey(listener) + try: + yield silent + finally: + silent.close() + + def bulk_reply(payload: bytes) -> bytes: """A RESP bulk string reply.""" return b"$%d\r\n%s\r\n" % (len(payload), payload) diff --git a/tests/valkey/test_valkey_cache_tier.py b/tests/valkey/test_valkey_cache_tier.py index 9d44d32a91..1aef582b1a 100644 --- a/tests/valkey/test_valkey_cache_tier.py +++ b/tests/valkey/test_valkey_cache_tier.py @@ -2,19 +2,24 @@ Each test drives the circuit breaker of the tier through the shared Valkey fake, whose server fails each command while `connected` is False, and through the `clock` fixture, which moves the -wall clock that the breaker reads. No test waits in real time. +wall clock that the breaker reads. No test waits in real time, except the test of a silent host, +which waits one `valkey.timeout` of 0.05 s. The hash, TTL, rename and WATCH commands of the +shared tier of the project brain (#4668) go through the same breaker. """ from __future__ import annotations import logging +import zlib from typing import TYPE_CHECKING import pytest -from fakeredis import FakeServer +from fakeredis import FakeServer, FakeValkey from devops_cli.valkey.client import ValkeyClient from tests.support.fakes.clock import ClockFake +from tests.support.fakes.otlp import FakeCollector +from tests.support.fakes.valkey import SilentValkey, valkey_client_on if TYPE_CHECKING: from pathlib import Path @@ -260,3 +265,138 @@ def test_a_valkey_url_that_is_not_valid_turns_each_cache_off_with_one_warning( 1, True, ) + + +# ── The commands of the shared tier of the project brain (#4668) ────────────── + +# A zlib value, as the shared listing snapshot keeps each record: bytes that are not UTF-8. +_BINARY = zlib.compress(b'{"number": 7, "title": "a record"}' * 8) + + +def _errors(otlp: FakeCollector) -> dict[tuple[str, str], float]: + """The failed commands of the tier, by command and error.""" + from devops_cli.telemetry.instruments import VALKEY_CACHE_ERRORS_TOTAL + + counted: dict[tuple[str, str], float] = {} + for attributes, value in otlp.points(VALKEY_CACHE_ERRORS_TOTAL.name): + point = (attributes["op"], attributes["error"]) + counted[point] = counted.get(point, 0) + value + return counted + + +def test_the_cache_tier_keeps_a_binary_hash_with_a_ttl( + valkey_server: FakeServer, valkey_client: ValkeyClient +) -> None: + """The tier writes and reads bytes that are not UTF-8, sets a TTL, removes a field, renames + the hash and unlinks it.""" + tier = _tier(valkey_client) + reader = FakeValkey(server=valkey_server) + + written = tier.hset("hash", {"7": _BINARY, "meta": "text"}) + scanned = tier.hscan("hash", 0, 500) + expired = tier.expire("hash", 60) + ttl = reader.ttl("hash") + removed = tier.hdel("hash", "meta", "missing") + field = tier.hget("hash", "7") + renamed = tier.rename("hash", "moved") + unlinked = tier.unlink("moved", "missing") + + assert (written, scanned, expired, 0 < ttl <= 60, removed, field, renamed, unlinked) == ( + 2, + (0, {"7": _BINARY, "meta": b"text"}), + True, + True, + 1, + _BINARY, + True, + 1, + ) + assert reader.exists("hash", "moved") == 0 + + +def test_a_writer_whose_watched_key_changed_writes_nothing( + valkey_server: FakeServer, valkey_client: ValkeyClient +) -> None: + """A transaction whose key another client changed after the WATCH writes nothing and is not + tried again; a transaction with no change writes its commands.""" + other = valkey_client_on(valkey_server) + tier = _tier(valkey_client) + other.hset("snapshot", {"meta": "first"}) + seen: list[bytes | None] = [] + + def lost(meta: bytes | None) -> list[tuple[str, ...]]: + seen.append(meta) + other.hset("snapshot", {"meta": "other"}) + return [("HSET", "snapshot", "meta", "mine")] + + def won(meta: bytes | None) -> list[tuple[str, ...]]: + seen.append(meta) + return [("HSET", "snapshot", "meta", "mine"), ("EXPIRE", "snapshot", "60")] + + try: + lost_write = tier.watch_and_write("snapshot", "meta", lost) + after_the_lost_write = other.hget("snapshot", "meta") + refused_write = tier.watch_and_write("snapshot", "meta", lambda meta: []) + won_write = tier.watch_and_write("snapshot", "meta", won) + after_the_won_write = other.hget("snapshot", "meta") + finally: + other.close() + + assert ( + lost_write, + after_the_lost_write, + refused_write, + won_write, + after_the_won_write, + seen, + ) == (False, b"other", False, True, b"mine", [b"first", b"other"]) + + +def test_a_failed_tier_command_counts_its_command_and_error( + valkey_server: FakeServer, valkey_client: ValkeyClient, otlp: FakeCollector +) -> None: + """The first failed command counts `connection`; a command that the open breaker does not + send counts `open`, and the server gets nothing.""" + tier = _tier(valkey_client) + valkey_server.connected = False + scanned = tier.hscan("hash", 0, 500) + valkey_server.connected = True + written = tier.hset("hash", {"1": _BINARY}) + + assert (scanned, written, FakeValkey(server=valkey_server).exists("hash"), _errors(otlp)) == ( + None, + None, + 0, + {("hscan", "connection"): 1.0, ("hset", "open"): 1.0}, + ) + + +@pytest.mark.usefixtures("keyring_store") +def test_a_silent_valkey_times_out_and_opens_the_breaker( + silent_valkey: SilentValkey, monkeypatch: pytest.MonkeyPatch, otlp: FakeCollector +) -> None: + """T3: a Valkey host that accepts the connection and answers no command costs one timeout. + + The tier waits at most 0.25 s for a connection and `valkey.timeout` for a reply. The first + read is a miss that counts `timeout`, the breaker opens, and the next read opens no second + connection to the host. + """ + from devops_cli.config.defaults import DEFAULT_VALKEY_CACHE_CONNECT_TIMEOUT_SECONDS + from devops_cli.config.settings import reset_settings_cache + from devops_cli.valkey.cache import shared_cache_tier + + monkeypatch.setenv("DEVOPS_CLI_VALKEY_URL", f"valkey://127.0.0.1:{silent_valkey.port}") + monkeypatch.setenv("DEVOPS_CLI_VALKEY_TIMEOUT", "0.05") + reset_settings_cache() + tier = shared_cache_tier() + assert tier is not None + + reads = (tier.get("fact"), tier.get("fact")) + + assert ( + tier.client.connect_timeout <= DEFAULT_VALKEY_CACHE_CONNECT_TIMEOUT_SECONDS, + reads, + tier.is_open, + silent_valkey.connections, + _errors(otlp), + ) == (True, (None, None), True, 1, {("get", "timeout"): 1.0, ("get", "open"): 1.0}) From e5d266f48fb6ecd2257d7da85a94966d4dad54ed Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:30:26 +0000 Subject: [PATCH 04/20] feat(valkey): give the cache tier the commands of the shared tier ValkeyClient and ValkeyCacheTier get HGET, HSET, HDEL, HSCAN, EXPIRE, UNLINK, RENAME and one WATCH transaction that is not tried again. A read of a hash value uses NEVER_DECODE, so a zlib value comes back as bytes. Each failed or unsent command of the tier adds one to devops_cli_valkey_cache_errors_total. The four counters of the project brain and their label values are declared. --- .../tasks.md | 6 +- src/devops_cli/config/constants.py | 51 ++++++++ src/devops_cli/telemetry/instruments.py | 40 ++++++ src/devops_cli/valkey/cache.py | 120 ++++++++++++++++-- src/devops_cli/valkey/client.py | 86 ++++++++++++- 5 files changed, 289 insertions(+), 14 deletions(-) diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index a9a5488a1c..3a6f84e159 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -11,11 +11,11 @@ Kind: other. Reads: `tests/support/valkey_scenarios.py`, `tests/support/valkey_r ## 2. Give the cache tier the hash, TTL, rename and WATCH commands behind its breaker Kind: behavior. Reads: `src/devops_cli/valkey/client.py`, `src/devops_cli/valkey/cache.py`, `src/devops_cli/telemetry/instruments.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/exceptions/valkey.py`, `tests/valkey/test_valkey_cache_tier.py`, `tests/support/fakes/valkey.py`, `tests/support/fakes/otlp.py`, `tests/telemetry/test_telemetry_instruments.py`. Changes: `src/devops_cli/valkey/client.py`, `src/devops_cli/valkey/cache.py`, `src/devops_cli/telemetry/instruments.py`, `src/devops_cli/config/constants.py`, `tests/valkey/test_valkey_cache_tier.py`, `tests/support/fakes/valkey.py`. -Adds: `ValkeyClient.hget`, `ValkeyClient.hset`, `ValkeyClient.hdel`, `ValkeyClient.hscan`, `ValkeyClient.expire`, `ValkeyClient.unlink`, `ValkeyClient.rename`, `ValkeyClient.watch_and_write`, the same eight methods on `ValkeyCacheTier`, `BRAIN_READS_TOTAL`, `BRAIN_WRITES_TOTAL`, `VALKEY_CACHE_ERRORS_TOTAL`, `BRAIN_GITHUB_REQUESTS_SAVED_TOTAL`, the `silent_valkey` fixture +Adds: `ValkeyClient.hget`, `ValkeyClient.hset`, `ValkeyClient.hdel`, `ValkeyClient.hscan`, `ValkeyClient.expire`, `ValkeyClient.unlink`, `ValkeyClient.rename`, `ValkeyClient.watch_and_write`, the same eight methods on `ValkeyCacheTier`, `ValkeyCacheTier.is_open`, `install_shared_cache_tier`, `BrainStore`, `BrainRead`, `BrainWrite`, `ValkeyCacheError`, `BRAIN_READS_TOTAL`, `BRAIN_WRITES_TOTAL`, `VALKEY_CACHE_ERRORS_TOTAL`, `BRAIN_GITHUB_REQUESTS_SAVED_TOTAL`, the `silent_valkey` and `shared_valkey` fixtures -- [ ] 2.1 Write in `tests/valkey/test_valkey_cache_tier.py`: `test_the_cache_tier_keeps_a_binary_hash_with_a_ttl` (HSET of zlib bytes, HSCAN gives the same bytes, EXPIRE gives a TTL above 0, HDEL, RENAME and UNLINK, on the `valkey_server` fake); `test_a_writer_whose_watched_key_changed_writes_nothing` (two clients on one fake; `watch_and_write` returns False and the hash keeps the other client's value); `test_a_failed_tier_command_counts_its_command_and_error` (with `connected = False` on the OTLP fake, the first HSCAN adds `devops_cli_valkey_cache_errors_total{op="hscan",error="connection"}`, and an HSET in the cooldown adds `error="open"` and sends nothing); and `test_a_silent_valkey_times_out_and_opens_the_breaker` for the scenario `T3 silent shared tier`: add the fixture `silent_valkey` to `tests/support/fakes/valkey.py`, a loopback listener that accepts and never answers, set `DEVOPS_CLI_VALKEY_TIMEOUT=0.05`, and assert the connect timeout of at most 0.25 s, the counted `timeout`, the open breaker and no second connection to the listener, with no bound on the elapsed time +- [x] 2.1 Write in `tests/valkey/test_valkey_cache_tier.py`: `test_the_cache_tier_keeps_a_binary_hash_with_a_ttl` (HSET of zlib bytes, HSCAN gives the same bytes, EXPIRE gives a TTL above 0, HDEL, RENAME and UNLINK, on the `valkey_server` fake); `test_a_writer_whose_watched_key_changed_writes_nothing` (two clients on one fake; `watch_and_write` returns False and the hash keeps the other client's value); `test_a_failed_tier_command_counts_its_command_and_error` (with `connected = False` on the OTLP fake, the first HSCAN adds `devops_cli_valkey_cache_errors_total{op="hscan",error="connection"}`, and an HSET in the cooldown adds `error="open"` and sends nothing); and `test_a_silent_valkey_times_out_and_opens_the_breaker` for the scenario `T3 silent shared tier`: add the fixtures `silent_valkey` and `shared_valkey` (a cache tier over the fake, installed as the tier of the process through `install_shared_cache_tier`) to `tests/support/fakes/valkey.py`; `silent_valkey` is a loopback listener that accepts and never answers, set `DEVOPS_CLI_VALKEY_TIMEOUT=0.05`, and assert the connect timeout of at most 0.25 s, the counted `timeout`, the open breaker and no second connection to the listener, with no bound on the elapsed time - Verification: `$ uv run devops ci test tests/valkey/test_valkey_cache_tier.py` fails on the base -- [ ] 2.2 Add the eight commands to `ValkeyClient` in `src/devops_cli/valkey/client.py`. `hget` of a value and `hscan` send `NEVER_DECODE` and return bytes. `watch_and_write(key, decide)` runs WATCH, gives `decide` the reply of `HGET key meta`, sends the commands that `decide` returns in one MULTI/EXEC, and returns False with no retry on `WatchError` or when `decide` returns nothing. Add the same methods to `ValkeyCacheTier` in `src/devops_cli/valkey/cache.py` through `_send`, and make `_send` add one `VALKEY_CACHE_ERRORS_TOTAL` for each failed command and each command that the open breaker does not send, with `op` the command and `error` one of `timeout`, `connection`, `auth`, `reply`, `open`. Declare the four counters in `src/devops_cli/telemetry/instruments.py`, add them to `INSTRUMENTS` and `__all__`, and put their label values in `src/devops_cli/config/constants.py` +- [x] 2.2 Add the eight commands to `ValkeyClient` in `src/devops_cli/valkey/client.py`. `hget` of a value and `hscan` send `NEVER_DECODE` and return bytes. `watch_and_write(key, field, decide)` runs WATCH, gives `decide` the reply of `HGET key field` as bytes, sends the commands that `decide` returns in one MULTI/EXEC, and returns False with no retry on `WatchError` or when `decide` returns nothing. Add the same methods to `ValkeyCacheTier` in `src/devops_cli/valkey/cache.py` through `_send`, and make `_send` add one `VALKEY_CACHE_ERRORS_TOTAL` for each failed command and each command that the open breaker does not send, with `op` the command and `error` one of `timeout`, `connection`, `auth`, `reply`, `open`. `is_open` tells a caller a miss from a failure, `set` returns whether the write was sent, and `install_shared_cache_tier` installs the tier of the process. Declare the four counters in `src/devops_cli/telemetry/instruments.py`, add them to `INSTRUMENTS` and `__all__`, and put their label values in `src/devops_cli/config/constants.py` as the enums `BrainStore`, `BrainRead`, `BrainWrite` and `ValkeyCacheError` - Verification: `$ uv run devops ci test tests/valkey/test_valkey_cache_tier.py tests/telemetry/test_telemetry_instruments.py` passes ## 3. Add the tiered mapping over the in-process tier and the shared tier diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 528e508a33..b215ffa2f7 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -2891,6 +2891,57 @@ class WebhookExposure(StrEnum): # The one query key that a Valkey URL can hold: the database, as in `valkey://example.com/?db=2` CONST_VALKEY_URL_QUERY_KEYS: Final[frozenset[str]] = frozenset({"db"}) +# The key prefixes of the project brain in the cache Valkey (#4668, ADR 0023 section 6): the tool +# facts under `valkey:brain`, the listing snapshots under `valkey:roadmap`. The version is part of +# the prefix, so a reader of a new version never reads a key of an older one. +CONST_VALKEY_BRAIN_PREFIX: Final[str] = "valkey:brain:v1" +CONST_VALKEY_ROADMAP_PREFIX: Final[str] = "valkey:roadmap:v1" + + +class BrainStore(StrEnum): + """The `store` label of the counters of the project brain (#4668).""" + + SNAPSHOT = "snapshot" + FACT = "fact" + + +class BrainRead(StrEnum): + """The `result` label of `devops_cli_brain_reads_total` (#4668): the tier that gave the value, + the source when no tier held it, the fallback when the shared tier failed or its breaker was + open, and a private repository, which the shared tier does not hold.""" + + MEMORY = "memory" + SHARED = "shared" + SOURCE = "source" + FALLBACK = "fallback" + PRIVATE = "private" + + +class BrainWrite(StrEnum): + """The `result` label of `devops_cli_brain_writes_total` (#4668): written to the shared tier, + skipped while it failed, kept local because the value is over its bound, refused because the + shared copy is newer, or kept local for a private repository.""" + + SHARED = "shared" + SKIPPED = "skipped" + OVERSIZE = "oversize" + OLDER = "older" + PRIVATE = "private" + + +class ValkeyCacheError(StrEnum): + """The `error` label of `devops_cli_valkey_cache_errors_total` (#4668): how a command of the + Valkey cache tier failed, `open` for a command that the open breaker did not send, and + `budget` for a load of a shared snapshot that passed its time budget.""" + + TIMEOUT = "timeout" + CONNECTION = "connection" + AUTH = "auth" + REPLY = "reply" + OPEN = "open" + BUDGET = "budget" + + # Characters of a failed embedding reply's body quoted in its EmbeddingsError CONST_EMBEDDING_REPLY_EXCERPT_CHARS: Final[int] = 500 diff --git a/src/devops_cli/telemetry/instruments.py b/src/devops_cli/telemetry/instruments.py index 8637fe5292..54fb59e51b 100644 --- a/src/devops_cli/telemetry/instruments.py +++ b/src/devops_cli/telemetry/instruments.py @@ -707,6 +707,38 @@ class Instrument: "or miss. A hit names its tier: memory for the cache of the process, valkey, or disk for " "the cache file that keeps the vectors of intake between runs", ) +BRAIN_READS_TOTAL = Instrument( + "devops_cli_brain_reads_total", + InstrumentKind.COUNTER, + "1", + "Reads of the project brain (#4668), by store (snapshot or fact) and result: memory or " + "shared for the tier that gave the value, source when no tier held it, fallback when the " + "shared tier failed or its breaker was open, and private for a repository that the shared " + "tier does not hold", +) +BRAIN_WRITES_TOTAL = Instrument( + "devops_cli_brain_writes_total", + InstrumentKind.COUNTER, + "1", + "Writes of the project brain to the shared tier (#4668), by store and result: shared, " + "skipped while the tier failed, oversize for a value over 1 MiB that stays in memory, older " + "when the shared snapshot is newer or another writer won, and private", +) +VALKEY_CACHE_ERRORS_TOTAL = Instrument( + "devops_cli_valkey_cache_errors_total", + InstrumentKind.COUNTER, + "1", + "Commands of the Valkey cache tier that failed or that its open breaker did not send " + "(#4668), by command (op) and error: timeout, connection, auth, reply, open, or budget for a " + "load of a shared snapshot that passed its time budget", +) +BRAIN_GITHUB_REQUESTS_SAVED_TOTAL = Instrument( + "devops_cli_brain_github_requests_saved_total", + InstrumentKind.COUNTER, + "1", + "Listing pages of a full read that a process did not send because it took the shared " + "snapshot (#4668), by store", +) EMBEDDING_CACHE_SIZE = Instrument( "devops_cli_embedding_cache_size", InstrumentKind.GAUGE, @@ -974,6 +1006,10 @@ class Instrument: ROADMAP_STAGE_GATE_PROBLEMS, ROADMAP_STAGE_GATE_REFUSALS_TOTAL, EMBEDDING_CACHE_LOOKUPS_TOTAL, + BRAIN_READS_TOTAL, + BRAIN_WRITES_TOTAL, + VALKEY_CACHE_ERRORS_TOTAL, + BRAIN_GITHUB_REQUESTS_SAVED_TOTAL, EMBEDDING_CACHE_SIZE, RAG_EMBEDDING_BATCH_SIZE, RAG_EMBEDDING_BATCH_RESIZES_TOTAL, @@ -1070,6 +1106,9 @@ def backend_name(served_by: str | None) -> str: "AI_SPEND_USD_TOTAL", "AI_STRUCTURED_ATTEMPTS_TOTAL", "AI_TOKENS_TOTAL", + "BRAIN_GITHUB_REQUESTS_SAVED_TOTAL", + "BRAIN_READS_TOTAL", + "BRAIN_WRITES_TOTAL", "CI_CHECKS_TOTAL", "CI_GATE_SLOT_WAIT", "COMMAND_DURATION", @@ -1162,6 +1201,7 @@ def backend_name(served_by: str | None) -> str: "UPSTREAM_COMPONENT_STATUS", "UPSTREAM_SERVICE_STATUS", "USAGE_ERROR_TOTAL", + "VALKEY_CACHE_ERRORS_TOTAL", "VULNERABILITY_LOOKUPS_TOTAL", "WEB_SEARCHES_TOTAL", "Instrument", diff --git a/src/devops_cli/valkey/cache.py b/src/devops_cli/valkey/cache.py index c5e1067041..6ee633d2e0 100644 --- a/src/devops_cli/valkey/cache.py +++ b/src/devops_cli/valkey/cache.py @@ -17,24 +17,31 @@ A reply error (`ValkeyCommandError`) comes from a server that answers, so it does not open the breaker. A command that fails is a miss or a write that does not occur, and the cache continues -with its other tiers. pybreaker reads the time with `datetime.now`, which the `clock` fixture of -the tests moves. +with its other tiers. Each command that fails, and each command that the open breaker does not +send, adds one to `devops_cli_valkey_cache_errors_total` with the command and the error (#4668). +pybreaker reads the time with `datetime.now`, which the `clock` fixture of the tests moves. + +The shared tier of the project brain (#4668) uses the hash, TTL, rename and WATCH commands of the +tier through the same breaker, so the listing snapshots and the tool facts share the cooldown of +the embeddings and the threat-intelligence reads. """ from __future__ import annotations import logging import threading -from collections.abc import Callable +from collections.abc import Callable, Mapping, Sequence from typing import TYPE_CHECKING, Any from pybreaker import ( + STATE_OPEN, CircuitBreaker, CircuitBreakerError, CircuitBreakerListener, CircuitBreakerState, ) +from devops_cli.config.constants import ValkeyCacheError from devops_cli.config.defaults import ( DEFAULT_VALKEY_CACHE_BREAKER_COOLDOWN_SECONDS, DEFAULT_VALKEY_CACHE_BREAKER_FAILURES, @@ -42,7 +49,13 @@ ) from devops_cli.config.settings import get_valkey_password, load_settings from devops_cli.exceptions import DevOpsCLIError -from devops_cli.exceptions.valkey import ValkeyCommandError, ValkeyError +from devops_cli.exceptions.valkey import ( + ValkeyAuthenticationError, + ValkeyCommandError, + ValkeyError, + ValkeyTimeoutError, +) +from devops_cli.telemetry.instruments import VALKEY_CACHE_ERRORS_TOTAL, emit from devops_cli.valkey.client import ValkeyClient if TYPE_CHECKING: @@ -83,26 +96,101 @@ def __init__(self, client: ValkeyClient) -> None: throw_new_error_on_trip=False, ) + @property + def is_open(self) -> bool: + """Whether the breaker is open: the last command failed, and the cooldown sends none. + + A caller reads it after a command that gave None, to tell a miss from a failure. + """ + return bool(self._breaker.current_state == STATE_OPEN) + def get(self, key: str) -> str | None: """The string at `key`; None for a miss, an open breaker and a read that fails.""" - value: str | None = self._send(self.client.get, key) + value: str | None = self._send("get", self.client.get, key) + return value + + def set(self, key: str, value: str, *, ex: int) -> bool: + """Keep `value` at `key` for `ex` seconds; False when the write is not sent or fails.""" + return bool(self._send("set", self.client.set, key, value, ex=ex)) + + def hget(self, key: str, field: str) -> bytes | None: + """The bytes of one field of the hash at `key`; None for a miss and a failure.""" + value: bytes | None = self._send("hget", self.client.hget, key, field) return value - def set(self, key: str, value: str, *, ex: int) -> None: - """Keep `value` at `key` for `ex` seconds; no write while the breaker is open.""" - self._send(self.client.set, key, value, ex=ex) + def hset(self, key: str, values: Mapping[str, bytes | str]) -> int | None: + """Set fields of the hash at `key`: the number of new fields, or None on a failure.""" + written: int | None = self._send("hset", self.client.hset, key, values) + return written + + def hdel(self, key: str, *fields: str) -> int | None: + """Remove fields of the hash at `key`: the number removed, or None on a failure.""" + removed: int | None = self._send("hdel", self.client.hdel, key, *fields) + return removed + + def hscan(self, key: str, cursor: int, count: int) -> tuple[int, dict[str, bytes]] | None: + """One step of `HSCAN` (see `ValkeyClient.hscan`), or None on a failure.""" + step: tuple[int, dict[str, bytes]] | None = self._send( + "hscan", self.client.hscan, key, cursor, count + ) + return step + + def expire(self, key: str, seconds: int) -> bool: + """Expire `key` after `seconds`; False when the key is missing or the command fails.""" + return bool(self._send("expire", self.client.expire, key, seconds)) + + def unlink(self, *keys: str) -> int | None: + """Remove keys: the number removed, or None on a failure.""" + removed: int | None = self._send("unlink", self.client.unlink, *keys) + return removed - def _send(self, command: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: - """The reply to one command through the breaker; None when it is not sent or it fails.""" + def rename(self, source: str, target: str) -> bool: + """Move `source` onto `target`; False when the command fails.""" + return bool(self._send("rename", self.client.rename, source, target)) + + def watch_and_write( + self, + key: str, + field: str, + decide: Callable[[bytes | None], Sequence[Sequence[Any]]], + ) -> bool | None: + """One WATCH transaction (see `ValkeyClient.watch_and_write`): True when it wrote, False + when `decide` gave no command or another client changed `key`, None on a failure.""" + written: bool | None = self._send("watch", self.client.watch_and_write, key, field, decide) + return written + + def _send(self, op: str, command: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + """The reply to one command through the breaker; None when it is not sent or it fails. + + `op` names the command in `devops_cli_valkey_cache_errors_total`. + """ try: return self._breaker.call(command, *args, **kwargs) except CircuitBreakerError: + _count_error(op, ValkeyCacheError.OPEN) return None except ValkeyError as exc: logger.debug("A command of the Valkey cache tier failed: %s", exc) + _count_error(op, _error_of(exc)) return None +def _error_of(exc: ValkeyError) -> ValkeyCacheError: + """The error label of a failed command.""" + if isinstance(exc, ValkeyTimeoutError): + return ValkeyCacheError.TIMEOUT + if isinstance(exc, ValkeyAuthenticationError): + return ValkeyCacheError.AUTH + if isinstance(exc, ValkeyCommandError): + return ValkeyCacheError.REPLY + return ValkeyCacheError.CONNECTION + + +def _count_error(op: str, error: ValkeyCacheError) -> None: + """Add one failed or unsent command to `devops_cli_valkey_cache_errors_total`.""" + emit(VALKEY_CACHE_ERRORS_TOTAL, 1, {"op": op, "error": error.value}) + + def _configured_cache_tier(settings: Settings) -> ValkeyCacheTier: """A cache tier over the Valkey that `valkey.url` names. @@ -145,6 +233,18 @@ def shared_cache_tier() -> ValkeyCacheTier | None: return _shared_tier +def install_shared_cache_tier(tier: ValkeyCacheTier | None) -> None: + """Make `tier` the one cache tier of the process, or turn the Valkey tier off with None. + + A test installs a tier over the in-memory Valkey through this seam; `reset_shared_cache_tier` + removes it. + """ + global _shared_tier, _shared_tier_built + with _SHARED_TIER_LOCK: + _shared_tier = tier + _shared_tier_built = True + + def reset_shared_cache_tier() -> None: """Drop the tier of the process, so the next `shared_cache_tier` builds it again.""" global _shared_tier, _shared_tier_built diff --git a/src/devops_cli/valkey/client.py b/src/devops_cli/valkey/client.py index e9e2cf4f79..091b6975ab 100644 --- a/src/devops_cli/valkey/client.py +++ b/src/devops_cli/valkey/client.py @@ -6,13 +6,17 @@ the private egress level, and connect only to the vetted IP literals. Valkey is an internal service, so every address but a cloud metadata address and a scoped IPv6 address is admitted. This includes the link-local 169.254.1.2 that a rootless Podman container reaches its host at. + +The pool decodes each reply as UTF-8, which would spoil a binary value such as a zlib record of +the shared listing snapshot. A read of a hash value (`hget`, `hscan`) sends valkey-py's per-command +option `NEVER_DECODE`, so the value comes back as bytes; a write of bytes needs no option (#4668). """ from __future__ import annotations import ipaddress import socket -from collections.abc import Callable, Iterator, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence from contextlib import contextmanager from itertools import batched from typing import Any, Protocol, runtime_checkable @@ -20,6 +24,7 @@ import httpcore2 import valkey from valkey import exceptions as valkey_exceptions +from valkey.client import NEVER_DECODE from valkey.connection import Connection, SSLConnection from devops_cli.config.defaults import ( @@ -281,6 +286,85 @@ def bgsave(self) -> str: """Start a background snapshot; the server's acknowledgement.""" return str(self.execute("BGSAVE")) + def hget(self, key: str, field: str) -> bytes | None: + """The bytes of one field of the hash at `key`, or None.""" + value = self._call(self._raw.execute_command, "HGET", key, field, **{NEVER_DECODE: True}) + return None if value is None else bytes(value) + + def hset(self, key: str, values: Mapping[str, bytes | str]) -> int: + """Set fields of the hash at `key`; return the number of fields that are new.""" + words = [word for pair in values.items() for word in pair] + return int(self._call(self._raw.execute_command, "HSET", key, *words)) + + def hdel(self, key: str, *fields: str) -> int: + """Remove fields of the hash at `key`; return the number of fields removed.""" + if not fields: + return 0 + return int(self._call(self._raw.execute_command, "HDEL", key, *fields)) + + def hscan(self, key: str, cursor: int, count: int) -> tuple[int, dict[str, bytes]]: + """One step of `HSCAN`: the next cursor, 0 at the end, and the fields of the step with + the bytes of their values. `count` is the number of fields that the server is asked for.""" + reply = self._call( + self._raw.execute_command, + "HSCAN", + key, + cursor, + "COUNT", + count, + **{NEVER_DECODE: True}, + ) + next_cursor, flat = reply + fields = { + bytes(name).decode(): bytes(value) + for name, value in zip(flat[::2], flat[1::2], strict=True) + } + return int(next_cursor), fields + + def expire(self, key: str, seconds: int) -> bool: + """Expire `key` after `seconds`; whether the key exists.""" + return bool(self._call(self._raw.execute_command, "EXPIRE", key, seconds)) + + def unlink(self, *keys: str) -> int: + """Remove keys and free their memory in the background; return the number removed.""" + if not keys: + return 0 + return int(self._call(self._raw.execute_command, "UNLINK", *keys)) + + def rename(self, source: str, target: str) -> bool: + """Move `source`, with its TTL, onto `target`, which it replaces.""" + return bool(self._call(self._raw.execute_command, "RENAME", source, target) == "OK") + + def watch_and_write( + self, + key: str, + field: str, + decide: Callable[[bytes | None], Sequence[Sequence[Any]]], + ) -> bool: + """Write the commands that `decide` gives in one MULTI/EXEC, unless `key` changed. + + The client WATCHes `key`, reads `field` of its hash as bytes, and gives the bytes to + `decide`. When `decide` gives no command, nothing is written. When another client changed + `key` after the WATCH, EXEC writes nothing. In both cases the result is False, and the + client does not try again, unlike `Valkey.transaction` of valkey-py, which tries again. + """ + # valkey-py's pipeline has no type hints. + pipe: Any = self._raw.pipeline(transaction=True) + with _valkey_failures(self.host, self.port, self.timeout), pipe: + pipe.watch(key) + value = pipe.execute_command("HGET", key, field, **{NEVER_DECODE: True}) + commands = decide(None if value is None else bytes(value)) + if not commands: + return False + pipe.multi() + for command in commands: + pipe.execute_command(*command) + try: + pipe.execute() + except valkey_exceptions.WatchError: + return False + return True + def close(self) -> None: """Close every connection the client holds.""" self._valkey.connection_pool.disconnect() From c1f8e252e782a80823a7e214451e10b0ce2e1ffe Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:31:42 +0000 Subject: [PATCH 05/20] test(valkey): add the tiered mapping of the project brain A shared read fills the in-process tier (T1), a down shared tier gives the source value and keeps the write in memory (T2), a value over 1 MiB stays in memory and each key has a TTL (T5), a value of an old kind or schema is read from the source (T6), and the counters send only fixed labels. Failed tests: - tests/valkey/test_tiered.py::test_a_shared_read_fills_the_memory_tier - tests/valkey/test_tiered.py::test_a_down_shared_tier_gives_the_source_value_and_keeps_the_write_in_memory - tests/valkey/test_tiered.py::test_an_oversize_value_stays_in_memory_and_each_key_has_a_ttl - tests/valkey/test_tiered.py::test_a_value_of_an_old_kind_or_schema_is_read_from_the_source - tests/valkey/test_tiered.py::test_the_brain_counters_send_only_fixed_labels --- tests/valkey/test_tiered.py | 227 ++++++++++++++++++++++++++++++++++++ 1 file changed, 227 insertions(+) create mode 100644 tests/valkey/test_tiered.py diff --git a/tests/valkey/test_tiered.py b/tests/valkey/test_tiered.py new file mode 100644 index 0000000000..21e5566fd1 --- /dev/null +++ b/tests/valkey/test_tiered.py @@ -0,0 +1,227 @@ +"""The tiered mapping of the project brain: an in-process tier over the shared Valkey tier (#4668). + +Each test runs the mapping over the in-memory Valkey (`shared_valkey`), whose server fails each +command while `connected` is False, and reads the counters of the mapping and of the cache tier +on the OTLP fake. A read that reached Valkey while the server was down counts a `connection` +error, and a read that the open breaker did not send counts `open`, so the counters show each +command that the mapping sent. +""" + +from __future__ import annotations + +import json +from typing import TYPE_CHECKING, Any + +from cachetools import cached +from fakeredis import FakeServer, FakeValkey +from pydantic import BaseModel, TypeAdapter + +from devops_cli.config.constants import CONST_VALKEY_BRAIN_PREFIX +from tests.support.fakes.otlp import FakeCollector + +if TYPE_CHECKING: + from devops_cli.valkey.tiered import TieredMapping + + from devops_cli.valkey.cache import ValkeyCacheTier + +_PREFIX = f"{CONST_VALKEY_BRAIN_PREFIX}:fact:test" +_TTL = 60 + + +class _Fact(BaseModel): + name: str + stars: int + + +def _facts(adapter: TypeAdapter[Any] | None = None) -> TieredMapping[Any]: + """A mapping of facts under `_PREFIX`, as a new process builds it. + + The import is local, so the module loads on a base without the mapping. + """ + from devops_cli.valkey.tiered import TieredMapping + + return TieredMapping(_PREFIX, adapter or TypeAdapter(_Fact), ttl=_TTL) + + +def _summed(otlp: FakeCollector, name: str, *labels: str) -> dict[tuple[str, ...], float]: + """The data points of the counter `name`, summed by the values of `labels`.""" + counted: dict[tuple[str, ...], float] = {} + for attributes, value in otlp.points(name): + point = tuple(attributes[label] for label in labels) + counted[point] = counted.get(point, 0) + value + return counted + + +def _reads(otlp: FakeCollector) -> dict[tuple[str, ...], float]: + from devops_cli.telemetry.instruments import BRAIN_READS_TOTAL + + return _summed(otlp, BRAIN_READS_TOTAL.name, "store", "result") + + +def _writes(otlp: FakeCollector) -> dict[tuple[str, ...], float]: + from devops_cli.telemetry.instruments import BRAIN_WRITES_TOTAL + + return _summed(otlp, BRAIN_WRITES_TOTAL.name, "store", "result") + + +def _errors(otlp: FakeCollector) -> dict[tuple[str, ...], float]: + from devops_cli.telemetry.instruments import VALKEY_CACHE_ERRORS_TOTAL + + return _summed(otlp, VALKEY_CACHE_ERRORS_TOTAL.name, "op", "error") + + +def _stored(server: FakeServer) -> dict[str, tuple[str, bool]]: + """Each key on the server, with its value and whether it has a TTL above 0.""" + reader = FakeValkey(server=server, decode_responses=True) + return {key: (reader.get(key), 0 < reader.ttl(key) <= _TTL) for key in reader.keys("*")} + + +def test_a_shared_read_fills_the_memory_tier( + shared_valkey: ValkeyCacheTier, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """T1: a second process reads the fact from Valkey once; its next read is from memory. + + The server is down for the second read, so a read that reached Valkey would count an error. + """ + fact = _Fact(name="tool", stars=3) + _facts()["tool"] = fact + otlp.clear() + reader = _facts() + + first = reader["tool"] + valkey_server.connected = False + second = reader["tool"] + + assert (first, second, _reads(otlp), _errors(otlp)) == ( + fact, + fact, + {("fact", "shared"): 1.0, ("fact", "memory"): 1.0}, + {}, + ) + + +def test_a_down_shared_tier_gives_the_source_value_and_keeps_the_write_in_memory( + shared_valkey: ValkeyCacheTier, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """T2: with Valkey down, each read goes to the source and each write stays in memory. + + One command reaches Valkey and fails; the open breaker sends no other command in the + cooldown, and no error reaches the caller. + """ + sources: list[str] = [] + + @cached(_facts()) + def read(name: str) -> _Fact: + sources.append(name) + return _Fact(name=name, stars=1) + + valkey_server.connected = False + results = [read("a"), read("b"), read("a")] + valkey_server.connected = True + + assert ( + [fact.name for fact in results], + sources, + _stored(valkey_server), + _reads(otlp), + _writes(otlp), + _errors(otlp), + ) == ( + ["a", "b", "a"], + ["a", "b"], + {}, + {("fact", "fallback"): 2.0, ("fact", "memory"): 1.0}, + {("fact", "skipped"): 2.0}, + {("get", "connection"): 1.0, ("get", "open"): 1.0, ("set", "open"): 2.0}, + ) + + +def test_an_oversize_value_stays_in_memory_and_each_key_has_a_ttl( + shared_valkey: ValkeyCacheTier, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """T5: a value whose encoded form is 1 MiB and one byte is not sent; a value of 1 KiB is, + with a TTL.""" + from devops_cli.config.defaults import DEFAULT_BRAIN_VALUE_MAX_BYTES + + texts = _facts(TypeAdapter(str)) + # The encoded form is the 16 characters of the schema key, a colon, and the JSON string. + big = "x" * (DEFAULT_BRAIN_VALUE_MAX_BYTES - len(texts.schema_key) - 1 - 2 + 1) + small = "y" * 1024 + texts["big"] = big + texts["small"] = small + + assert (texts["big"] == big, _stored(valkey_server), _writes(otlp)) == ( + True, + {f"{_PREFIX}:small": (f"{texts.schema_key}:{json.dumps(small)}", True)}, + {("fact", "oversize"): 1.0, ("fact", "shared"): 1.0}, + ) + + +def test_a_value_of_an_old_kind_or_schema_is_read_from_the_source( + shared_valkey: ValkeyCacheTier, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """T6: a fact under an older key version, and a fact under the current key with another + schema key, are misses; the source value replaces them under the current key.""" + old = _Fact(name="old", stars=0).model_dump_json() + writer = FakeValkey(server=valkey_server, decode_responses=True) + writer.set("valkey:brain:v0:fact:test:a", f"0000000000000000:{old}", ex=_TTL) + writer.set(f"{_PREFIX}:b", f"0123456789abcdef:{old}", ex=_TTL) + facts = _facts() + + @cached(facts) + def read(name: str) -> _Fact: + return _Fact(name=name, stars=2) + + results = [read("a"), read("b")] + fresh = {name: _Fact(name=name, stars=2).model_dump_json() for name in ("a", "b")} + + assert (results, _stored(valkey_server), _reads(otlp)) == ( + [_Fact(name="a", stars=2), _Fact(name="b", stars=2)], + { + "valkey:brain:v0:fact:test:a": (f"0000000000000000:{old}", True), + f"{_PREFIX}:a": (f"{facts.schema_key}:{fresh['a']}", True), + f"{_PREFIX}:b": (f"{facts.schema_key}:{fresh['b']}", True), + }, + {("fact", "source"): 2.0}, + ) + + +def test_the_brain_counters_send_only_fixed_labels( + shared_valkey: ValkeyCacheTier, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """The counters of a fact read with the shared tier up and one with it down hold only the + labels `store`, `result`, `op` and `error`, each with a value of a fixed set, and never the + name of the package.""" + from devops_cli.config.constants import BrainRead, BrainStore, BrainWrite, ValkeyCacheError + from devops_cli.telemetry.instruments import ( + BRAIN_READS_TOTAL, + BRAIN_WRITES_TOTAL, + VALKEY_CACHE_ERRORS_TOTAL, + ) + + @cached(_facts()) + def read(name: str) -> _Fact: + return _Fact(name=name, stars=1) + + read("secret-package-up") + valkey_server.connected = False + read("secret-package-down") + allowed = { + "store": {str(value) for value in BrainStore}, + "result": {str(value) for value in (*BrainRead, *BrainWrite)}, + "op": {"get", "set"}, + "error": {str(value) for value in ValkeyCacheError}, + } + points = [ + attributes + for name in (BRAIN_READS_TOTAL, BRAIN_WRITES_TOTAL, VALKEY_CACHE_ERRORS_TOTAL) + for attributes, _ in otlp.points(name.name) + ] + unbounded = [ + (label, value) + for attributes in points + for label, value in attributes.items() + if value not in allowed.get(label, set()) + ] + + assert (len(points) >= 3, unbounded) == (True, []) From c7a24984254c5cd33a628572f6922c1161ee894e Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:33:44 +0000 Subject: [PATCH 06/20] feat(valkey): add the tiered mapping of the project brain TieredMapping is a MutableMapping over an in-process TTLCache and the cache tier of the process, so cachetools.cached takes it as its cache. A shared hit fills the memory tier; a value with another schema key is a miss; a value over 1 MiB stays in memory; each key gets the TTL of the mapping. Each read and write adds one to the brain counters. --- .../design.md | 4 +- .../proposal.md | 4 +- .../tasks.md | 6 +- src/devops_cli/config/defaults.py | 8 + src/devops_cli/valkey/tiered.py | 196 ++++++++++++++++++ tests/conftest.py | 1 + tests/valkey/test_tiered.py | 9 +- 7 files changed, 216 insertions(+), 12 deletions(-) create mode 100644 src/devops_cli/valkey/tiered.py diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md index ac9d53ee4e..b7a793a73c 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md @@ -5,9 +5,9 @@ - **The memory bound of `valkey-devops` is `--maxmemory 256mb` inside a container limit of `384Mi`.**: The owner comment of 2026-11-19 on #4668 found four targets that do not agree (ADR 0023 line 134, #4624 item 6, the refined design of #4624, and the body of #4668). Only 256mb inside 384Mi keeps the owner decision 6 of #4624 (256 MB) and the rule of `openspec/specs/llm-valkey/spec.md` that `--maxmemory` is at most three quarters of the limit: 256 MiB is two thirds of 384Mi. The pull request comment on #4668 names this target and says that 240mb/320Mi and 256MB/320Mi in the bodies are replaced. The bodies of #4668 and #4624 stay as they are. - **ADR 0023 does not change.**: Its line 134 already says that the item raises the `maxmemory` of `valkey-devops` from 96 MB to 256 MB, which is the decided bound, and it names no limit. `docs/adr/README.md` forbids an edit of the body of an accepted record, and `tests/invariants/test_adr_records.py` fails on a changed body hash. A Status History line is only for a fact that a change makes wrong, and no fact of the record becomes wrong. The limit is a value of the manifest and of the spec of this change, as the length rule of the ADR README asks. - **The memory bound has a validator command and a live check as its proof, and no test.**: `docs/TESTING.md` forbids a test that asserts a value of a manifest, and the `test-tree` row refuses one (`tests/gate/tree_checks/config_values.py`). The proof is `uv run devops ci --check --only k8s` before the merge, and after the Argo CD sync `kubectl -n llm get deployment valkey-devops -o jsonpath=...` (the `--maxmemory 256mb` argument and the `384Mi` limit) and `redis_config_maxmemory{job="valkey-devops"}` at 268,435,456. -- **`TieredMapping` is a `MutableMapping` over a `cachetools.TTLCache` and the `ValkeyCacheTier`.**: No library gives a mapping over an in-process LRU and a Valkey tier with a breaker, a codec, a bound for each value and a schema check. As a `MutableMapping`, it plugs into `cachetools.cached`, so `_read_pypi` and `_linked_packages` keep their bodies and get a decorator. `__iter__` and `__len__` cover the in-process tier only, because a scan of the shared tier for each call has no use. +- **`TieredMapping` is a `MutableMapping` over a `cachetools.TTLCache` and the `ValkeyCacheTier`.**: No library gives a mapping over an in-process LRU and a Valkey tier with a breaker, a schema check and a bound for each value. As a `MutableMapping`, it plugs into `cachetools.cached`, so `_read_pypi` and `_linked_packages` keep their bodies and get a decorator. `__iter__` and `__len__` cover the in-process tier only, because a scan of the shared tier for each call has no use. - **A read goes memory, then Valkey, then the source, and a hit fills the tiers above it.**: ADR 0023 section 2 sets this order for content-addressed data. A write goes to Valkey and then to memory. A failed Valkey write is a later miss, never an error of the caller. -- **The mapping encodes each value through a pydantic `TypeAdapter` of its value type, and stores the schema key of that type with the value.**: A reader that finds another schema key, or a key of an older kind version, treats it as a miss, reads the source and writes the value under the current key. This is the rule of T6. The schema key is the first 16 hex characters of the sha256 of the JSON schema of the type, as `LISTING_SCHEMA_KEY` already does for the snapshot. +- **The mapping encodes each value through a pydantic `TypeAdapter` of its value type, and stores the schema key of that type in front of the value (`:`).**: The facts are small JSON texts, so the mapping does not compress them; the snapshot store compresses its records itself. The keys are text, so each `cachetools.cached` read gives a `key` function. A reader that finds another schema key, or a key of an older kind version, treats it as a miss, reads the source and writes the value under the current key. This is the rule of T6. The schema key is the first 16 hex characters of the sha256 of the JSON schema of the type, as `LISTING_SCHEMA_KEY` already does for the snapshot. - **A value over 1 MiB stays in the in-process tier.**: The mapping measures the encoded value before it sends it. Over the bound, it sends no command, keeps the value in memory and counts `devops_cli_brain_writes_total{result="oversize"}`. ADR 0023 section 2 says that a value over 1 MiB stays local. `cachetools.cached` ignores a `ValueError` on a write, so the mapping does not raise one. - **Each key has a TTL.**: Each write of the mapping sends `SET ... EX `, and each write of the snapshot store ends with `EXPIRE` in the same MULTI/EXEC. The facts get 24 hours (`DEFAULT_BRAIN_FACT_TTL_SECONDS`) and the snapshot 7 days (`DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS`). A temporary key of a full write gets 600 s, so a killed writer leaves no key without an end. - **`ValkeySnapshotStore` is the Valkey implementation of the `SnapshotStore` protocol.**: The protocol of #4552 is the seam that `IncrementalListing` reads, so no caller changes. `FileSnapshotStore` keeps one JSON file and cannot hold a shared copy. The hash `valkey:roadmap:v1:snapshot:/` holds the field `meta` (`schema`, `full_at`, `watermark`) and one zlib JSON `IssueRecord` for each issue number. One field for each record keeps each value under the bound: the snapshot of devops-cli is 14.13 MB with zlib, and its largest record is 23,700 B with zlib. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md index 02bf519d3e..47f89462db 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md @@ -11,7 +11,7 @@ - `src/devops_cli/valkey/client.py`: `ValkeyClient` gets the hash commands `hget`, `hset`, `hdel` and `hscan`, and `expire`, `unlink` and `rename`. A read of a binary value uses the `NEVER_DECODE` option of valkey-py, so a zlib value comes back as bytes. A new method `watch_and_write` runs one WATCH, a check of the current value, and one MULTI/EXEC, and it says when another client changed the key first. It does not retry. - `src/devops_cli/valkey/cache.py`: `ValkeyCacheTier` gets the same commands behind its circuit breaker. A command that fails, or that the open breaker does not send, is a miss or a skipped write, and the tier counts it in `devops_cli_valkey_cache_errors_total`. -- `src/devops_cli/valkey/tiered.py` (new): `TieredMapping`, a `MutableMapping` over an in-process `cachetools.TTLCache` and the shared `ValkeyCacheTier`. It has a key prefix, a value codec (JSON, or JSON and zlib) over a pydantic `TypeAdapter`, a TTL for each key, a bound of 1 MiB for each value, and the read and write counters. A read from the shared tier fills the in-process tier. A value of another schema is a miss. +- `src/devops_cli/valkey/tiered.py` (new): `TieredMapping`, a `MutableMapping` over an in-process `cachetools.TTLCache` and the shared `ValkeyCacheTier`. It has a key prefix, a JSON value with the schema key of its pydantic `TypeAdapter` in front, a TTL for each key, a bound of 1 MiB for each value, and the read and write counters. A read from the shared tier fills the in-process tier. A value of another schema is a miss. - `src/devops_cli/roadmap/stores/listing_shared.py` (new): `ValkeySnapshotStore` and `TieredSnapshotStore` behind the `SnapshotStore` protocol. The snapshot of a repository is one hash, `valkey:roadmap:v1:snapshot:/`, with the field `meta` and one zlib JSON `IssueRecord` for each issue, and a TTL of 7 days. A load reads the hash with `HSCAN COUNT 500` within a budget of 20 s. A writer writes only when its watermark is not older than the stored one, in one WATCH and MULTI/EXEC. A full read writes a temporary key and RENAMEs it. The store uses the shared copy and writes a key only for a public repository. - `src/devops_cli/roadmap/stores/listing_snapshot.py`: `intake_listing` and `lane_listing` give `IncrementalListing` a `TieredSnapshotStore` over the `FileSnapshotStore` of today and the shared tier of the process. The callers of the two factories do not change. - `src/devops_cli/roadmap/alternatives.py` and `src/devops_cli/roadmap/inventory.py`: the PyPI and deps.dev reads go through one fact `TieredMapping`, `valkey:brain:v1:fact::`, with a TTL of 24 hours. A miss reads the source. @@ -67,6 +67,6 @@ Each premise was checked on 2026-11-21 against `origin/main` at ddad1a45e and th - valkey-py 6.2.0 (in `uv.lock`) gives the client, the hash commands, `NEVER_DECODE` and the WATCH pipeline. pybreaker 1.4.1 gives the circuit breaker, which `ValkeyCacheTier` already wraps. cachetools 8.0.2 gives the in-process `TTLCache` and the `cached` decorator, which accepts any `MutableMapping` as its cache. The change uses each of them and adds no dependency. - The `SnapshotStore` protocol of #4552 is the seam: the two new stores implement it, and `IncrementalListing` and its callers do not change. -- No tool gives a mapping over an LRU and a Valkey tier with a breaker, a codec, a value bound and a schema check, or a snapshot store with a watermark guard. hishel is rejected: it is a shared cache by default, and the GitHub answers are private with `Vary: Authorization`. Page ETags are rejected for the listing: each new issue changes the ETag of every page (#4552). +- No tool gives a mapping over an LRU and a Valkey tier with a breaker, a schema check and a value bound, or a snapshot store with a watermark guard. hishel is rejected: it is a shared cache by default, and the GitHub answers are private with `Vary: Authorization`. Page ETags are rejected for the listing: each new issue changes the ETag of every page (#4552). - The change builds about 450 lines of code (the mapping, the two stores and the tier commands) and about 600 lines of tests. Cost, from the body: about 220,000 tokens and 6 hours to build. It keeps about 5,000 tokens a month and about 30,000 tokens for each fix. - Internal code that the change deletes: none. `FileSnapshotStore` stays as the local tier. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index 3a6f84e159..81bf122ed2 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -21,11 +21,11 @@ Adds: `ValkeyClient.hget`, `ValkeyClient.hset`, `ValkeyClient.hdel`, `ValkeyClie ## 3. Add the tiered mapping over the in-process tier and the shared tier Kind: behavior. Reads: `src/devops_cli/valkey/cache.py`, `src/devops_cli/core/clock.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/telemetry/instruments.py`, `tests/conftest.py`, `tests/support/fakes/valkey.py`, `tests/support/fakes/otlp.py`. Changes: `src/devops_cli/valkey/tiered.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/config/constants.py`, `tests/valkey/test_tiered.py`, `tests/conftest.py`. -Adds: `TieredMapping`, `reset_tiered_mappings`, `DEFAULT_BRAIN_VALUE_MAX_BYTES`, `DEFAULT_BRAIN_MEMORY_ENTRIES`, `DEFAULT_BRAIN_FACT_TTL_SECONDS` +Adds: `TieredMapping`, `reset_tiered_mappings`, `schema_key_of`, `count_read`, `count_write`, `DEFAULT_BRAIN_VALUE_MAX_BYTES`, `DEFAULT_BRAIN_MEMORY_ENTRIES`, `DEFAULT_BRAIN_FACT_TTL_SECONDS` -- [ ] 3.1 Write `tests/valkey/test_tiered.py`: `test_a_shared_read_fills_the_memory_tier` (T1); `test_a_down_shared_tier_gives_the_source_value_and_keeps_the_write_in_memory` (T2: `connected = False`, two reads through `cachetools.cached` within one cooldown, one command reaches the fake, `result="fallback"` and `result="skipped"` counted); `test_an_oversize_value_stays_in_memory_and_each_key_has_a_ttl` (T5: an encoded value of 1 MiB and one byte sends no command, and each key on the fake has a TTL above 0); `test_a_value_of_an_old_kind_or_schema_is_read_from_the_source` (T6); and `test_the_brain_counters_send_only_fixed_labels` for the requirement `The brain counters have bounded labels`, on the OTLP fake +- [x] 3.1 Write `tests/valkey/test_tiered.py`: `test_a_shared_read_fills_the_memory_tier` (T1); `test_a_down_shared_tier_gives_the_source_value_and_keeps_the_write_in_memory` (T2: `connected = False`, two reads through `cachetools.cached` within one cooldown, one command reaches the fake, `result="fallback"` and `result="skipped"` counted); `test_an_oversize_value_stays_in_memory_and_each_key_has_a_ttl` (T5: an encoded value of 1 MiB and one byte sends no command, and each key on the fake has a TTL above 0); `test_a_value_of_an_old_kind_or_schema_is_read_from_the_source` (T6); and `test_the_brain_counters_send_only_fixed_labels` for the requirement `The brain counters have bounded labels`, on the OTLP fake - Verification: `$ uv run devops ci test tests/valkey/test_tiered.py` fails on the base -- [ ] 3.2 Add `TieredMapping` to the new `src/devops_cli/valkey/tiered.py`: a `MutableMapping` with a key prefix, a pydantic `TypeAdapter` of its value type, a codec (`json` or `json+zlib`), a TTL, an in-process `cachetools.TTLCache` of `DEFAULT_BRAIN_MEMORY_ENTRIES`, and the tier of `shared_cache_tier()`, built on first use. Each value in Valkey holds the schema key of its type (the first 16 hex characters of the sha256 of its JSON schema); another schema key is a miss. A read counts `BRAIN_READS_TOTAL` and a write `BRAIN_WRITES_TOTAL`; a value over `DEFAULT_BRAIN_VALUE_MAX_BYTES` (1 MiB) stays in memory and counts `oversize`. `__iter__` and `__len__` cover the in-process tier. Each mapping joins a registry that `reset_tiered_mappings` clears, and `tests/conftest.py` adds `"devops_cli.valkey.tiered": ("reset_tiered_mappings",)` to `_PROCESS_STATE_RESETS`. Add the defaults and the key prefixes `valkey:brain:v1` and `valkey:roadmap:v1` +- [x] 3.2 Add `TieredMapping` to the new `src/devops_cli/valkey/tiered.py`: a `MutableMapping` with text keys, a key prefix, a pydantic `TypeAdapter` of its value type, a JSON value with its schema key in front (`:`), a TTL, an in-process `cachetools.TTLCache` of `DEFAULT_BRAIN_MEMORY_ENTRIES`, and the tier of `shared_cache_tier()`, built on first use. Each value in Valkey holds the schema key of its type (the first 16 hex characters of the sha256 of its JSON schema); another schema key is a miss. A read counts `BRAIN_READS_TOTAL` and a write `BRAIN_WRITES_TOTAL`; a value over `DEFAULT_BRAIN_VALUE_MAX_BYTES` (1 MiB) stays in memory and counts `oversize`. `__iter__` and `__len__` cover the in-process tier. Each mapping joins a registry that `reset_tiered_mappings` clears, and `tests/conftest.py` adds `"devops_cli.valkey.tiered": ("reset_tiered_mappings",)` to `_PROCESS_STATE_RESETS`. Add the defaults and the key prefixes `valkey:brain:v1` and `valkey:roadmap:v1` (`CONST_VALKEY_BRAIN_PREFIX`, `CONST_VALKEY_ROADMAP_PREFIX`) - Verification: `$ uv run devops ci test tests/valkey/test_tiered.py` passes ## 4. Share the listing snapshot through the shared tier diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 0cc4184cbc..76572a93d9 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -733,6 +733,14 @@ # 2026-10-29: a loopback connect took at most 0.6 ms, and a connect to a Service on another node # of the homelab took at most 0.4 ms, so the bound is more than 400 times the slowest connect. DEFAULT_VALKEY_CACHE_CONNECT_TIMEOUT_SECONDS: float = 0.25 +# The project brain in the cache Valkey (#4668, ADR 0023 section 2). A value whose encoded form is +# over this bound stays in the in-process tier: ADR 0023 section 2 sets 1 MiB. +DEFAULT_BRAIN_VALUE_MAX_BYTES: int = 1_048_576 +# The entries of the in-process tier of one tiered mapping. A PyPI fact holds about 1 KB, so a +# full tier holds about 1 MB. +DEFAULT_BRAIN_MEMORY_ENTRIES: int = 1024 +# How long a tool fact of PyPI or deps.dev is kept, in memory and in Valkey: 24 hours. +DEFAULT_BRAIN_FACT_TTL_SECONDS: int = 86_400 # Commands wait at most this long on the run index before keeping a run locally only. DEFAULT_RUNS_INDEX_TIMEOUT_SECONDS: float = 2.0 diff --git a/src/devops_cli/valkey/tiered.py b/src/devops_cli/valkey/tiered.py new file mode 100644 index 0000000000..1b52595bae --- /dev/null +++ b/src/devops_cli/valkey/tiered.py @@ -0,0 +1,196 @@ +"""The tiered mapping of the project brain: an in-process tier over the shared Valkey tier (#4668). + +ADR 0023 section 2 sets the tiers of a fact that each process reads the same: the memory of the +process, then the cache Valkey `valkey-devops`, then the source. `TieredMapping` is a +`MutableMapping`, so `cachetools.cached` takes it as its cache and the decorated read stays as it +is. The keys are text, so `cached` gets a `key` function that gives the text of the key, such as +`packaging.utils.canonicalize_name`, in place of its default tuple: + +- A read looks in memory, then in Valkey. A Valkey hit fills the memory tier. A miss in both + raises `KeyError`, and `cached` reads the source and writes the value. +- A write keeps the value in memory and sends it to Valkey with the TTL of the mapping. A value + whose encoded form is over `DEFAULT_BRAIN_VALUE_MAX_BYTES` stays in memory. +- The Valkey tier is the one tier of the process (`shared_cache_tier`), behind its circuit + breaker. While Valkey fails, a read goes to the source and a write stays in memory; no error + reaches the caller. + +A value in Valkey is `:`. The schema key is the first 16 hex characters of the +sha256 of the JSON schema of the value type, as `LISTING_SCHEMA_KEY` is for the listing snapshot. +A value with another schema key is a miss, so a release that changes the type reads the source +again and writes the value under its own key. The prefix holds the version of the key kind, so a +new version never reads a key of an older one. + +`__iter__` and `__len__` cover the memory tier only: a scan of Valkey for each call has no use. +Each read adds one to `devops_cli_brain_reads_total` and each write one to +`devops_cli_brain_writes_total`, with the store of the mapping and the result, never the key. +""" + +from __future__ import annotations + +import hashlib +import json +import logging +import threading +import weakref +from collections.abc import Iterator, MutableMapping +from typing import Any, Final + +from cachetools import TTLCache +from pydantic import TypeAdapter, ValidationError + +from devops_cli.config.constants import BrainRead, BrainStore, BrainWrite +from devops_cli.config.defaults import DEFAULT_BRAIN_MEMORY_ENTRIES, DEFAULT_BRAIN_VALUE_MAX_BYTES +from devops_cli.core import clock +from devops_cli.telemetry.instruments import BRAIN_READS_TOTAL, BRAIN_WRITES_TOTAL, emit +from devops_cli.valkey.cache import shared_cache_tier + +logger = logging.getLogger(__name__) + +# The text between the schema key and the JSON of a value, and between the prefix and a key. +_SEPARATOR: Final = ":" +# The length of a schema key, in hex characters. +_SCHEMA_KEY_CHARS: Final = 16 + +# Each mapping of the process by its id, so `reset_tiered_mappings` empties their memory tiers. A +# mapping compares as a mapping and has no hash, so a weak set cannot hold it. +_MAPPINGS: weakref.WeakValueDictionary[int, TieredMapping[Any]] = weakref.WeakValueDictionary() + + +def schema_key_of(adapter: TypeAdapter[Any]) -> str: + """The first 16 hex characters of the sha256 of the JSON schema of the type of `adapter`.""" + schema = json.dumps(adapter.json_schema(), sort_keys=True) + return hashlib.sha256(schema.encode()).hexdigest()[:_SCHEMA_KEY_CHARS] + + +def count_read(store: BrainStore, result: BrainRead) -> None: + """Add one read of `store` to `devops_cli_brain_reads_total`.""" + emit(BRAIN_READS_TOTAL, 1, {"store": store.value, "result": result.value}) + + +def count_write(store: BrainStore, result: BrainWrite) -> None: + """Add one write of `store` to `devops_cli_brain_writes_total`.""" + emit(BRAIN_WRITES_TOTAL, 1, {"store": store.value, "result": result.value}) + + +def _monotonic() -> float: + """The clock of the memory tier: the clock seam, which the `clock` fixture of the tests moves.""" + return clock.monotonic() + + +class TieredMapping[V](MutableMapping[str, V]): + """Values of one type under one key prefix, in the memory of the process and in Valkey. + + `prefix` is the key prefix in Valkey, such as `valkey:brain:v1:fact:pypi`, and the key of a + value is `:`. `adapter` validates and encodes the values. Each value lives `ttl` + seconds in memory and in Valkey. `store` is the label of the counters. + """ + + def __init__( + self, + prefix: str, + adapter: TypeAdapter[V], + *, + ttl: int, + store: BrainStore = BrainStore.FACT, + entries: int = DEFAULT_BRAIN_MEMORY_ENTRIES, + ) -> None: + self.prefix = prefix + self.ttl = ttl + self.store = store + self._adapter = adapter + self._schema_key: str | None = None + self._memory: TTLCache[str, V] = TTLCache(maxsize=entries, ttl=ttl, timer=_monotonic) + self._lock = threading.Lock() + _MAPPINGS[id(self)] = self + + @property + def schema_key(self) -> str: + """The schema key of the value type, which each value in Valkey starts with.""" + if self._schema_key is None: + self._schema_key = schema_key_of(self._adapter) + return self._schema_key + + def shared_key(self, key: str) -> str: + """The Valkey key of `key`.""" + return f"{self.prefix}{_SEPARATOR}{key}" + + def __getitem__(self, key: str) -> V: + with self._lock: + held = [self._memory[key]] if key in self._memory else [] + if held: + count_read(self.store, BrainRead.MEMORY) + return held[0] + tier = shared_cache_tier() + text = None if tier is None else tier.get(self.shared_key(key)) + found = [] if text is None else self._decoded(text) + if found: + with self._lock: + self._memory[key] = found[0] + count_read(self.store, BrainRead.SHARED) + return found[0] + down = tier is None or tier.is_open + count_read(self.store, BrainRead.FALLBACK if down else BrainRead.SOURCE) + raise KeyError(key) + + def __setitem__(self, key: str, value: V) -> None: + with self._lock: + self._memory[key] = value + encoded = self.schema_key.encode() + _SEPARATOR.encode() + self._adapter.dump_json(value) + if len(encoded) > DEFAULT_BRAIN_VALUE_MAX_BYTES: + count_write(self.store, BrainWrite.OVERSIZE) + return + tier = shared_cache_tier() + sent = tier is not None and tier.set(self.shared_key(key), encoded.decode(), ex=self.ttl) + count_write(self.store, BrainWrite.SHARED if sent else BrainWrite.SKIPPED) + + def __delitem__(self, key: str) -> None: + with self._lock: + self._memory.pop(key, None) + tier = shared_cache_tier() + if tier is not None: + tier.unlink(self.shared_key(key)) + + def __iter__(self) -> Iterator[str]: + with self._lock: + keys = list(self._memory) + return iter(keys) + + def __len__(self) -> int: + with self._lock: + return len(self._memory) + + def clear_memory(self) -> None: + """Empty the memory tier, as a new process starts; Valkey keeps its values.""" + with self._lock: + self._memory.clear() + + def _decoded(self, text: str) -> list[V]: + """The value that `text` from Valkey holds, or nothing for another schema key or a value + that does not validate.""" + schema, separator, body = text.partition(_SEPARATOR) + if not separator or schema != self.schema_key: + return [] + try: + return [self._adapter.validate_json(body)] + except ValidationError as exc: + logger.debug( + "A value of %s in Valkey does not validate, so the read is a miss: %s", + self.prefix, + exc.error_count(), + ) + return [] + + +def reset_tiered_mappings() -> None: + """Empty the memory tier of each mapping of the process.""" + for mapping in list(_MAPPINGS.values()): + mapping.clear_memory() + + +__all__ = [ + "TieredMapping", + "count_read", + "count_write", + "reset_tiered_mappings", + "schema_key_of", +] diff --git a/tests/conftest.py b/tests/conftest.py index f7b9498741..042ee3ddc5 100755 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -155,6 +155,7 @@ def isolate_kubeconfig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Non "devops_cli.telemetry.tracer": ("clear_span_buffer", "remove_exporter", "reset_tracer"), "devops_cli.valkey.cache": ("reset_shared_cache_tier",), "devops_cli.valkey.client": ("reset_valkey_client",), + "devops_cli.valkey.tiered": ("reset_tiered_mappings",), } diff --git a/tests/valkey/test_tiered.py b/tests/valkey/test_tiered.py index 21e5566fd1..fe1b114a50 100644 --- a/tests/valkey/test_tiered.py +++ b/tests/valkey/test_tiered.py @@ -20,9 +20,8 @@ from tests.support.fakes.otlp import FakeCollector if TYPE_CHECKING: - from devops_cli.valkey.tiered import TieredMapping - from devops_cli.valkey.cache import ValkeyCacheTier + from devops_cli.valkey.tiered import TieredMapping _PREFIX = f"{CONST_VALKEY_BRAIN_PREFIX}:fact:test" _TTL = 60 @@ -110,7 +109,7 @@ def test_a_down_shared_tier_gives_the_source_value_and_keeps_the_write_in_memory """ sources: list[str] = [] - @cached(_facts()) + @cached(_facts(), key=str) def read(name: str) -> _Fact: sources.append(name) return _Fact(name=name, stars=1) @@ -168,7 +167,7 @@ def test_a_value_of_an_old_kind_or_schema_is_read_from_the_source( writer.set(f"{_PREFIX}:b", f"0123456789abcdef:{old}", ex=_TTL) facts = _facts() - @cached(facts) + @cached(facts, key=str) def read(name: str) -> _Fact: return _Fact(name=name, stars=2) @@ -199,7 +198,7 @@ def test_the_brain_counters_send_only_fixed_labels( VALKEY_CACHE_ERRORS_TOTAL, ) - @cached(_facts()) + @cached(_facts(), key=str) def read(name: str) -> _Fact: return _Fact(name=name, stars=1) From 3c7aefc4e0c14ec27120ebe4728a2381f81d1c1a Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:37:05 +0000 Subject: [PATCH 07/20] test(roadmap): share the listing snapshot through the cache Valkey A cold process reads the shared snapshot and one page of changes, the newer of the two copies gives the watermark, a round with the shared tier down reads the local file (T2), a trial after the cooldown and a lost WATCH transaction (T4), an older watermark and a full read, no key of a private repository, no visibility read without the shared tier, and a shared load past its budget. Failed tests: - tests/roadmap/stores/test_listing_shared.py::test_a_cold_process_reads_the_shared_snapshot_and_at_most_two_pages - tests/roadmap/stores/test_listing_shared.py::test_the_newer_copy_of_the_two_tiers_gives_the_watermark - tests/roadmap/stores/test_listing_shared.py::test_a_round_with_the_shared_tier_down_reads_the_local_file - tests/roadmap/stores/test_listing_shared.py::test_a_trial_after_the_cooldown_lets_the_newer_snapshot_replace_the_older - tests/roadmap/stores/test_listing_shared.py::test_an_older_writer_loses_its_watch_transaction - tests/roadmap/stores/test_listing_shared.py::test_an_older_watermark_does_not_replace_the_shared_snapshot - tests/roadmap/stores/test_listing_shared.py::test_a_full_read_replaces_the_shared_snapshot_whole - tests/roadmap/stores/test_listing_shared.py::test_no_key_of_a_private_repository_is_written - tests/roadmap/stores/test_listing_shared.py::test_no_visibility_read_without_the_shared_tier - tests/roadmap/stores/test_listing_shared.py::test_a_shared_load_past_its_budget_falls_back --- tests/roadmap/stores/test_listing_shared.py | 505 ++++++++++++++++++++ 1 file changed, 505 insertions(+) create mode 100644 tests/roadmap/stores/test_listing_shared.py diff --git a/tests/roadmap/stores/test_listing_shared.py b/tests/roadmap/stores/test_listing_shared.py new file mode 100644 index 0000000000..c6fe05ff43 --- /dev/null +++ b/tests/roadmap/stores/test_listing_shared.py @@ -0,0 +1,505 @@ +"""The listing snapshot shared through the cache Valkey, over the local file of each process (#4668). + +Each test reads the listing through `IncrementalListing` and a `GitHubRoadmapStore` on the GitHub +API fake, with a `TieredSnapshotStore` over a local directory and the in-memory Valkey of +`shared_valkey`. A new process is a new `TieredSnapshotStore` after `reset_shared_snapshots`, +which drops the state of the shared store and the visibility answers of the process. The counters +are read on the OTLP fake. +""" + +from __future__ import annotations + +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import pytest +from fakeredis import FakeServer, FakeValkey + +from devops_cli.github.session import get_github_session +from devops_cli.roadmap.stores.github_store import GitHubRoadmapStore +from devops_cli.roadmap.stores.listing_snapshot import ( + LISTING_SCHEMA_KEY, + FileSnapshotStore, + IncrementalListing, + ListingSnapshot, +) +from devops_cli.roadmap.stores.store import IssueRecord +from devops_cli.valkey.cache import ValkeyCacheTier +from tests.support.fakes.clock import ClockFake +from tests.support.fakes.github import GitHubApiFake, github_json +from tests.support.fakes.otlp import FakeCollector +from tests.support.fakes.valkey import valkey_client_on +from tests.support.roadmap_github_store import REPO, RecordedGh, issue_payload + +if TYPE_CHECKING: + from devops_cli.roadmap.stores.listing_shared import TieredSnapshotStore, ValkeySnapshotStore + +STARTED = datetime(2026, 1, 1, 10, 0, tzinfo=UTC) +REPOSITORY_URL = f"https://api.github.com/repos/{REPO}" +FULL = f"/repos/{REPO}/issues?state=all&per_page=100" +SNAPSHOT_KEY = f"valkey:roadmap:v1:snapshot:{REPO}" + + +def _since(at: str) -> str: + """The path of the read of the issues changed since `at`, newest change first.""" + return f"/repos/{REPO}/issues?state=all&sort=updated&direction=desc&since={at}&per_page=100" + + +def _issue(number: int, *, updated: str = "2026-01-01T09:00:00Z", **changes: Any) -> Any: + """Issue `number` as the listing gives it, last changed at `updated`.""" + return issue_payload( + number, updated_at=updated, repository_url=REPOSITORY_URL, body="Text", **changes + ) + + +def _public(repo: str) -> bool: + return True + + +def _tiered( + root: Path, + *, + at: datetime = STARTED, + is_public: Callable[[str], bool] = _public, + shared: Callable[[], ValkeySnapshotStore | None] | None = None, +) -> TieredSnapshotStore: + """The tiered store of a process at `at`, over the local directory `root`. + + The import is local, so the module loads on a base without the store. + """ + from devops_cli.roadmap.stores.listing_shared import TieredSnapshotStore, shared_snapshot_store + + return TieredSnapshotStore( + FileSnapshotStore(root), + shared=shared or shared_snapshot_store, + is_public=is_public, + clock=lambda: at, + ) + + +def _round( + tiered: TieredSnapshotStore, *, at: datetime = STARTED, full: bool = False +) -> list[IssueRecord]: + """One listing round at `at` through `tiered`: every issue, the newest first.""" + listing = IncrementalListing(tiered, full=full, clock=lambda: at) + store = GitHubRoadmapStore( + REPO, runner=RecordedGh({}), session=get_github_session(), listing=listing + ) + return list(store.issues()) + + +def _new_process() -> None: + from devops_cli.roadmap.stores.listing_shared import reset_shared_snapshots + + reset_shared_snapshots() + + +def _valkey_store(tier: ValkeyCacheTier) -> ValkeySnapshotStore: + from devops_cli.roadmap.stores.listing_shared import ValkeySnapshotStore + + return ValkeySnapshotStore(tier) + + +def _snapshot(watermark: datetime, *numbers: int, full_at: datetime = STARTED) -> ListingSnapshot: + """A snapshot of the issues `numbers`, read in full at `full_at`, with `watermark`.""" + records = tuple( + IssueRecord( + number=number, + title=f"Issue {number}", + url=f"https://github.com/{REPO}/issues/{number}", + body="Text", + updated_at=STARTED - timedelta(hours=1), + ) + for number in numbers + ) + return ListingSnapshot( + repo=REPO, + schema_key=LISTING_SCHEMA_KEY, + full_at=full_at, + watermark=watermark, + issues=records, + ) + + +def _shared(server: FakeServer) -> tuple[str | None, list[str]]: + """The watermark of the shared snapshot and the numbers of its issues, the highest first.""" + import json + + reader = FakeValkey(server=server, decode_responses=True) + meta = reader.hget(SNAPSHOT_KEY, "meta") + numbers = sorted((f for f in reader.hkeys(SNAPSHOT_KEY) if f != "meta"), key=int, reverse=True) + return (None if meta is None else json.loads(meta)["watermark"]), numbers + + +def _keys(server: FakeServer) -> list[str]: + return sorted(FakeValkey(server=server, decode_responses=True).keys("*")) + + +def _queries(github_api: GitHubApiFake) -> list[dict[str, str]]: + return [dict(request.url.params) for request in github_api.sent] + + +def _summed(otlp: FakeCollector, name: str, *labels: str) -> dict[tuple[str, ...], float]: + counted: dict[tuple[str, ...], float] = {} + for attributes, value in otlp.points(name): + point = tuple(attributes[label] for label in labels) + counted[point] = counted.get(point, 0) + value + return counted + + +def _reads(otlp: FakeCollector) -> dict[tuple[str, ...], float]: + from devops_cli.telemetry.instruments import BRAIN_READS_TOTAL + + return _summed(otlp, BRAIN_READS_TOTAL.name, "store", "result") + + +def _writes(otlp: FakeCollector) -> dict[tuple[str, ...], float]: + from devops_cli.telemetry.instruments import BRAIN_WRITES_TOTAL + + return _summed(otlp, BRAIN_WRITES_TOTAL.name, "store", "result") + + +def _errors(otlp: FakeCollector) -> dict[tuple[str, ...], float]: + from devops_cli.telemetry.instruments import VALKEY_CACHE_ERRORS_TOTAL + + return _summed(otlp, VALKEY_CACHE_ERRORS_TOTAL.name, "op", "error") + + +def _saved(otlp: FakeCollector) -> dict[tuple[str, ...], float]: + from devops_cli.telemetry.instruments import BRAIN_GITHUB_REQUESTS_SAVED_TOTAL + + return _summed(otlp, BRAIN_GITHUB_REQUESTS_SAVED_TOTAL.name, "store") + + +def _labels_with_a_name(otlp: FakeCollector) -> list[str]: + """Each label value of the brain counters that names the repository or holds a number.""" + from devops_cli.telemetry.instruments import ( + BRAIN_GITHUB_REQUESTS_SAVED_TOTAL, + BRAIN_READS_TOTAL, + BRAIN_WRITES_TOTAL, + VALKEY_CACHE_ERRORS_TOTAL, + ) + + names = ( + BRAIN_READS_TOTAL, + BRAIN_WRITES_TOTAL, + VALKEY_CACHE_ERRORS_TOTAL, + BRAIN_GITHUB_REQUESTS_SAVED_TOTAL, + ) + return [ + f"{label}={value}" + for name in names + for attributes, _ in otlp.points(name.name) + for label, value in attributes.items() + if label not in {"store", "result", "op", "error"} + or "/" in value + or any(character.isdigit() for character in value) + ] + + +@pytest.mark.usefixtures("shared_valkey") +def test_a_cold_process_reads_the_shared_snapshot_and_at_most_two_pages( + github_api: GitHubApiFake, tmp_path: Path, otlp: FakeCollector +) -> None: + """A process with no local snapshot starts from the shared one, reads one page of changes, + and counts the 3 pages of the full read that it did not send.""" + github_api.route("GET", FULL, github_json([_issue(n) for n in range(250, 0, -1)])) + _round(_tiered(tmp_path / "first")) + _new_process() + github_api.sent.clear() + otlp.clear() + changed = [_issue(n, updated="2026-01-01T10:30:00Z", title=f"new title {n}") for n in (3, 2, 1)] + github_api.route("GET", _since("2026-01-01T08:59:00Z"), github_json(changed)) + later = STARTED + timedelta(hours=1) + + issues = _round(_tiered(tmp_path / "cold", at=later), at=later) + + kept = FileSnapshotStore(tmp_path / "cold").load(REPO) + titles = {issue.number: issue.title for issue in issues} + assert ( + [query.get("since") for query in _queries(github_api)], + len(issues), + [titles[n] for n in (1, 2, 3)], + None if kept is None else len(kept.issues), + _saved(otlp), + _reads(otlp), + _labels_with_a_name(otlp), + ) == ( + ["2026-01-01T08:59:00Z"], + 250, + ["new title 1", "new title 2", "new title 3"], + 250, + {("snapshot",): 3.0}, + {("snapshot", "shared"): 1.0}, + [], + ) + + +def test_the_newer_copy_of_the_two_tiers_gives_the_watermark( + github_api: GitHubApiFake, tmp_path: Path, shared_valkey: ValkeyCacheTier +) -> None: + """The local copy has the watermark 09:00 and the shared copy 10:00: the read starts at 10:00.""" + FileSnapshotStore(tmp_path).save(_snapshot(STARTED - timedelta(hours=1), 2, 1)) + _valkey_store(shared_valkey).save(_snapshot(STARTED, 3, 2, 1)) + github_api.route("GET", _since("2026-01-01T10:00:00Z"), github_json([])) + later = STARTED + timedelta(hours=1) + + numbers = [issue.number for issue in _round(_tiered(tmp_path, at=later), at=later)] + + assert ([query.get("since") for query in _queries(github_api)], numbers) == ( + ["2026-01-01T10:00:00Z"], + [3, 2, 1], + ) + + +def test_a_round_with_the_shared_tier_down_reads_the_local_file( + github_api: GitHubApiFake, + tmp_path: Path, + valkey_server: FakeServer, + shared_valkey: ValkeyCacheTier, + otlp: FakeCollector, +) -> None: + """T2: the round reads the changes since the local watermark and keeps the new local file; + one command reaches Valkey, and the round reads no visibility.""" + FileSnapshotStore(tmp_path).save(_snapshot(STARTED - timedelta(minutes=1), 2, 1)) + github_api.route( + "GET", + _since("2026-01-01T09:59:00Z"), + github_json([_issue(3, updated="2026-01-01T10:30:00Z")]), + ) + asked: list[str] = [] + + def is_public(repo: str) -> bool: + asked.append(repo) + return True + + valkey_server.connected = False + later = STARTED + timedelta(hours=1) + numbers = [i.number for i in _round(_tiered(tmp_path, at=later, is_public=is_public), at=later)] + kept = FileSnapshotStore(tmp_path).load(REPO) + + assert ( + numbers, + None if kept is None else [i.number for i in kept.issues], + asked, + _reads(otlp), + _writes(otlp), + _errors(otlp), + ) == ( + [3, 2, 1], + [3, 2, 1], + [], + {("snapshot", "fallback"): 1.0}, + {("snapshot", "skipped"): 1.0}, + {("hget", "connection"): 1.0, ("hget", "open"): 1.0}, + ) + + +def test_a_trial_after_the_cooldown_lets_the_newer_snapshot_replace_the_older( + tmp_path: Path, + valkey_server: FakeServer, + shared_valkey: ValkeyCacheTier, + clock: ClockFake, +) -> None: + """T4: the breaker is open; after the cooldown the save is the trial, which closes it, and + the snapshot of watermark 10:00 replaces the one of 09:00.""" + from devops_cli.config.defaults import DEFAULT_VALKEY_CACHE_BREAKER_COOLDOWN_SECONDS + + _valkey_store(shared_valkey).save(_snapshot(STARTED - timedelta(hours=1), 1)) + valkey_server.connected = False + tiered = _tiered(tmp_path) + tiered.load(REPO) + valkey_server.connected = True + in_the_cooldown = (shared_valkey.is_open, _shared(valkey_server)[0]) + clock.shift(DEFAULT_VALKEY_CACHE_BREAKER_COOLDOWN_SECONDS) + + tiered.save(_snapshot(STARTED, 2, 1)) + + assert (in_the_cooldown, shared_valkey.is_open, _shared(valkey_server)) == ( + (True, "2026-01-01T09:00:00Z"), + False, + ("2026-01-01T10:00:00Z", ["2", "1"]), + ) + + +class _RacingTier(ValkeyCacheTier): + """A cache tier whose WATCH transaction lets another writer write before its EXEC.""" + + def __init__(self, server: FakeServer, race: Callable[[], None]) -> None: + super().__init__(valkey_client_on(server)) + self._race = race + + def watch_and_write( + self, key: str, field: str, decide: Callable[[bytes | None], Any] + ) -> bool | None: + def racing(meta: bytes | None) -> Any: + commands = decide(meta) + self._race() + return commands + + return super().watch_and_write(key, field, racing) + + +def test_an_older_writer_loses_its_watch_transaction( + tmp_path: Path, valkey_server: FakeServer, shared_valkey: ValkeyCacheTier, otlp: FakeCollector +) -> None: + """T4: a writer of watermark 10:15 reads the shared watermark 10:00, and another client + writes 10:30 before its EXEC. Its transaction writes nothing, it does not try again, and it + leaves no temporary key.""" + _valkey_store(shared_valkey).save(_snapshot(STARTED, 1)) + other = _valkey_store(ValkeyCacheTier(valkey_client_on(valkey_server))) + racing = _RacingTier( + valkey_server, lambda: other.save(_snapshot(STARTED + timedelta(minutes=30), 3, 1)) + ) + otlp.clear() + + _tiered(tmp_path, shared=lambda: _valkey_store(racing)).save( + _snapshot(STARTED + timedelta(minutes=15), 2, 1) + ) + + assert (_shared(valkey_server), _keys(valkey_server), _writes(otlp)) == ( + ("2026-01-01T10:30:00Z", ["3", "1"]), + [SNAPSHOT_KEY], + {("snapshot", "older"): 1.0, ("snapshot", "shared"): 1.0}, + ) + + +@pytest.mark.usefixtures("shared_valkey") +def test_an_older_watermark_does_not_replace_the_shared_snapshot( + tmp_path: Path, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """The shared snapshot of 10:00 keeps its watermark and records; the local file takes 09:00.""" + _tiered(tmp_path / "newer").save(_snapshot(STARTED, 2, 1)) + otlp.clear() + + _tiered(tmp_path / "older").save(_snapshot(STARTED - timedelta(hours=1), 1)) + + kept = FileSnapshotStore(tmp_path / "older").load(REPO) + assert ( + _shared(valkey_server), + None if kept is None else kept.watermark, + _writes(otlp), + ) == ( + ("2026-01-01T10:00:00Z", ["2", "1"]), + STARTED - timedelta(hours=1), + {("snapshot", "older"): 1.0}, + ) + + +@pytest.mark.usefixtures("shared_valkey") +def test_a_full_read_replaces_the_shared_snapshot_whole( + github_api: GitHubApiFake, tmp_path: Path, valkey_server: FakeServer +) -> None: + """Issue 2 left the repository: the full read lists 1 and 3, and the shared snapshot holds + only them, with no temporary key left.""" + github_api.route("GET", FULL, github_json([_issue(3), _issue(2), _issue(1)])) + _round(_tiered(tmp_path)) + github_api.route( + "GET", FULL, github_json([_issue(3, updated="2026-01-01T09:30:00Z"), _issue(1)]) + ) + later = STARTED + timedelta(hours=1) + + _round(_tiered(tmp_path, at=later), at=later, full=True) + + assert (_shared(valkey_server), _keys(valkey_server)) == ( + ("2026-01-01T09:29:00Z", ["3", "1"]), + [SNAPSHOT_KEY], + ) + + +@pytest.mark.usefixtures("shared_valkey") +def test_no_key_of_a_private_repository_is_written( + github_api: GitHubApiFake, tmp_path: Path, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """A round for a private repository and a round whose visibility read fails write no key + and use no shared copy; each counts `private`.""" + from devops_cli.roadmap.stores.listing_shared import repository_is_public + + private = RecordedGh({"isPrivate": {"data": {"repository": {"isPrivate": True}}}}) + failing = RecordedGh({"isPrivate": (1, "HTTP 502: Bad Gateway")}) + github_api.route("GET", FULL, github_json([_issue(2), _issue(1)])) + github_api.route("GET", _since("2026-01-01T08:59:00Z"), github_json([])) + + _round(_tiered(tmp_path, is_public=lambda repo: repository_is_public(repo, runner=private))) + _new_process() + later = STARTED + timedelta(hours=1) + _round( + _tiered( + tmp_path, at=later, is_public=lambda repo: repository_is_public(repo, runner=failing) + ), + at=later, + ) + + assert ( + _keys(valkey_server), + len(private.calls), + len(failing.calls), + _reads(otlp), + _writes(otlp), + ) == ( + [], + 1, + 1, + {("snapshot", "private"): 2.0}, + {("snapshot", "private"): 2.0}, + ) + + +def test_no_visibility_read_without_the_shared_tier( + github_api: GitHubApiFake, + tmp_path: Path, + valkey_server: FakeServer, + shared_valkey: ValkeyCacheTier, +) -> None: + from devops_cli.roadmap.stores.listing_shared import repository_is_public + + runner = RecordedGh({}) + github_api.route("GET", FULL, github_json([_issue(1)])) + valkey_server.connected = False + + _round(_tiered(tmp_path, is_public=lambda repo: repository_is_public(repo, runner=runner))) + + assert runner.calls == [] + + +class _SlowTier(ValkeyCacheTier): + """A cache tier whose second `HSCAN` takes 21 s on the `clock` fixture.""" + + def __init__(self, server: FakeServer, clock: ClockFake) -> None: + super().__init__(valkey_client_on(server)) + self._clock = clock + self.scans = 0 + + def hscan(self, key: str, cursor: int, count: int) -> tuple[int, dict[str, bytes]] | None: + self.scans += 1 + step = super().hscan(key, cursor, count) + if self.scans == 2: + self._clock.shift(21) + return step + + +def test_a_shared_load_past_its_budget_falls_back( + tmp_path: Path, + valkey_server: FakeServer, + shared_valkey: ValkeyCacheTier, + clock: ClockFake, + otlp: FakeCollector, +) -> None: + """The load of a shared snapshot of 1,200 records stops after the second `HSCAN`, and the + reader takes the local snapshot.""" + local = _snapshot(STARTED - timedelta(hours=1), 1) + FileSnapshotStore(tmp_path).save(local) + _valkey_store(shared_valkey).save(_snapshot(STARTED, *range(1200, 0, -1))) + slow = _SlowTier(valkey_server, clock) + otlp.clear() + + loaded = _tiered(tmp_path, shared=lambda: _valkey_store(slow)).load(REPO) + + assert (loaded, slow.scans, _errors(otlp), _reads(otlp)) == ( + local, + 2, + {("hscan", "budget"): 1.0}, + {("snapshot", "fallback"): 1.0}, + ) From a58480983f0c605d06bede29458b494bd6f849d1 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:48:27 +0000 Subject: [PATCH 08/20] feat(roadmap): share the listing snapshot through the cache Valkey ValkeySnapshotStore keeps the snapshot of a repository in one hash of zlib JSON records with a meta field and a TTL of 7 days. A writer writes only when its watermark is not older, in one WATCH transaction that is not tried again; a full read replaces the hash through a temporary key and RENAME. TieredSnapshotStore loads the local and the shared copy and takes the fit copy with the newer watermark, saves the shared copy first, and holds no key of a private repository: it reads the visibility only after Valkey answered, and a failed read counts as private. intake_listing and lane_listing give it to every caller. --- .../design.md | 2 +- .../tasks.md | 8 +- src/devops_cli/config/defaults.py | 13 + .../roadmap/stores/listing_shared.py | 467 ++++++++++++++++++ .../roadmap/stores/listing_snapshot.py | 22 +- tests/conftest.py | 1 + tests/roadmap/stores/test_listing_shared.py | 5 +- tests/roadmap/test_roadmap_run_lanes.py | 7 +- tests/server/test_server_service.py | 6 +- 9 files changed, 515 insertions(+), 16 deletions(-) create mode 100644 src/devops_cli/roadmap/stores/listing_shared.py diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md index b7a793a73c..76eabbe501 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md @@ -10,7 +10,7 @@ - **The mapping encodes each value through a pydantic `TypeAdapter` of its value type, and stores the schema key of that type in front of the value (`:`).**: The facts are small JSON texts, so the mapping does not compress them; the snapshot store compresses its records itself. The keys are text, so each `cachetools.cached` read gives a `key` function. A reader that finds another schema key, or a key of an older kind version, treats it as a miss, reads the source and writes the value under the current key. This is the rule of T6. The schema key is the first 16 hex characters of the sha256 of the JSON schema of the type, as `LISTING_SCHEMA_KEY` already does for the snapshot. - **A value over 1 MiB stays in the in-process tier.**: The mapping measures the encoded value before it sends it. Over the bound, it sends no command, keeps the value in memory and counts `devops_cli_brain_writes_total{result="oversize"}`. ADR 0023 section 2 says that a value over 1 MiB stays local. `cachetools.cached` ignores a `ValueError` on a write, so the mapping does not raise one. - **Each key has a TTL.**: Each write of the mapping sends `SET ... EX `, and each write of the snapshot store ends with `EXPIRE` in the same MULTI/EXEC. The facts get 24 hours (`DEFAULT_BRAIN_FACT_TTL_SECONDS`) and the snapshot 7 days (`DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS`). A temporary key of a full write gets 600 s, so a killed writer leaves no key without an end. -- **`ValkeySnapshotStore` is the Valkey implementation of the `SnapshotStore` protocol.**: The protocol of #4552 is the seam that `IncrementalListing` reads, so no caller changes. `FileSnapshotStore` keeps one JSON file and cannot hold a shared copy. The hash `valkey:roadmap:v1:snapshot:/` holds the field `meta` (`schema`, `full_at`, `watermark`) and one zlib JSON `IssueRecord` for each issue number. One field for each record keeps each value under the bound: the snapshot of devops-cli is 14.13 MB with zlib, and its largest record is 23,700 B with zlib. +- **`ValkeySnapshotStore` is the Valkey implementation of the `SnapshotStore` protocol.**: The protocol of #4552 is the seam that `IncrementalListing` reads, so no caller changes. `FileSnapshotStore` keeps one JSON file and cannot hold a shared copy. The hash `valkey:roadmap:v1:snapshot:/` holds the field `meta` (`schema_key`, `full_at`, `watermark`, and a `token` that is new for each write, so two writes never give the same `meta`) and one zlib JSON `IssueRecord` for each issue number. One field for each record keeps each value under the bound: the snapshot of devops-cli is 14.13 MB with zlib, and its largest record is 23,700 B with zlib. - **`TieredSnapshotStore` combines the local and the shared store.**: ADR 0023 section 2 says that a reader loads the local and the shared copy, drops a copy with another schema or a full read older than 24 hours, and takes the copy with the newer watermark. The rule needs both copies at one place, so it is a store of its own and not a change of `IncrementalListing`. A save writes the shared tier first and then the local file, the order of ADR 0023 section 2. - **The newest watermark wins.**: A writer WATCHes the snapshot key, reads `meta`, and writes in one MULTI/EXEC only when its watermark is not older than the stored one, or when the stored copy has another schema. An EXEC that another client made fail writes nothing, and the writer does not retry: the other writer is newer or equal. This is the safe stop of ADR 0023 section 4. - **A save writes only the changed fields when it can, and a full write goes through a temporary key and RENAME.**: The store keeps a digest of each record that it loaded from or wrote to the shared tier in this process. When the stored `meta` is the `meta` that the store last saw, it sends `HSET` for the changed records, `HDEL` for the removed ones and the new `meta`. In every other case (a full read, no shared copy in this process, or a changed `meta`) it writes all records to `:next:` in pipelined batches and then, under the WATCH of the snapshot key, RENAMEs the temporary key onto it and sets its TTL. A full read so removes each issue that left the repository. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index 81bf122ed2..a87ebd4117 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -30,12 +30,12 @@ Adds: `TieredMapping`, `reset_tiered_mappings`, `schema_key_of`, `count_read`, ` ## 4. Share the listing snapshot through the shared tier -Kind: behavior. Reads: `src/devops_cli/roadmap/stores/listing_snapshot.py`, `src/devops_cli/roadmap/stores/github_store.py`, `src/devops_cli/roadmap/stores/store.py`, `src/devops_cli/valkey/cache.py`, `src/devops_cli/valkey/tiered.py`, `src/devops_cli/core/clock.py`, `src/devops_cli/commands/roadmap.py`, `src/devops_cli/roadmap/run.py`, `src/devops_cli/server/routes/webhooks.py`, `tests/roadmap/stores/test_listing_snapshot.py`, `tests/roadmap/stores/test_roadmap_store_install.py`, `tests/roadmap/test_roadmap_run_lanes.py`, `tests/roadmap/test_roadmap_run_scoped_update.py`, `tests/server/test_server_service.py`, `tests/conftest.py`. Changes: `src/devops_cli/roadmap/stores/listing_shared.py`, `src/devops_cli/roadmap/stores/listing_snapshot.py`, `src/devops_cli/config/defaults.py`, `tests/roadmap/stores/test_listing_shared.py`, `tests/conftest.py`. -Adds: `ValkeySnapshotStore`, `TieredSnapshotStore`, `repository_is_public`, `reset_repository_visibility`, `DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS`, `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`, `DEFAULT_BRAIN_SNAPSHOT_SCAN_COUNT`, `DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS` +Kind: behavior. Reads: `src/devops_cli/roadmap/stores/listing_snapshot.py`, `src/devops_cli/roadmap/stores/github_store.py`, `src/devops_cli/roadmap/stores/store.py`, `src/devops_cli/valkey/cache.py`, `src/devops_cli/valkey/tiered.py`, `src/devops_cli/core/clock.py`, `src/devops_cli/commands/roadmap.py`, `src/devops_cli/roadmap/run.py`, `src/devops_cli/server/routes/webhooks.py`, `tests/roadmap/stores/test_listing_snapshot.py`, `tests/roadmap/stores/test_roadmap_store_install.py`, `tests/roadmap/test_roadmap_run_lanes.py`, `tests/roadmap/test_roadmap_run_scoped_update.py`, `tests/server/test_server_service.py`, `tests/conftest.py`. Changes: `src/devops_cli/roadmap/stores/listing_shared.py`, `src/devops_cli/roadmap/stores/listing_snapshot.py`, `src/devops_cli/config/defaults.py`, `tests/roadmap/stores/test_listing_shared.py`, `tests/roadmap/test_roadmap_run_lanes.py`, `tests/server/test_server_service.py`, `tests/conftest.py`. +Adds: `ValkeySnapshotStore`, `TieredSnapshotStore`, `SharedMeta`, `HeldMeta`, `may_replace`, `snapshot_key`, `shared_snapshot_store`, `repository_is_public`, `reset_shared_snapshots`, `DEFAULT_BRAIN_SNAPSHOT_TEMPORARY_TTL_SECONDS`, `DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS`, `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`, `DEFAULT_BRAIN_SNAPSHOT_SCAN_COUNT`, `DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS` -- [ ] 4.1 Write `tests/roadmap/stores/test_listing_shared.py` on the `valkey_server` fake, the `clock` fixture and a GitHub listing fake: `test_a_cold_process_reads_the_shared_snapshot_and_at_most_two_pages` (scenario `Warm shared snapshot, cold process`, with the saved-requests counter); `test_the_newer_copy_of_the_two_tiers_gives_the_watermark`; `test_a_round_with_the_shared_tier_down_reads_the_local_file` (T2 for the snapshot); `test_a_trial_after_the_cooldown_lets_the_newer_snapshot_replace_the_older` and `test_an_older_writer_loses_its_watch_transaction` (T4); `test_an_older_watermark_does_not_replace_the_shared_snapshot`; `test_a_full_read_replaces_the_shared_snapshot_whole`; `test_no_key_of_a_private_repository_is_written` (a private answer and a failed visibility read); `test_no_visibility_read_without_the_shared_tier`; and `test_a_shared_load_past_its_budget_falls_back` +- [x] 4.1 Write `tests/roadmap/stores/test_listing_shared.py` on the `valkey_server` fake, the `clock` fixture and a GitHub listing fake: `test_a_cold_process_reads_the_shared_snapshot_and_at_most_two_pages` (scenario `Warm shared snapshot, cold process`, with the saved-requests counter); `test_the_newer_copy_of_the_two_tiers_gives_the_watermark`; `test_a_round_with_the_shared_tier_down_reads_the_local_file` (T2 for the snapshot); `test_a_trial_after_the_cooldown_lets_the_newer_snapshot_replace_the_older` and `test_an_older_writer_loses_its_watch_transaction` (T4); `test_an_older_watermark_does_not_replace_the_shared_snapshot`; `test_a_full_read_replaces_the_shared_snapshot_whole`; `test_no_key_of_a_private_repository_is_written` (a private answer and a failed visibility read); `test_no_visibility_read_without_the_shared_tier`; and `test_a_shared_load_past_its_budget_falls_back` - Verification: `$ uv run devops ci test tests/roadmap/stores/test_listing_shared.py` fails on the base -- [ ] 4.2 Add `ValkeySnapshotStore` and `TieredSnapshotStore` to the new `src/devops_cli/roadmap/stores/listing_shared.py`, each with `load` and `save` of the `SnapshotStore` protocol. The key is `valkey:roadmap:v1:snapshot:/`, a hash with `meta` (`schema`, `full_at`, `watermark`) and one zlib JSON `IssueRecord` for each issue number, with a TTL of `DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS` (7 days). A load reads `meta`, then the records with `HSCAN COUNT 500`, and stops at `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS` (20 s) on `devops_cli.core.clock.monotonic`. A save writes the changed fields under `watch_and_write` when the stored `meta` is the one that the store last saw, else all records to `:next:` with a TTL of 600 s and a RENAME under the WATCH; it writes only when its watermark is not older or the stored schema key differs. `TieredSnapshotStore` takes the fit copy with the newer watermark (the rule of ADR 0023 section 2), saves the shared tier first and then the local file, and uses the shared tier for a repository only when `repository_is_public` says so after the shared tier answered. `repository_is_public` reads `isPrivate` through `is_private_args` once for each repository and hour, keeps no failed read, and counts a failed read as private; `tests/conftest.py` adds `"devops_cli.roadmap.stores.listing_shared": ("reset_repository_visibility",)`. Make `intake_listing` and `lane_listing` in `src/devops_cli/roadmap/stores/listing_snapshot.py` give a `TieredSnapshotStore` over their `FileSnapshotStore` and `shared_cache_tier()`, and say so in the module docstring. The callers in `src/devops_cli/commands/roadmap.py`, `src/devops_cli/roadmap/run.py` and `src/devops_cli/server/routes/webhooks.py` do not change +- [x] 4.2 Add `ValkeySnapshotStore` and `TieredSnapshotStore` to the new `src/devops_cli/roadmap/stores/listing_shared.py`, each with `load` and `save` of the `SnapshotStore` protocol. The key is `valkey:roadmap:v1:snapshot:/`, a hash with `meta` (`schema_key`, `full_at`, `watermark`, `token`) and one zlib JSON `IssueRecord` for each issue number, with a TTL of `DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS` (7 days). A load reads `meta`, then the records with `HSCAN COUNT 500`, and stops at `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS` (20 s) on `devops_cli.core.clock.monotonic`. A save writes the changed fields under `watch_and_write` when the stored `meta` is the one that the store last saw, else all records to `:next:` with a TTL of 600 s and a RENAME under the WATCH; it writes only when its watermark is not older or the stored schema key differs. `TieredSnapshotStore` takes the fit copy with the newer watermark (the rule of ADR 0023 section 2), saves the shared tier first and then the local file, and uses the shared tier for a repository only when `repository_is_public` says so after the shared tier answered. `repository_is_public` reads `isPrivate` through `is_private_args` once for each repository and hour, keeps no failed read, and counts a failed read as private; `reset_shared_snapshots` drops the shared store and the visibility answers of the process, and `tests/conftest.py` adds `"devops_cli.roadmap.stores.listing_shared": ("reset_shared_snapshots",)`. The two tests that compare the store of a lane and of a scoped update expect the `TieredSnapshotStore` over the `FileSnapshotStore` (`tests/roadmap/test_roadmap_run_lanes.py`, `tests/server/test_server_service.py`). Make `intake_listing` and `lane_listing` in `src/devops_cli/roadmap/stores/listing_snapshot.py` give a `TieredSnapshotStore` over their `FileSnapshotStore` and `shared_cache_tier()`, and say so in the module docstring. The callers in `src/devops_cli/commands/roadmap.py`, `src/devops_cli/roadmap/run.py` and `src/devops_cli/server/routes/webhooks.py` do not change - Verification: `$ uv run devops ci test tests/roadmap/stores/test_listing_shared.py tests/roadmap/stores/test_listing_snapshot.py tests/roadmap/stores/test_roadmap_store_install.py tests/roadmap/test_roadmap_run_lanes.py tests/roadmap/test_roadmap_run_scoped_update.py tests/server/test_server_service.py` passes ## 5. Read the PyPI and deps.dev facts through the shared fact cache diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 76572a93d9..55e62feee6 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -741,6 +741,19 @@ DEFAULT_BRAIN_MEMORY_ENTRIES: int = 1024 # How long a tool fact of PyPI or deps.dev is kept, in memory and in Valkey: 24 hours. DEFAULT_BRAIN_FACT_TTL_SECONDS: int = 86_400 +# The shared listing snapshot of a repository lives 7 days after its last write (#4668). +DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS: int = 604_800 +# A load of a shared snapshot stops after this time and the reader takes the local copy or reads +# GitHub (#4668). Each command keeps the shorter bound of `valkey.timeout`. +DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS: float = 20.0 +# The fields that one `HSCAN` of a shared snapshot asks for, and that one `HSET` of a full write +# sends. 500 records are about 1 MB with zlib. +DEFAULT_BRAIN_SNAPSHOT_SCAN_COUNT: int = 500 +# The temporary key of a full write lives this long, so a killed writer leaves no key without an +# end. +DEFAULT_BRAIN_SNAPSHOT_TEMPORARY_TTL_SECONDS: int = 600 +# A process reads the visibility of a repository again after this time (#4668). +DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS: float = 3600.0 # Commands wait at most this long on the run index before keeping a run locally only. DEFAULT_RUNS_INDEX_TIMEOUT_SECONDS: float = 2.0 diff --git a/src/devops_cli/roadmap/stores/listing_shared.py b/src/devops_cli/roadmap/stores/listing_shared.py new file mode 100644 index 0000000000..be8e8a34ba --- /dev/null +++ b/src/devops_cli/roadmap/stores/listing_shared.py @@ -0,0 +1,467 @@ +"""The listing snapshot shared through the cache Valkey, over the local file of each process (#4668). + +A process with no local snapshot, such as an intake pod that starts with an empty home, reads the +whole listing: one request for each 100 issues. ADR 0023 section 2 adds a shared tier in the cache +Valkey `valkey-devops`, so a cold process starts from the newest copy and reads only the changes +since its watermark. GitHub stays the source of truth (ADR 0001): each copy can be dropped and read +again in full. + +`ValkeySnapshotStore` keeps the snapshot of a repository in one hash, +`valkey:roadmap:v1:snapshot:/`, with the field `meta` (the schema key, the time of +the last full read, the watermark, and a token of each write) and one zlib JSON `IssueRecord` +for each issue number. One field for each record keeps each value far under the bound of 1 MiB; +the whole snapshot of devops-cli is about 14 MB. The key lives +`DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS` after its last write. + +- A load reads `meta`, then the records with `HSCAN`, and stops when it passes + `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`. It reads `meta` again at the end, so a copy that + another writer changed during the scan is not used. +- A write is made only when its watermark is not older than the stored one, or when the stored + copy has another schema key (ADR 0023 section 4). The check and the write are one WATCH and + MULTI/EXEC; a writer whose EXEC fails writes nothing and does not try again, because the other + writer is as new or newer. +- When the stored `meta` is the one that this process last wrote or read, a write sends only the + changed and removed records. Else, and after each full read, it writes all records to a + temporary key with a TTL and RENAMEs it onto the snapshot key, so an issue that left the + repository leaves the shared copy. + +`TieredSnapshotStore` is the `SnapshotStore` that intake and the lanes read through. It loads the +local and the shared copy, drops a copy with another schema key or a full read older than +`DEFAULT_ROADMAP_INTAKE_SNAPSHOT_MAX_AGE_HOURS`, and takes the copy with the newer watermark. It +saves the shared copy first and then the local file. While Valkey fails, it reads and writes the +local file only. Until `valkey-devops` has role ACL users (#4704), the shared tier holds no data +of a private repository (ADR 0023 section 8): the store reads the visibility of a repository only +after Valkey answered, and a failed visibility read counts as private. +""" + +from __future__ import annotations + +import hashlib +import logging +import math +import threading +import uuid +import zlib +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field +from datetime import UTC, datetime, timedelta +from itertools import batched +from typing import Any, Final + +from pydantic import BaseModel, ConfigDict, ValidationError + +from devops_cli.config.constants import ( + CONST_VALKEY_ROADMAP_PREFIX, + BrainRead, + BrainStore, + BrainWrite, + ValkeyCacheError, +) +from devops_cli.config.defaults import ( + DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS, + DEFAULT_BRAIN_SNAPSHOT_SCAN_COUNT, + DEFAULT_BRAIN_SNAPSHOT_TEMPORARY_TTL_SECONDS, + DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS, + DEFAULT_BRAIN_VALUE_MAX_BYTES, + DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS, + DEFAULT_GH_REST_PER_PAGE, + DEFAULT_ROADMAP_INTAKE_SNAPSHOT_MAX_AGE_HOURS, +) +from devops_cli.core import clock +from devops_cli.exceptions import DevOpsCLIError +from devops_cli.roadmap.stores.github_store import GhRunner, GitHubRoadmapStore +from devops_cli.roadmap.stores.listing_snapshot import ( + LISTING_SCHEMA_KEY, + ListingSnapshot, + SnapshotStore, +) +from devops_cli.roadmap.stores.store import IssueRecord +from devops_cli.telemetry.instruments import ( + BRAIN_GITHUB_REQUESTS_SAVED_TOTAL, + VALKEY_CACHE_ERRORS_TOTAL, + emit, +) +from devops_cli.valkey.cache import ValkeyCacheTier, shared_cache_tier +from devops_cli.valkey.tiered import count_read, count_write + +logger = logging.getLogger(__name__) + +# The field of the hash that holds the facts of the snapshot. +META_FIELD: Final = "meta" +_MAX_AGE: Final = timedelta(hours=DEFAULT_ROADMAP_INTAKE_SNAPSHOT_MAX_AGE_HOURS) + + +class SharedMeta(BaseModel): + """The `meta` field of a shared snapshot. `token` is new for each write, so two writes never + give the same `meta`.""" + + model_config = ConfigDict(frozen=True) + + schema_key: str + full_at: datetime + watermark: datetime + token: str + + +@dataclass(frozen=True) +class HeldMeta: + """The `meta` of a shared snapshot as Valkey gave it: its bytes, and its facts when they parse.""" + + raw: bytes + meta: SharedMeta | None + + +@dataclass(frozen=True) +class _Seen: + """What the shared copy of a repository held when this process last wrote or read it: its + `meta`, the time of its full read, and a digest of the JSON of each record by number.""" + + raw: bytes + full_at: datetime + digests: Mapping[str, bytes] + + +def snapshot_key(repo: str) -> str: + """The Valkey key of the shared snapshot of `repo`.""" + return f"{CONST_VALKEY_ROADMAP_PREFIX}:snapshot:{repo}" + + +def _digest(text: bytes) -> bytes: + return hashlib.blake2b(text, digest_size=16).digest() + + +def _parsed(raw: bytes) -> SharedMeta | None: + """The facts of a `meta` field; None when it does not parse.""" + try: + return SharedMeta.model_validate_json(raw) + except ValidationError as exc: + logger.debug("The meta field of a shared snapshot does not parse: %s", exc.error_count()) + return None + + +def may_replace(stored: SharedMeta | None, mine: SharedMeta) -> bool: + """Whether a write of `mine` may replace the stored copy: there is none, it has another schema + key, or its watermark is not newer than that of `mine`.""" + return ( + stored is None or stored.schema_key != mine.schema_key or mine.watermark >= stored.watermark + ) + + +def _count_budget() -> None: + emit( + VALKEY_CACHE_ERRORS_TOTAL, + 1, + {"op": "hscan", "error": ValkeyCacheError.BUDGET.value}, + ) + + +@dataclass +class ValkeySnapshotStore: + """The snapshots of the repositories in the cache Valkey, one hash for each repository. + + The store keeps what the shared copy of each repository held when the store last wrote or + read it, so a later write sends only the changed records. One store lives for a process + (`shared_snapshot_store`). + """ + + tier: ValkeyCacheTier + _seen: dict[str, _Seen] = field(default_factory=dict, init=False, repr=False) + _lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False) + + def meta(self, repo: str) -> HeldMeta | None: + """The `meta` of the shared snapshot of `repo`; None when there is none or the read + fails. `tier.is_open` after the call tells a failure.""" + raw = self.tier.hget(snapshot_key(repo), META_FIELD) + return None if raw is None else HeldMeta(raw, _parsed(raw)) + + def records(self, repo: str, held: HeldMeta) -> ListingSnapshot | None: + """The shared snapshot whose `meta` is `held`; None when the read fails, passes its + budget, finds a record that does not parse, or finds that another writer changed it.""" + if held.meta is None: + return None + key = snapshot_key(repo) + started = clock.monotonic() + values: dict[str, bytes] = {} + cursor = 0 + while True: + step = self.tier.hscan(key, cursor, DEFAULT_BRAIN_SNAPSHOT_SCAN_COUNT) + if step is None: + return None + cursor, fields = step + values |= fields + if cursor == 0: + break + if clock.monotonic() - started > DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS: + logger.info( + "The load of the shared snapshot of %s passed its budget of %s s.", + repo, + DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS, + ) + _count_budget() + return None + if values.pop(META_FIELD, None) != held.raw or self.tier.hget(key, META_FIELD) != held.raw: + return None + texts = _decompressed(repo, values) + if texts is None: + return None + try: + issues = [IssueRecord.model_validate_json(text) for text in texts.values()] + except ValidationError as exc: + logger.info("A record of the shared snapshot of %s does not parse: %s", repo, exc) + return None + meta = held.meta + with self._lock: + self._seen[repo] = _Seen(held.raw, meta.full_at, _digests(texts)) + return ListingSnapshot( + repo=repo, + schema_key=meta.schema_key, + full_at=meta.full_at, + watermark=meta.watermark, + issues=tuple(sorted(issues, key=lambda issue: issue.number, reverse=True)), + ) + + def load(self, repo: str) -> ListingSnapshot | None: + held = self.meta(repo) + return None if held is None else self.records(repo, held) + + def save(self, snapshot: ListingSnapshot) -> None: + """Write `snapshot` when it may replace the shared copy, and count the result.""" + count_write(BrainStore.SNAPSHOT, self.write(snapshot, self.meta(snapshot.repo))) + + def write(self, snapshot: ListingSnapshot, held: HeldMeta | None) -> BrainWrite: + """Write `snapshot` over the shared copy whose `meta` was `held`, and return the result.""" + texts = {str(issue.number): issue.model_dump_json().encode() for issue in snapshot.issues} + records = {number: zlib.compress(text) for number, text in texts.items()} + if any(len(value) > DEFAULT_BRAIN_VALUE_MAX_BYTES for value in records.values()): + return BrainWrite.OVERSIZE + meta = SharedMeta( + schema_key=snapshot.schema_key, + full_at=snapshot.full_at, + watermark=snapshot.watermark, + token=uuid.uuid4().hex, + ) + if held is not None and not may_replace(held.meta, meta): + return BrainWrite.OLDER + seen = _Seen(meta.model_dump_json().encode(), meta.full_at, _digests(texts)) + with self._lock: + before = self._seen.get(snapshot.repo) + if ( + before is not None + and held is not None + and before.raw == held.raw + and before.full_at == snapshot.full_at + and self._update(snapshot.repo, before, seen, records) + ): + return self._kept(snapshot.repo, seen) + return self._replace(snapshot.repo, meta, seen, records) + + def _update(self, repo: str, before: _Seen, seen: _Seen, records: dict[str, bytes]) -> bool: + """Send the changed and removed records and the new `meta` in one transaction, when the + stored `meta` is still the one of `before`.""" + key = snapshot_key(repo) + changed = [ + word + for number, value in records.items() + if before.digests.get(number) != seen.digests[number] + for word in (number, value) + ] + removed = [number for number in before.digests if number not in records] + + def decide(current: bytes | None) -> list[tuple[Any, ...]]: + if current != before.raw: + return [] + return [ + *([("HSET", key, *changed)] if changed else []), + *([("HDEL", key, *removed)] if removed else []), + ("HSET", key, META_FIELD, seen.raw), + ("EXPIRE", key, DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS), + ] + + return bool(self.tier.watch_and_write(key, META_FIELD, decide)) + + def _replace( + self, repo: str, meta: SharedMeta, seen: _Seen, records: dict[str, bytes] + ) -> BrainWrite: + """Write every record to a temporary key, then RENAME it onto the snapshot key when the + stored copy may still be replaced.""" + key = snapshot_key(repo) + temporary = f"{key}:next:{meta.token}" + written = self.tier.hset(temporary, {META_FIELD: seen.raw}) is not None and ( + self.tier.expire(temporary, DEFAULT_BRAIN_SNAPSHOT_TEMPORARY_TTL_SECONDS) + ) + for batch in batched(records.items(), DEFAULT_BRAIN_SNAPSHOT_SCAN_COUNT, strict=False): + written = written and self.tier.hset(temporary, dict(batch)) is not None + + def decide(current: bytes | None) -> list[tuple[Any, ...]]: + if current is not None and not may_replace(_parsed(current), meta): + return [] + return [ + ("RENAME", temporary, key), + ("EXPIRE", key, DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS), + ] + + renamed = self.tier.watch_and_write(key, META_FIELD, decide) if written else None + if renamed: + return self._kept(repo, seen) + self.tier.unlink(temporary) + return BrainWrite.SKIPPED if renamed is None else BrainWrite.OLDER + + def _kept(self, repo: str, seen: _Seen) -> BrainWrite: + with self._lock: + self._seen[repo] = seen + return BrainWrite.SHARED + + +def _digests(texts: Mapping[str, bytes]) -> dict[str, bytes]: + return {number: _digest(text) for number, text in texts.items()} + + +def _decompressed(repo: str, values: Mapping[str, bytes]) -> dict[str, bytes] | None: + """The JSON of each record; None when a value is not zlib data.""" + try: + return {number: zlib.decompress(value) for number, value in values.items()} + except zlib.error as exc: + logger.info("A record of the shared snapshot of %s is not zlib data: %s", repo, exc) + return None + + +_STORE_LOCK = threading.Lock() +_stores: list[ValkeySnapshotStore] = [] + + +def shared_snapshot_store() -> ValkeySnapshotStore | None: + """The one shared snapshot store of the process, over `shared_cache_tier()`; None when the + process has no Valkey tier.""" + tier = shared_cache_tier() + if tier is None: + return None + with _STORE_LOCK: + if not _stores or _stores[0].tier is not tier: + _stores[:] = [ValkeySnapshotStore(tier)] + return _stores[0] + + +_VISIBILITY_LOCK = threading.Lock() +# The visibility of each repository that this process read: whether it is public, and when. +_visibility: dict[str, tuple[bool, float]] = {} + + +def repository_is_public(repo: str, *, runner: GhRunner | None = None) -> bool: + """Whether GitHub says that `repo` is public, read once for each repository and + `DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS`. A failed read counts as private and is not kept, so + the shared tier gets no data that could be private (ADR 0023 section 8).""" + now = clock.monotonic() + with _VISIBILITY_LOCK: + held = _visibility.get(repo) + if held is not None and now - held[1] < DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS: + return held[0] + store = GitHubRoadmapStore(repo) if runner is None else GitHubRoadmapStore(repo, runner=runner) + try: + public = not store.repository_is_private() + except DevOpsCLIError as exc: + logger.warning( + "The visibility of %s is not known, so the shared tier does not hold its listing: %s", + repo, + exc, + ) + return False + with _VISIBILITY_LOCK: + _visibility[repo] = (public, now) + return public + + +def reset_shared_snapshots() -> None: + """Drop the shared snapshot store and the visibility answers of the process, as a new + process starts.""" + with _STORE_LOCK: + _stores.clear() + with _VISIBILITY_LOCK: + _visibility.clear() + + +def _now() -> datetime: + return datetime.now(UTC) + + +@dataclass(frozen=True) +class TieredSnapshotStore: + """The local snapshot store of a process and the shared one in Valkey, as one store. + + `shared` gives the shared store of the process, None when there is no Valkey tier. + `is_public` says whether a repository is public. `clock` gives the time now, which the age of + a full read is measured from. + """ + + local: SnapshotStore + shared: Callable[[], ValkeySnapshotStore | None] = shared_snapshot_store + is_public: Callable[[str], bool] = repository_is_public + clock: Callable[[], datetime] = _now + schema_key: str = LISTING_SCHEMA_KEY + + def load(self, repo: str) -> ListingSnapshot | None: + local = self.local.load(repo) + shared = self.shared() + held = None if shared is None else shared.meta(repo) + if shared is None or (held is None and shared.tier.is_open): + count_read(BrainStore.SNAPSHOT, BrainRead.FALLBACK) + return local + if not self.is_public(repo): + count_read(BrainStore.SNAPSHOT, BrainRead.PRIVATE) + return local + now = self.clock() + local_fit = self._fit(local, now) + meta = None if held is None else held.meta + if ( + held is None + or meta is None + or not self._fit(meta, now) + or (local is not None and local_fit and local.watermark >= meta.watermark) + ): + count_read(BrainStore.SNAPSHOT, BrainRead.SOURCE) + return local + copy = shared.records(repo, held) + if copy is None: + count_read(BrainStore.SNAPSHOT, BrainRead.FALLBACK) + return local + count_read(BrainStore.SNAPSHOT, BrainRead.SHARED) + if not local_fit: + pages = math.ceil(len(copy.issues) / DEFAULT_GH_REST_PER_PAGE) + emit(BRAIN_GITHUB_REQUESTS_SAVED_TOTAL, pages, {"store": BrainStore.SNAPSHOT.value}) + return copy + + def save(self, snapshot: ListingSnapshot) -> None: + """Write the shared copy, then the local file.""" + count_write(BrainStore.SNAPSHOT, self._share(snapshot)) + self.local.save(snapshot) + + def _share(self, snapshot: ListingSnapshot) -> BrainWrite: + shared = self.shared() + held = None if shared is None else shared.meta(snapshot.repo) + if shared is None or (held is None and shared.tier.is_open): + return BrainWrite.SKIPPED + if not self.is_public(snapshot.repo): + return BrainWrite.PRIVATE + return shared.write(snapshot, held) + + def _fit(self, held: ListingSnapshot | SharedMeta | None, now: datetime) -> bool: + """Whether a run can read the changes from `held`: it has this schema key, and its last + full read is younger than the max age.""" + return ( + held is not None + and held.schema_key == self.schema_key + and now - held.full_at < _MAX_AGE + ) + + +__all__ = [ + "META_FIELD", + "HeldMeta", + "SharedMeta", + "TieredSnapshotStore", + "ValkeySnapshotStore", + "may_replace", + "repository_is_public", + "reset_shared_snapshots", + "shared_snapshot_store", + "snapshot_key", +] diff --git a/src/devops_cli/roadmap/stores/listing_snapshot.py b/src/devops_cli/roadmap/stores/listing_snapshot.py index b1b67a077e..3d99a0573a 100644 --- a/src/devops_cli/roadmap/stores/listing_snapshot.py +++ b/src/devops_cli/roadmap/stores/listing_snapshot.py @@ -18,7 +18,10 @@ in the state directory of the roadmap: under the data directory for `devops roadmap intake`, and on the Service's volume for the intake of the lane of `intake` and the scoped intake of a delivery. Each other lane of the Service keeps its own snapshots beside them (`lane_listing`, #4854, #5553), -so each file has one writer. A shared store for the pods of the Service can plug in later (#4517). +so each file has one writer. `intake_listing` and `lane_listing` put the local file under a +`TieredSnapshotStore` (`listing_shared`, #4668), which shares one copy of each public repository +through the cache Valkey: a cold process starts from the newest copy, and the newest watermark +wins. While Valkey fails, the local file is the only tier. """ from __future__ import annotations @@ -214,15 +217,24 @@ def intake_listing(state_dir: Path | None = None, *, full: bool = False) -> Incr """How intake reads every issue: the snapshot that `state_dir` keeps, see `snapshot_root`, and the issues changed since its watermark, or the whole listing on `full`. `devops roadmap intake`, the lane of `intake` in the Service and the scoped intake of a delivery read through - it (#4448, #3670).""" - return IncrementalListing(FileSnapshotStore(snapshot_root(state_dir)), full=full) + it (#4448, #3670). The local file sits under the shared tier (#4668).""" + return IncrementalListing(_tiered(FileSnapshotStore(snapshot_root(state_dir))), full=full) def lane_listing(state_dir: Path, lane: str) -> IncrementalListing: """How the rounds of the Service lane `lane` read every issue: the snapshot that `state_dir` keeps for the lane in `listing-`, apart from the one of intake, and the issues changed - since its watermark. The lane's worker is the one writer of each file of the lane (#4854).""" - return IncrementalListing(FileSnapshotStore(state_dir / f"{_SNAPSHOT_DIRNAME}-{lane}")) + since its watermark. The lane's worker is the one writer of each file of the lane (#4854). The + lanes of a repository share one copy in the shared tier, where the newest watermark wins (#4668).""" + return IncrementalListing(_tiered(FileSnapshotStore(state_dir / f"{_SNAPSHOT_DIRNAME}-{lane}"))) + + +def _tiered(local: SnapshotStore) -> SnapshotStore: + """`local` under the shared tier of the process (#4668). The import is local, since the + shared store reads the types of this module.""" + from devops_cli.roadmap.stores.listing_shared import TieredSnapshotStore + + return TieredSnapshotStore(local) def lane_snapshot_dirs(state_dir: Path) -> dict[str, Path]: diff --git a/tests/conftest.py b/tests/conftest.py index 042ee3ddc5..1a7a3fac98 100755 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -147,6 +147,7 @@ def isolate_kubeconfig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Non "devops_cli.roadmap.stores.store": ("reset_roadmap_store",), "devops_cli.security.reference_extractor": ("reset_reference_extractor_caches",), "devops_cli.security.secrets": ("reset_resolver",), + "devops_cli.roadmap.stores.listing_shared": ("reset_shared_snapshots",), "devops_cli.server.start": ("remove_server_starter",), "devops_cli.telemetry.library_spans": ("reset_library_spans",), "devops_cli.telemetry.logfire": ("reset_logfire_bridge",), diff --git a/tests/roadmap/stores/test_listing_shared.py b/tests/roadmap/stores/test_listing_shared.py index c6fe05ff43..7b621570e1 100644 --- a/tests/roadmap/stores/test_listing_shared.py +++ b/tests/roadmap/stores/test_listing_shared.py @@ -414,7 +414,8 @@ def test_no_key_of_a_private_repository_is_written( github_api: GitHubApiFake, tmp_path: Path, valkey_server: FakeServer, otlp: FakeCollector ) -> None: """A round for a private repository and a round whose visibility read fails write no key - and use no shared copy; each counts `private`.""" + and use no shared copy; each counts `private`. A private answer is kept for the round; a + failed read is not, so the save reads the visibility again.""" from devops_cli.roadmap.stores.listing_shared import repository_is_public private = RecordedGh({"isPrivate": {"data": {"repository": {"isPrivate": True}}}}) @@ -441,7 +442,7 @@ def test_no_key_of_a_private_repository_is_written( ) == ( [], 1, - 1, + 2, {("snapshot", "private"): 2.0}, {("snapshot", "private"): 2.0}, ) diff --git a/tests/roadmap/test_roadmap_run_lanes.py b/tests/roadmap/test_roadmap_run_lanes.py index 536b1a3056..aa45c953c8 100644 --- a/tests/roadmap/test_roadmap_run_lanes.py +++ b/tests/roadmap/test_roadmap_run_lanes.py @@ -28,6 +28,7 @@ service_jobs, ) from devops_cli.roadmap.stores.github_store import GitHubRoadmapStore +from devops_cli.roadmap.stores.listing_shared import TieredSnapshotStore from devops_cli.roadmap.stores.listing_snapshot import ( FileSnapshotStore, IncrementalListing, @@ -127,7 +128,7 @@ def test_each_lane_reads_every_issue_through_its_own_snapshot( """Test first for #3670, #4854 and #5553: the lane of intake opens its store with the listing snapshot that the Service keeps in its state directory, as the scoped intake does. Each other lane opens its store with a snapshot in a directory of its own, so each snapshot has one - writer.""" + writer. Each local file sits under the shared tier of the process (#4668).""" github = service_github([]) serve_over(tmp_path, monkeypatch, github, stamped=False) rows = (*STATUS_LANE_ROWS, *TRIAGE_LANE_ROWS, *MODEL_LANE_ROWS) @@ -145,7 +146,9 @@ def store(repo: str, *, listing: IncrementalListing | None = None, **_: Any) -> job(POLL) intake_lane = _lane_of(jobs, "intake") assert snapshots == [ - FileSnapshotStore(tmp_path / ("listing" if lane == intake_lane else f"listing-{lane}")) + TieredSnapshotStore( + FileSnapshotStore(tmp_path / ("listing" if lane == intake_lane else f"listing-{lane}")) + ) for lane in jobs ] diff --git a/tests/server/test_server_service.py b/tests/server/test_server_service.py index 3d027f0acc..ba894b25a2 100644 --- a/tests/server/test_server_service.py +++ b/tests/server/test_server_service.py @@ -48,6 +48,7 @@ from devops_cli.lang import MESSAGES from devops_cli.roadmap.run import DEFAULT_DUE_TABLE, JobOutcome from devops_cli.roadmap.service_stop import service_stopping +from devops_cli.roadmap.stores.listing_shared import TieredSnapshotStore from devops_cli.roadmap.stores.listing_snapshot import ( FileSnapshotStore, IncrementalListing, @@ -1994,7 +1995,8 @@ def test_a_scoped_update_reads_every_issue_through_the_snapshot_in_the_state_dir ) -> None: """Test first for #3670: the store of a scoped update reads every issue through the listing snapshot that the Service keeps in its state directory, the one the triage lane's intake - reads, and the update keeps its records beside it.""" + reads, and the update keeps its records beside it. The local file sits under the shared tier + of the process (#4668).""" snapshots: list[SnapshotStore | None] = [] data_dirs: list[Any] = [] @@ -2023,7 +2025,7 @@ def fake_scoped(delivery: Any, store: Any, **kwargs: Any) -> Any: assert (response.status_code, settled, snapshots, data_dirs) == ( 202, True, - [FileSnapshotStore(state_dir / "listing")], + [TieredSnapshotStore(FileSnapshotStore(state_dir / "listing"))], [tmp_path], ) From 1624027f74165d07e06eabc1dc3c30eee44bf13e Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:48:54 +0000 Subject: [PATCH 09/20] test(roadmap): read the PyPI and deps.dev facts through the fact cache A second PyPI read of one package in another spelling and a second deps.dev read of one project, each with an empty memory tier, send no request. A failed PyPI read keeps nothing; it passes on the base and guards the change. Failed tests: - tests/roadmap/test_roadmap_alternatives.py::test_a_second_pypi_read_of_one_package_sends_no_request - tests/roadmap/test_roadmap_alternatives_project_facts.py::test_a_second_deps_dev_read_of_one_project_sends_no_request --- tests/roadmap/test_roadmap_alternatives.py | 39 +++++++++++++++++++ ...test_roadmap_alternatives_project_facts.py | 23 +++++++++++ 2 files changed, 62 insertions(+) diff --git a/tests/roadmap/test_roadmap_alternatives.py b/tests/roadmap/test_roadmap_alternatives.py index af8fad7328..1c65b624cb 100644 --- a/tests/roadmap/test_roadmap_alternatives.py +++ b/tests/roadmap/test_roadmap_alternatives.py @@ -820,6 +820,45 @@ def test_a_pypi_read_answers_with_the_latest_upload_and_remembers_it( ) +@pytest.mark.usefixtures("shared_valkey") +def test_a_second_pypi_read_of_one_package_sends_no_request( + store: InMemoryRoadmapStore, web: WebFake +) -> None: + """PyPI fact reuse across processes (#4668): `Scanner`, then `scanner` with the memory tier of + the process empty, as in a new process. The second read comes from the shared tier.""" + from devops_cli.valkey.tiered import reset_tiered_mappings + + _pypi(web, "Scanner", uploads=[NOW.isoformat()], license_expression="MIT") + + first = AlternativesTools(store=store).pypi_package("Scanner") + reset_tiered_mappings() + second = AlternativesTools(store=store).pypi_package("scanner") + + assert (first == second, web.requested) == ( + True, + [DEFAULT_PYPI_PACKAGE_URL.format(name="Scanner")], + ) + + +@pytest.mark.usefixtures("shared_valkey") +def test_a_failed_pypi_read_keeps_nothing(store: InMemoryRoadmapStore, web: WebFake) -> None: + """PyPI answers 503 and then 200: the failure is not kept, so the second call reads PyPI and + gives the facts (#4668).""" + url = DEFAULT_PYPI_PACKAGE_URL.format(name="scanner") + web.respond("GET", url, 503) + failed = AlternativesTools(store=store).pypi_package("scanner") + web.method_routes.clear() + _pypi(web, "scanner", uploads=[NOW.isoformat()], license_expression="MIT") + + answer = AlternativesTools(store=store).pypi_package("scanner") + + assert (failed, "License: MIT" in answer.splitlines(), web.requested) == ( + "The read failed: HTTPStatusError.", + True, + [url, url], + ) + + @pytest.mark.parametrize( ("fields", "license_name"), [ diff --git a/tests/roadmap/test_roadmap_alternatives_project_facts.py b/tests/roadmap/test_roadmap_alternatives_project_facts.py index 2cc4e3f0ed..4384e725f8 100644 --- a/tests/roadmap/test_roadmap_alternatives_project_facts.py +++ b/tests/roadmap/test_roadmap_alternatives_project_facts.py @@ -204,6 +204,29 @@ def test_a_github_tool_whose_package_deps_dev_links_and_the_sbom_holds_is_in_use ) +@pytest.mark.usefixtures("shared_valkey") +def test_a_second_deps_dev_read_of_one_project_sends_no_request( + store: InMemoryRoadmapStore, web: WebFake +) -> None: + """deps.dev fact reuse (#4668): two inventory reads link the packages of one project, with + the memory tier of the process empty between them, as in a new process.""" + from devops_cli.valkey.tiered import reset_tiered_mappings + + project = "github.com/example/tool" + _deps_dev(web, project, ("PYPI", "example-tool")) + store.seed_dependencies("pkg:pypi/example-tool@1.0.0") + + first = read_inventory(store, None, PATHS).uses(f"https://{project}", project) + reset_tiered_mappings() + second = read_inventory(store, None, PATHS).uses(f"https://{project}", project) + + assert (first, second, web.requested) == ( + True, + True, + [DEFAULT_DEPS_DEV_PROJECT_URL.format(project=quote(project, safe=""))], + ) + + def test_a_tool_that_no_source_holds_keeps_its_verdict_and_an_empty_sbom_asks_no_deps_dev( store: InMemoryRoadmapStore, web: WebFake ) -> None: From c3b6a8bc2283106f5f8bfd4865b0a4927bd6cd81 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:49:49 +0000 Subject: [PATCH 10/20] feat(roadmap): read the PyPI and deps.dev facts through the fact cache _read_pypi and _linked_packages go through cachetools.cached over one TieredMapping each, under valkey:brain:v1:fact:pypi with the canonical package name and valkey:brain:v1:fact:deps-dev with the project key in lower case, for 24 hours. A package or project that a process or another pod read sends no request; a failed read keeps nothing. --- .../tasks.md | 4 ++-- src/devops_cli/roadmap/alternatives.py | 21 +++++++++++++++++-- src/devops_cli/roadmap/inventory.py | 20 ++++++++++++++++-- 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index a87ebd4117..a3d80f5290 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -42,9 +42,9 @@ Adds: `ValkeySnapshotStore`, `TieredSnapshotStore`, `SharedMeta`, `HeldMeta`, `m Kind: behavior. Reads: `src/devops_cli/roadmap/alternatives.py`, `src/devops_cli/roadmap/inventory.py`, `src/devops_cli/valkey/tiered.py`, `tests/roadmap/test_roadmap_alternatives.py`, `tests/roadmap/test_roadmap_alternatives_project_facts.py`, `tests/support/fakes/http.py`. Changes: `src/devops_cli/roadmap/alternatives.py`, `src/devops_cli/roadmap/inventory.py`, `tests/roadmap/test_roadmap_alternatives.py`, `tests/roadmap/test_roadmap_alternatives_project_facts.py`. -- [ ] 5.1 Write `test_a_second_pypi_read_of_one_package_sends_no_request` (scenario `PyPI fact reuse across processes`: `Scanner` then `scanner`, with `reset_tiered_mappings` between them, one request on the `web` fake) and `test_a_failed_pypi_read_keeps_nothing` (503 then 200) in `tests/roadmap/test_roadmap_alternatives.py`, and `test_a_second_deps_dev_read_of_one_project_sends_no_request` in `tests/roadmap/test_roadmap_alternatives_project_facts.py`. Check each existing test of these two files that reads one package or project twice with two answers, and give it two names +- [x] 5.1 Write `test_a_second_pypi_read_of_one_package_sends_no_request` (scenario `PyPI fact reuse across processes`: `Scanner` then `scanner`, with `reset_tiered_mappings` between them, one request on the `web` fake) and `test_a_failed_pypi_read_keeps_nothing` (503 then 200) in `tests/roadmap/test_roadmap_alternatives.py`, and `test_a_second_deps_dev_read_of_one_project_sends_no_request` in `tests/roadmap/test_roadmap_alternatives_project_facts.py`. Check each existing test of these two files that reads one package or project twice with two answers, and give it two names - Verification: `$ uv run devops ci test tests/roadmap/test_roadmap_alternatives.py tests/roadmap/test_roadmap_alternatives_project_facts.py` fails on the base -- [ ] 5.2 Decorate `_read_pypi` in `src/devops_cli/roadmap/alternatives.py` with `cachetools.cached` over a `TieredMapping` of `_PyPIPackage | None` with the prefix `valkey:brain:v1:fact:pypi` and the key `packaging.utils.canonicalize_name(name)`, and `_linked_packages` in `src/devops_cli/roadmap/inventory.py` with a `TieredMapping` of `frozenset[str]` with the prefix `valkey:brain:v1:fact:deps-dev` and the project key in lower case, each with the TTL `DEFAULT_BRAIN_FACT_TTL_SECONDS` (24 hours). A raised read keeps nothing. Say in each docstring that the read goes through the fact cache +- [x] 5.2 Decorate `_read_pypi` in `src/devops_cli/roadmap/alternatives.py` with `cachetools.cached` over a `TieredMapping` of `_PyPIPackage | None` with the prefix `valkey:brain:v1:fact:pypi` and the key `packaging.utils.canonicalize_name(name)`, and `_linked_packages` in `src/devops_cli/roadmap/inventory.py` with `cachetools.cached` over a `TieredMapping` of `frozenset[str]` with the prefix `valkey:brain:v1:fact:deps-dev` and the key `str.lower(project)`, each with the TTL `DEFAULT_BRAIN_FACT_TTL_SECONDS` (24 hours). A raised read keeps nothing. Say in each docstring that the read goes through the fact cache - Verification: `$ uv run devops ci test tests/roadmap/test_roadmap_alternatives.py tests/roadmap/test_roadmap_alternatives_project_facts.py` passes ## 6. Raise the memory bound of valkey-devops diff --git a/src/devops_cli/roadmap/alternatives.py b/src/devops_cli/roadmap/alternatives.py index 1d837ccc8f..f7d379e701 100644 --- a/src/devops_cli/roadmap/alternatives.py +++ b/src/devops_cli/roadmap/alternatives.py @@ -76,7 +76,9 @@ from urllib.parse import quote import httpx2 -from pydantic import BaseModel, Field, ValidationError +from cachetools import cached +from packaging.utils import canonicalize_name +from pydantic import BaseModel, Field, TypeAdapter, ValidationError from pydantic_ai import Tool from pydantic_ai.messages import ToolReturn @@ -105,8 +107,10 @@ CONST_ROADMAP_REFINE_TOOL_MAX_CHARS, CONST_ROADMAP_STATUS_NEW, CONST_ROADMAP_STATUS_READY, + CONST_VALKEY_BRAIN_PREFIX, ) from devops_cli.config.defaults import ( + DEFAULT_BRAIN_FACT_TTL_SECONDS, DEFAULT_PYPI_PACKAGE_URL, DEFAULT_PYPI_TIMEOUT_SECONDS, ) @@ -170,6 +174,7 @@ ROADMAP_ALTERNATIVES_UNCHECKED_ITEMS, emit, ) +from devops_cli.valkey.tiered import TieredMapping logger = logging.getLogger(__name__) @@ -295,9 +300,21 @@ def last_upload(self) -> datetime | None: return max((file.upload_time_iso_8601 for file in self.urls), default=None) +# The PyPI facts of the process and of the cache Valkey, by the canonical name of the package +# (#4668). PyPI answers each client the same, so the facts are shared for 24 hours. +_PYPI_FACTS: TieredMapping[_PyPIPackage | None] = TieredMapping( + f"{CONST_VALKEY_BRAIN_PREFIX}:fact:pypi", + TypeAdapter(_PyPIPackage | None), + ttl=DEFAULT_BRAIN_FACT_TTL_SECONDS, +) + + +@cached(_PYPI_FACTS, key=canonicalize_name) def _read_pypi(name: str) -> _PyPIPackage | None: """The PyPI record of package `name`, or None when PyPI has no such package. Raises on any - other failed read.""" + other failed read. The read goes through the fact cache of the project brain (#4668): a + package that a process or another pod read in the last 24 hours, in any spelling of its name, + sends no request, and a failed read keeps nothing.""" url = DEFAULT_PYPI_PACKAGE_URL.format(name=quote(name, safe="")) with http_client(EgressLevel.PUBLIC) as client: response = client.get(url, timeout=DEFAULT_PYPI_TIMEOUT_SECONDS) diff --git a/src/devops_cli/roadmap/inventory.py b/src/devops_cli/roadmap/inventory.py index 9446c12744..18d57d00e1 100644 --- a/src/devops_cli/roadmap/inventory.py +++ b/src/devops_cli/roadmap/inventory.py @@ -28,11 +28,14 @@ from urllib.parse import quote, urlsplit import httpx2 +from cachetools import cached from packageurl import PackageURL from packaging.utils import canonicalize_name -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, TypeAdapter +from devops_cli.config.constants import CONST_VALKEY_BRAIN_PREFIX from devops_cli.config.defaults import ( + DEFAULT_BRAIN_FACT_TTL_SECONDS, DEFAULT_DEPS_DEV_PROJECT_URL, DEFAULT_DEPS_DEV_TIMEOUT_SECONDS, ) @@ -40,6 +43,7 @@ from devops_cli.github.repo_ref import is_repository_name from devops_cli.http.egress import EgressLevel from devops_cli.http.entry import http_client +from devops_cli.valkey.tiered import TieredMapping if TYPE_CHECKING: from devops_cli.roadmap.stores.store import RoadmapStore @@ -183,10 +187,22 @@ def _read_files(root: Path, paths: Sequence[str]) -> str: return "\n".join(texts) +# The packages that deps.dev links to each project, in the process and in the cache Valkey, by +# the project key in lower case (#4668). deps.dev answers each client the same. +_DEPS_DEV_FACTS: TieredMapping[frozenset[str]] = TieredMapping( + f"{CONST_VALKEY_BRAIN_PREFIX}:fact:deps-dev", + TypeAdapter(frozenset[str]), + ttl=DEFAULT_BRAIN_FACT_TTL_SECONDS, +) + + +@cached(_DEPS_DEV_FACTS, key=str.lower) def _linked_packages(project: str) -> frozenset[str]: """The keys of the packages that deps.dev links to `project` as their source, none when deps.dev does not know the project. Raises `httpx2.HTTPError` on another failed read and - `pydantic.ValidationError` on a malformed answer.""" + `pydantic.ValidationError` on a malformed answer. The read goes through the fact cache of the + project brain (#4668): a project that a process or another pod read in the last 24 hours sends + no request, and a failed read keeps nothing.""" url = DEFAULT_DEPS_DEV_PROJECT_URL.format(project=quote(project, safe="")) with http_client(EgressLevel.PUBLIC) as client: response = client.get(url, timeout=DEFAULT_DEPS_DEV_TIMEOUT_SECONDS) From 642ca8157f69483e7020e9bd393539828727b6a9 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:50:13 +0000 Subject: [PATCH 11/20] perf(k8s): raise the memory bound of valkey-devops to 256mb in 384Mi The listing snapshots of the public repositories (about 15 MB) and the tool facts join the embeddings and the threat-intelligence reads. At 96 MiB the old pod evicted 3,600 keys in 7 days. 256 MiB is two thirds of the 384Mi limit, so the three-quarters rule of the llm Valkeys holds, and so does decision 6 of #4624. --- k8s/llm/valkey-devops.yaml | 24 +++++++++++-------- .../tasks.md | 2 +- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/k8s/llm/valkey-devops.yaml b/k8s/llm/valkey-devops.yaml index d5dc204401..c5d3af36e4 100644 --- a/k8s/llm/valkey-devops.yaml +++ b/k8s/llm/valkey-devops.yaml @@ -1,7 +1,9 @@ # Valkey that devops-cli's Service and cluster jobs in namespace devops use as their cache (#1655): -# the embeddings of the texts they embed and their threat-intelligence reads. A settled roadmap -# item then costs no embedding request on the next round, though each round and each job is a -# new process with an empty memory cache. +# the embeddings of the texts they embed, their threat-intelligence reads, the listing snapshots of +# the public repositories and the PyPI and deps.dev facts of the alternatives check (#4668). A +# settled roadmap item then costs no embedding request on the next round, and a new pod reads the +# listing from the newest snapshot, though each round and each job is a new process with an empty +# memory cache. It holds no data of a private repository until it has role ACL users (#4704). # # It holds caches only. It keeps no file, evicts the least recently used key at its bound, and # starts empty after a restart. The cache Valkey of Open WebUI (valkey.yaml) keeps its state with @@ -63,11 +65,13 @@ spec: # The password goes into a config file on a memory volume rather than onto the command # line, where it would show in the process list. # - # Valkey keeps at most 96 MiB of data, three quarters of the 128Mi limit, as the other - # Valkeys of llm do (#711). One embedding of qwen3-embedding:0.6b is about 20 KB of JSON, - # so the bound holds about 4,800 of them, many times the open and closed issues that a - # roadmap run embeds. At the bound Valkey evicts the least recently used key: a key it - # evicts costs one more embedding request, not a lost state. + # Valkey keeps at most 256 MiB of data, two thirds of the 384Mi limit, which keeps the + # three-quarters rule of the Valkeys of llm (#711). The embeddings, the listing snapshots + # of the public repositories (about 15 MB with zlib, #4668) and the tool facts share the + # bound. One embedding of qwen3-embedding:0.6b is about 20 KB of JSON. At 96 MiB the old + # pod evicted 3,600 keys in 7 days. At the bound Valkey evicts the least recently used + # key: a key it evicts costs one more embedding request or listing read, not a lost + # state. command: - sh - -c @@ -78,7 +82,7 @@ spec: --save "" --appendonly no --dir /data - --maxmemory 96mb + --maxmemory 256mb --maxmemory-policy allkeys-lru env: - name: VALKEY_PASSWORD @@ -102,7 +106,7 @@ spec: memory: 32Mi limits: cpu: 500m - memory: 128Mi + memory: 384Mi livenessProbe: tcpSocket: port: 6379 diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index a3d80f5290..364366b0a4 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -51,7 +51,7 @@ Kind: behavior. Reads: `src/devops_cli/roadmap/alternatives.py`, `src/devops_cli Kind: other. Reads: `k8s/llm/valkey-devops.yaml`, `openspec/specs/llm-valkey/spec.md`. Changes: `k8s/llm/valkey-devops.yaml`. -- [ ] 6.1 Set `--maxmemory 256mb` in place of `--maxmemory 96mb` and the memory limit of the valkey container to `384Mi` in place of `128Mi` in `k8s/llm/valkey-devops.yaml`. Change the comment above `command`: Valkey keeps at most 256 MiB of data, two thirds of the 384Mi limit, which keeps the three-quarters rule of the llm Valkeys (#711); the embeddings, the listing snapshots of the public repositories and the tool facts share the bound, and at the bound Valkey evicts the least recently used key. Change the header comment to name the snapshots and the facts beside the embeddings and the threat-intelligence reads +- [x] 6.1 Set `--maxmemory 256mb` in place of `--maxmemory 96mb` and the memory limit of the valkey container to `384Mi` in place of `128Mi` in `k8s/llm/valkey-devops.yaml`. Change the comment above `command`: Valkey keeps at most 256 MiB of data, two thirds of the 384Mi limit, which keeps the three-quarters rule of the llm Valkeys (#711); the embeddings, the listing snapshots of the public repositories and the tool facts share the bound, and at the bound Valkey evicts the least recently used key. Change the header comment to name the snapshots and the facts beside the embeddings and the threat-intelligence reads - Verification: `$ uv run devops ci --check --only k8s` passes - Verification: `$ ! git grep -n -F 96mb k8s/llm/valkey-devops.yaml` passes From bbfff0aec20423d3a0fdd143b67374b72fe70e2b Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:51:21 +0000 Subject: [PATCH 12/20] docs: name the shared snapshot, the fact cache and the new Valkey bound k8s/README.md gives valkey-devops its new keys, its bound of 256 MiB in 384Mi and no key of a private repository until #4704. The intake page names the shared copy of the listing snapshot, the alternatives page the fact cache of PyPI and deps.dev, and the telemetry page the four new counters. --- docs/TELEMETRY.md | 4 ++++ docs/roadmap/alternatives.md | 4 ++-- docs/roadmap/intake.md | 2 +- k8s/README.md | 2 +- .../4668-share-the-listing-snapshot-in-valkey/tasks.md | 4 ++-- 5 files changed, 10 insertions(+), 6 deletions(-) diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 17a3a0b592..24498d9744 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -175,6 +175,10 @@ writes by name. | `devops_cli_roadmap_stage_gate_problems` | Histogram | `1` | Findings of the stage checks in one reply of a plan, one observation for each reply that the checks judged, by repo and reply: 0 for the first reply of a plan run and 1 more for each return, so at most roadmap.stage.gate_returns plus roadmap.stage.gate_return_extensions plus 1 values (#4851, #5440). A reply that passes the checks observes 0. One repository adds at most 17 series, at the ceilings of the two settings. | | `devops_cli_roadmap_stage_gate_refusals_total` | Counter | `1` | Replies of the stage model that a gate found a problem in, one count for each gate that found at least one problem in a reply, by repo and gate. A reply that two gates refuse adds 1 to each. The gates run again on the reply that answers a problem, so the count is of refused replies and not of refused items. One repository adds 17 series, one for each gate. | | `devops_cli_embedding_cache_lookups_total` | Counter | `1` | Embedding cache lookups, one for each text that an embedding request gets, by result: hit or miss. A hit names its tier: memory for the cache of the process, valkey, or disk for the cache file that keeps the vectors of intake between runs. | +| `devops_cli_brain_reads_total` | Counter | `1` | Reads of the project brain (#4668), by store (snapshot or fact) and result: memory or shared for the tier that gave the value, source when no tier held it, fallback when the shared tier failed or its breaker was open, and private for a repository that the shared tier does not hold. | +| `devops_cli_brain_writes_total` | Counter | `1` | Writes of the project brain to the shared tier (#4668), by store and result: shared, skipped while the tier failed, oversize for a value over 1 MiB that stays in memory, older when the shared snapshot is newer or another writer won, and private. | +| `devops_cli_valkey_cache_errors_total` | Counter | `1` | Commands of the Valkey cache tier that failed or that its open breaker did not send (#4668), by command (op) and error: timeout, connection, auth, reply, open, or budget for a load of a shared snapshot that passed its time budget. | +| `devops_cli_brain_github_requests_saved_total` | Counter | `1` | Listing pages of a full read that a process did not send because it took the shared snapshot (#4668), by store. | | `devops_cli_embedding_cache_size` | Gauge | `1` | Embeddings that the memory cache of the process held after its last embedding request. | | `devops_cli_rag_embedding_batch_size` | Gauge | `1` | Texts in each embedding request after the last change of the adaptive batch size. | | `devops_cli_rag_embedding_batch_resizes_total` | Counter | `1` | Changes of the adaptive embedding batch size, by action: additive_increase after enough fast batches, or multiplicative_decrease after a slow or failed batch. | diff --git a/docs/roadmap/alternatives.md b/docs/roadmap/alternatives.md index 7276fd25ef..f1e81694e9 100644 --- a/docs/roadmap/alternatives.md +++ b/docs/roadmap/alternatives.md @@ -4,7 +4,7 @@ ## What a check does -For each item, one agent run searches the web through the providers of `search.providers` (SearXNG, DuckDuckGo and Firecrawl by default). A provider that is not configured is skipped. A provider that fails or returns no hit passes the search on to the next one, and the first provider with a hit answers. It reads the facts of each candidate tool from GitHub and PyPI: its license, its last activity and whether it is archived. When `crawl4ai.url` is set, the run also has the tool `fetch_page`, which reads the text of one page through the Crawl4AI service. It takes an https URL that a search of the same run returned or that the item text names, and no other URL; it sends no request for any other URL. A run fetches at most 3 pages. The tool frames the text as data from an outside page, never an instruction, and names the source URL and the fetch date so that a comment can cite them. A failed fetch is a tool answer and uses one fetch. Each call counts in `devops_cli_roadmap_page_fetches_total` by `toolset` (`refine` or `alternatives`) and `result` (`ok`, `refused`, `limit` or `error`). The tool is off with no `crawl4ai.url`. +For each item, one agent run searches the web through the providers of `search.providers` (SearXNG, DuckDuckGo and Firecrawl by default). A provider that is not configured is skipped. A provider that fails or returns no hit passes the search on to the next one, and the first provider with a hit answers. It reads the facts of each candidate tool from GitHub and PyPI: its license, its last activity and whether it is archived. The PyPI facts come from the fact cache of the project brain for 24 hours, in the memory of the process and in the cache Valkey `valkey-devops`, so a package that a process or another pod read sends no request, and a failed read keeps nothing (#4668). When `crawl4ai.url` is set, the run also has the tool `fetch_page`, which reads the text of one page through the Crawl4AI service. It takes an https URL that a search of the same run returned or that the item text names, and no other URL; it sends no request for any other URL. A run fetches at most 3 pages. The tool frames the text as data from an outside page, never an instruction, and names the source URL and the fetch date so that a comment can cite them. A failed fetch is a tool answer and uses one fetch. Each call counts in `devops_cli_roadmap_page_fetches_total` by `toolset` (`refine` or `alternatives`) and `result` (`ok`, `refused`, `limit` or `error`). The tool is off with no `crawl4ai.url`. The verdict is `covers`, `partly` or `none`. For every item except those named below, the check accepts a verdict only after the run made an answered search. A search that no provider answered, and a refused query, do not count. A reply with no answered search gets one more turn to search. Every call of `search_web` counts toward the limit of searches. @@ -44,7 +44,7 @@ Once for a run that checks an item of no skip class, the check reads the invento 1. The SPDX SBOM that the dependency graph of the repository exports (`GET /repos/{owner}/{repo}/dependency-graph/sbom`), with one request. It holds the package URL of each package of a manifest, a lock file or a workflow. A PyPI package matches by its canonical name, an action by its repository (`pkg:githubactions/github/codeql-action/init` is `github/codeql-action`), and the npm package `@/` by the repository of the same name. A dependency graph that is off gives an empty SBOM. 2. The files under `roadmap.alternatives.inventory_paths` of a clone (`k8s`, `tf`, `.devcontainer`, `src/devops_cli/config/commands.py`, `src/devops_cli/roadmap/runner_tools.py` and `src/devops_cli/infra/ansible_facts.py` by default). They name the services, images and CLIs that no manifest holds, such as LiteLLM, Grafana or kubectl. The three source files name, with no version, the commands that devops-cli starts, each program that a Job needs or leaves out, and the Ansible commands; they take the place of the tools lock (#4363). The name of the repository or of the package counts as a whole word in any case, as `git grep -i -w -F` finds it. The Service row uses the clone of its lane. On a workstation, `--source ` gives the clone, and with no clone the check uses the other two sources. -3. deps.dev, which links a GitHub project to the packages whose source it is (`GET https://api.deps.dev/v3/projects/:packageversions`). The repository `modelcontextprotocol/python-sdk` is the PyPI package `mcp` of the SBOM. The check asks deps.dev only when the SBOM holds a package and the other two sources do not hold the tool, and one run asks once for each project. A failed read skips the item, and the run takes it again after `roadmap.alternatives.retry_days`. +3. deps.dev, which links a GitHub project to the packages whose source it is (`GET https://api.deps.dev/v3/projects/:packageversions`). The repository `modelcontextprotocol/python-sdk` is the PyPI package `mcp` of the SBOM. The check asks deps.dev only when the SBOM holds a package and the other two sources do not hold the tool, and one run asks once for each project. The answer comes from the same fact cache for 24 hours. A failed read skips the item, and the run takes it again after `roadmap.alternatives.retry_days`. The inventory lives for one run. diff --git a/docs/roadmap/intake.md b/docs/roadmap/intake.md index 2d4f7367b7..ff31695fab 100644 --- a/docs/roadmap/intake.md +++ b/docs/roadmap/intake.md @@ -118,7 +118,7 @@ Intake compares each candidate with every item and with every issue closed as no - A run reads the whole listing and writes a new snapshot when no snapshot is kept, when the snapshot cannot be read, when its schema key is not the current one, when its last full read is 24 hours old or older, and on `--full`. The full read removes an issue that left the repository. - The snapshot is a copy of GitHub, which stays the source of truth. A snapshot that intake cannot read or write gives a warning. A failed write keeps the earlier file, because intake writes a temporary file and renames it. -In the Service, the lane of `intake` runs its intake rounds and the scoped intake of each delivery one at a time, so one writer keeps the snapshot of each repository. Thus a scoped round with a kept snapshot sends one listing request when 100 or fewer issues changed. The poll still reconciles each change that moved an `updated_at` (ADR 0017), and the full read of each day removes an issue that left the repository. Each other lane reads every issue through a snapshot of its own, in `listing-` of the state directory, which only its worker writes (#4854, #5553). `SnapshotStore` in `src/devops_cli/roadmap/stores/listing_snapshot.py` is the seam for a store that the pods of the Service can share (#4517). +In the Service, the lane of `intake` runs its intake rounds and the scoped intake of each delivery one at a time, so one writer keeps the snapshot of each repository. Thus a scoped round with a kept snapshot sends one listing request when 100 or fewer issues changed. The poll still reconciles each change that moved an `updated_at` (ADR 0017), and the full read of each day removes an issue that left the repository. Each other lane reads every issue through a snapshot of its own, in `listing-` of the state directory, which only its worker writes (#4854, #5553). Each local file sits under a shared copy of each public repository in the cache Valkey `valkey-devops` (`TieredSnapshotStore` in `src/devops_cli/roadmap/stores/listing_shared.py`, #4668). A run takes the fit copy with the newer watermark, so a pod with no local snapshot reads only the changes since the shared watermark. A writer replaces the shared copy only when its watermark is not older. While Valkey is down, a run reads and writes its local file only. The shared tier holds no copy of a private repository until `valkey-devops` has role ACL users (#4704), and a failed read of the visibility counts as private. `devops_cli_brain_reads_total{store="snapshot"}` counts where each load came from, and `devops_cli_brain_github_requests_saved_total` counts the listing pages that a shared copy saved. ## A failed write diff --git a/k8s/README.md b/k8s/README.md index efb306102f..53f3cd7de0 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -282,7 +282,7 @@ The cache Valkey's policy `valkey-perimeter` (`llm/valkey.yaml`) admits Open Web The cache Valkey keeps at most 1536 MiB of data (`--maxmemory`), three quarters of its 2048Mi limit. The rest of the limit holds fragmentation and Valkey's own overhead. At the bound, Valkey refuses writes and evicts no key (`--maxmemory-policy noeviction`). Open WebUI keeps its session pools and token revocations there, and an evicted revocation makes a signed-out token valid again. The run index (`llm/valkey-runs.yaml`) uses the same policy with a bound of 512 MiB. `ValkeyMemoryNearBound` warns when the cache Valkey keeps its data above 80% of the bound for 10 minutes. The rule selects each exported Valkey with the policy `noeviction`, and the run index has no exporter, so the rule does not watch it. -devops-cli's cache Valkey (`llm/valkey-devops.yaml`) holds the caches of the roadmap Service and the cluster jobs: the embeddings that `EmbeddingsEngine` writes, and the threat-intelligence reads. Each round of the Service and each job is a new process with an empty memory cache, so without it intake embeds every item of the roadmap again on each round. The devops ConfigMap names it in `valkey.url`, and its password reaches the pods from `devops/devops-cli` as `DEVOPS_CLI_VALKEY_PASSWORD`, the variable of `valkey.password`. Its policy `valkey-devops-perimeter` admits namespace `devops` on TCP 6379 and the `monitoring` namespace on the exporter port 9121, and allows no egress. `llm-default-perimeter` leaves its pods out, and `devops-default-perimeter` lets namespace `devops` reach namespace `llm` on 6379 beside the gateway's 4000. It keeps at most 96 MiB of data, three quarters of its 128Mi limit, writes no RDB or AOF, and at the bound evicts the least recently used key (`--maxmemory-policy allkeys-lru`): an evicted key costs one more embedding request. It can't share the cache Valkey, which must not evict Open WebUI's state. +devops-cli's cache Valkey (`llm/valkey-devops.yaml`) holds the caches of the roadmap Service and the cluster jobs: the embeddings that `EmbeddingsEngine` writes, the threat-intelligence reads, the listing snapshots of the public repositories (`valkey:roadmap:v1:snapshot:/`, 7 days) and the PyPI and deps.dev facts of the alternatives check (`valkey:brain:v1:fact::`, 24 hours) (#4668). It holds no key of a private repository until it has role ACL users (#4704). Each round of the Service and each job is a new process with an empty memory cache, so without it intake embeds every item of the roadmap again on each round. The devops ConfigMap names it in `valkey.url`, and its password reaches the pods from `devops/devops-cli` as `DEVOPS_CLI_VALKEY_PASSWORD`, the variable of `valkey.password`. Its policy `valkey-devops-perimeter` admits namespace `devops` on TCP 6379 and the `monitoring` namespace on the exporter port 9121, and allows no egress. `llm-default-perimeter` leaves its pods out, and `devops-default-perimeter` lets namespace `devops` reach namespace `llm` on 6379 beside the gateway's 4000. It keeps at most 256 MiB of data, two thirds of its 384Mi limit, writes no RDB or AOF, and at the bound evicts the least recently used key (`--maxmemory-policy allkeys-lru`): an evicted key costs one more embedding request or listing read. While it is down, each process reads and writes its local tiers only and makes one connection attempt in each cooldown of 60 s. It can't share the cache Valkey, which must not evict Open WebUI's state. Qdrant requires the key of `llm/qdrant-api-key` (see Cluster Secrets) on every REST and gRPC request. Only `/`, `/healthz`, `/readyz`, `/livez` and the files of its web UI need no key. The qdrant container reads `api-key` as `QDRANT__SERVICE__API_KEY` and `read-only-api-key` as `QDRANT__SERVICE__READ_ONLY_API_KEY` through `env` in `llm/values-qdrant.yaml`. Open WebUI names the Service in `QDRANT_URI` and sends the admin key as `QDRANT_API_KEY`; the devops ConfigMap names it in `qdrant.url`, and a pod that loads `devops/devops-cli` with `envFrom`, such as a Job of CronJob `devops-cli` or the MCP server, gets the read-only key as `DEVOPS_CLI_QDRANT_API_KEY` (#3823). The runner pod and the roadmap Service hold no Qdrant key (#6518). So a devops pod holds the search path and no write or delete path. Only WorkflowTemplate `rag-ingest` writes, with the admin key. `devops-default-perimeter` admits namespace `llm` on TCP 6333, and `llm-default-perimeter` admits namespace `devops` on 6333 and no other new peer. Alloy scrapes `/metrics` with the admin key as a bearer token. Helm drops a key of `llm/values-qdrant.yaml` that the chart does not declare with no error, so read the values of the chart (`helm show values qdrant/qdrant --version `) when you add a key or bump the chart. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index 364366b0a4..bc8d068fd5 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -66,9 +66,9 @@ Kind: other. Reads: `src/devops_cli/roadmap/stores/listing_shared.py`, `k8s/llm/ Kind: other. Reads: `k8s/README.md`, `docs/roadmap/intake.md`, `docs/roadmap/alternatives.md`, `docs/TELEMETRY.md`, `docs/SERVICE_PATTERNS.md`, `CONTEXT.md`, `ARCHITECTURE.md`, `src/devops_cli/ai/knowledge_base/it_domains/tools/valkey.md`. Changes: `k8s/README.md`, `docs/roadmap/intake.md`, `docs/roadmap/alternatives.md`, `docs/TELEMETRY.md`. -- [ ] 8.1 In `k8s/README.md`, change the paragraph of `valkey-devops`: it holds the embeddings, the threat-intelligence reads, the listing snapshots of the public repositories and the tool facts, keeps at most 256 MiB of data, two thirds of its 384Mi limit, and holds no key of a private repository until #4704. In `docs/roadmap/intake.md`, say that the intake and the lanes keep their local file and share one copy of each public repository in `valkey-devops`, where the newest watermark wins, in place of "the seam for a store that the pods of the Service can share (#4517)". In `docs/roadmap/alternatives.md`, say that the PyPI and deps.dev facts come from the shared fact cache for 24 hours. Run `git grep -n -e 96mb -e "96 MiB" -e 128Mi -e SnapshotStore -e ValkeyCacheTier -- docs k8s/README.md CONTEXT.md ARCHITECTURE.md openspec/specs src/devops_cli/ai/knowledge_base`, and fix each other line that the change makes wrong; the ADRs are records and do not change +- [x] 8.1 In `k8s/README.md`, change the paragraph of `valkey-devops`: it holds the embeddings, the threat-intelligence reads, the listing snapshots of the public repositories and the tool facts, keeps at most 256 MiB of data, two thirds of its 384Mi limit, and holds no key of a private repository until #4704. In `docs/roadmap/intake.md`, say that the intake and the lanes keep their local file and share one copy of each public repository in `valkey-devops`, where the newest watermark wins, in place of "the seam for a store that the pods of the Service can share (#4517)". In `docs/roadmap/alternatives.md`, say that the PyPI and deps.dev facts come from the shared fact cache for 24 hours. Run `git grep -n -e 96mb -e "96 MiB" -e 128Mi -e SnapshotStore -e ValkeyCacheTier -- docs k8s/README.md CONTEXT.md ARCHITECTURE.md openspec/specs src/devops_cli/ai/knowledge_base`, and fix each other line that the change makes wrong; the ADRs are records and do not change - Verification: `$ ! git grep -n -F "96 MiB" k8s/README.md` passes -- [ ] 8.2 Regenerate `docs/TELEMETRY.md` with `uv run devops docs generate` for the four new counters. Change no text of the page by hand +- [x] 8.2 Regenerate `docs/TELEMETRY.md` with `uv run devops docs generate` for the four new counters. Change no text of the page by hand - Verification: `$ uv run devops ci docs` passes ## Criteria From 223e079c363308cda3f21dc59b488d2888a1dc93 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:53:53 +0000 Subject: [PATCH 13/20] test(valkey): record the contract scenarios of the shared tier A temporary pod of valkey/valkey:9.1.4-alpine, the image of valkey-devops, recorded the replies of watch_lost, hscan_bytes, rename_hash_ttl and expire_hdel_unlink. The records of the earlier scenarios did not change. The same pod measured the shared load of the devops-cli snapshot: 6,571 records, 15.7 MB in Valkey, five cold loads with a median of 1.89 s and a maximum of 2.61 s. The pod is deleted. --- .../proposal.md | 2 +- .../tasks.md | 8 +- tests/fixtures/valkey/recorded_exchanges.json | 335 ++++++++++++++++++ 3 files changed, 340 insertions(+), 5 deletions(-) diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md index 47f89462db..99c2572e85 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md @@ -61,7 +61,7 @@ Each premise was checked on 2026-11-21 against `origin/main` at ddad1a45e and th - The size of the snapshot, measured in the body on 2026-11-11: 4,615 records, 23.31 MB raw and 9.21 MB with zlib, p99 28,340 B and max 65,177 B for one record. Measured again on 2026-11-21 from the local snapshot of devops-cli (full read at 2026-11-20T22:13Z): 6,571 records, 37.54 MB raw, 14.13 MB with zlib for each record apart, p99 29,598 B and max 65,177 B raw, and max 23,700 B with zlib. Each record is far under the bound of 1 MiB, and the whole snapshot is over it, so the snapshot needs one field for each record. - The memory of `valkey-devops`, from the owner comment of 2026-11-19: `redis_config_maxmemory{job="valkey-devops"}` is 100,663,296 (96 MiB). The old pod peaked at 95.97 MiB and evicted 3,600 keys in 7 days, with a hit ratio of 98.9 %. The new pod held 40.9 MiB in 2,871 keys with 0 evictions. The live Deployment runs `valkey/valkey:9.1.4-alpine` with a 128Mi limit. The snapshots of the 6 public repositories add about 15 MB, so 256 MiB keeps the embeddings, the snapshots and the facts with room to spare. - The value of the shared snapshot comes with #4567, which is open. Today the Service runs intake in its own pod and keeps the snapshots on the volume `roadmap-service-home`, a PersistentVolumeClaim (`k8s/devops/roadmap-service/deployment.yaml:210`), so its rounds already read only the changes. The intake pods of #4567 start with no snapshot. The fact caches give value at once: the Service restarts at each release, and each restart empties the memory of the process. -- The load time of the shared devops-cli snapshot is measured in the build against a temporary Valkey pod of `valkey/valkey:9.1.4-alpine`, never against the live `valkey-devops`. The result and its command go into the pull request. +- The load time of the shared devops-cli snapshot, measured on 2026-11-21 against a temporary Valkey pod `valkey-snapshot-load` of `valkey/valkey:9.1.4-alpine` (`--maxmemory 256mb`, limit `384Mi`) through a loopback port-forward from the devcontainer, never against the live `valkey-devops`: the 6,571 records of the local snapshot took 3.09 s to write and 15,714,823 bytes in Valkey (`MEMORY USAGE`). Five cold loads through `ValkeySnapshotStore` took 1.89, 1.56, 1.51, 2.14 and 2.61 s: a median of 1.89 s and a maximum of 2.61 s, under the budget of 20 s. The script is `.data/agent/scratch/4668/measure_load.py`, which is not in git. ## Existing Tool Considered diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index bc8d068fd5..fa49f2afc9 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -2,10 +2,10 @@ ## 1. Record the Valkey behavior that the shared tier needs in the contract suite -Kind: other. Reads: `tests/support/valkey_scenarios.py`, `tests/support/valkey_recording.py`, `tests/support/valkey_replay.py`, `tests/valkey/test_valkey_contract.py`, `tests/fixtures/valkey/recorded_exchanges.json`. Changes: `tests/support/valkey_scenarios.py`, `tests/valkey/test_valkey_contract.py`, `tests/fixtures/valkey/recorded_exchanges.json`. +Kind: other. Reads: `tests/support/valkey_scenarios.py`, `tests/support/valkey_recording.py`, `tests/support/valkey_replay.py`, `tests/valkey/test_valkey_contract.py`, `tests/fixtures/valkey/recorded_exchanges.json`. Changes: `tests/support/valkey_scenarios.py`, `tests/support/valkey_replay.py`, `tests/support/valkey_recording.py`, `tests/valkey/test_valkey_contract.py`, `tests/fixtures/valkey/recorded_exchanges.json`. -- [ ] 1.1 Add the scenarios `watch_lost` (one client WATCHes a hash and reads a field, a second client writes the hash, and the first client's MULTI/EXEC raises `WatchError` and writes nothing), `hscan_bytes` (HSET of zlib bytes, then `HSCAN COUNT 500` with `NEVER_DECODE` gives the same bytes and the end cursor), `rename_hash_ttl` (a temporary hash with `EXPIRE 600` RENAMEd onto a hash that exists replaces it and keeps a TTL), and `expire_hdel_unlink` (`EXPIRE` sets a TTL, `HDEL` removes a field, `UNLINK` counts the removed keys) to `tests/support/valkey_scenarios.py`, each with its own key prefix and a delete of its keys at the end. Add their expected tuples to `EXPECTED` and the new commands to the "Covered" list of the docstring of `tests/valkey/test_valkey_contract.py` -- [ ] 1.2 Record the replies of a real server: start a temporary pod `valkey-contract-record` of the image that `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].image}'` gives (`valkey/valkey:9.1.4-alpine` on 2026-11-21) in namespace `llm` from the hardened pod spec of #4557 (non-root, read-only root, `activeDeadlineSeconds`, `--save ''`, `--appendonly no`), forward the loopback port 6390 to it, run `record_scenarios(6390)` of `tests/support/valkey_recording.py`, then stop the port-forward and delete the pod. Never forward to the live `valkey-devops` +- [x] 1.1 Add the scenarios `watch_lost` (one client WATCHes a hash and reads a field, a second client writes the hash, and the first client's MULTI/EXEC raises `WatchError` and writes nothing), `hscan_bytes` (HSET of zlib bytes, then `HSCAN COUNT 500` with `NEVER_DECODE` gives the same bytes and the end cursor), `rename_hash_ttl` (a temporary hash with `EXPIRE 600` RENAMEd onto a hash that exists replaces it and keeps a TTL), and `expire_hdel_unlink` (`EXPIRE` sets a TTL, `HDEL` removes a field, `UNLINK` counts the removed keys) to `tests/support/valkey_scenarios.py`, each with its own key prefix and a delete of its keys at the end. Add their expected tuples to `EXPECTED` and the new commands to the "Covered" list of the docstring of `tests/valkey/test_valkey_contract.py`. The record keeps a byte that is not UTF-8 as a lone surrogate (`surrogateescape`) in `tests/support/valkey_replay.py` and `tests/support/valkey_recording.py`, so a zlib value replays as the same bytes +- [x] 1.2 Record the replies of a real server: start a temporary pod `valkey-snapshot-load` (the pod of group 7, which records first, while it is empty) of the image that `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].image}'` gives (`valkey/valkey:9.1.4-alpine` on 2026-11-21) in namespace `llm` from the hardened pod spec of #4557 (non-root, read-only root, `activeDeadlineSeconds`, `--save ''`, `--appendonly no`), forward the loopback port 6390 to it, run `record_scenarios(6390)` of `tests/support/valkey_recording.py`, then stop the port-forward and delete the pod. Never forward to the live `valkey-devops` - Verification: `$ uv run devops ci test tests/valkey/test_valkey_contract.py` passes, over the fake and over the record ## 2. Give the cache tier the hash, TTL, rename and WATCH commands behind its breaker @@ -59,7 +59,7 @@ Kind: other. Reads: `k8s/llm/valkey-devops.yaml`, `openspec/specs/llm-valkey/spe Kind: other. Reads: `src/devops_cli/roadmap/stores/listing_shared.py`, `k8s/llm/valkey-devops.yaml`. Changes: none; the result goes into the pull request body. -- [ ] 7.1 Start a temporary pod `valkey-snapshot-load` of the image that `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].image}'` gives (`valkey/valkey:9.1.4-alpine` on 2026-11-21) in namespace `llm` from the hardened pod spec of group 1, with `--maxmemory 256mb` and a memory limit of `384Mi`, and forward a loopback port to it. With a script under `.data/agent/scratch/`, read the local snapshot of devops-cli, save it through `ValkeySnapshotStore` on a client of that port, then time five cold loads with a new store each. Write the record count, the bytes in Valkey (`MEMORY USAGE` of the key) and the median and the maximum of the load times into the pull request body. Stop the port-forward and delete the pod. Never connect to the live `valkey-devops` +- [x] 7.1 Start a temporary pod `valkey-snapshot-load` of the image that `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].image}'` gives (`valkey/valkey:9.1.4-alpine` on 2026-11-21) in namespace `llm` from the hardened pod spec of group 1, with `--maxmemory 256mb` and a memory limit of `384Mi`, and forward a loopback port to it. With a script under `.data/agent/scratch/`, read the local snapshot of devops-cli, save it through `ValkeySnapshotStore` on a client of that port, then time five cold loads with a new store each. Write the record count, the bytes in Valkey (`MEMORY USAGE` of the key) and the median and the maximum of the load times into the pull request body. Stop the port-forward and delete the pod. Never connect to the live `valkey-devops` - Verification: each of the five loads ends under 20 s, and `kubectl -n llm get pod valkey-snapshot-load` finds no pod after the step ## 8. Update the documents that the change makes wrong diff --git a/tests/fixtures/valkey/recorded_exchanges.json b/tests/fixtures/valkey/recorded_exchanges.json index 4b5eed6068..622cc4d4f8 100644 --- a/tests/fixtures/valkey/recorded_exchanges.json +++ b/tests/fixtures/valkey/recorded_exchanges.json @@ -731,6 +731,341 @@ ], "reply": ":1\r\n" } + ], + "watch_lost": [ + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-NAME", + "valkey-py" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-VER", + "6.2.0" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "HSET", + "devops-contract:watch_lost:hash", + "meta", + "first" + ], + "reply": ":1\r\n" + }, + { + "command": [ + "WATCH", + "devops-contract:watch_lost:hash" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "HGET", + "devops-contract:watch_lost:hash", + "meta" + ], + "reply": "$5\r\nfirst\r\n" + }, + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-NAME", + "valkey-py" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-VER", + "6.2.0" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "HSET", + "devops-contract:watch_lost:hash", + "meta", + "other" + ], + "reply": ":0\r\n" + }, + { + "command": [ + "MULTI" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "HSET", + "devops-contract:watch_lost:hash", + "meta", + "mine" + ], + "reply": "+QUEUED\r\n" + }, + { + "command": [ + "EXEC" + ], + "reply": "*-1\r\n" + }, + { + "command": [ + "HGET", + "devops-contract:watch_lost:hash", + "meta" + ], + "reply": "$5\r\nother\r\n" + }, + { + "command": [ + "DEL", + "devops-contract:watch_lost:hash" + ], + "reply": ":1\r\n" + } + ], + "hscan_bytes": [ + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-NAME", + "valkey-py" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-VER", + "6.2.0" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "HSET", + "devops-contract:hscan_bytes:hash", + "1", + "x\udc9c\udcabV\udcca+\udccdMJ-R\udcb2R0\udcd4QP*\udcc9,\udcc9I\u0005\udcb2\udc95RR\udccb\udcf2\u000b\udc8a\u0015\udc92\udcf3\udcf3J\udc8a\u0012\udc93K\udc94j\udcab\u0007N!\u0000u\u00116\udcbd", + "2", + "x\udc9c\udcabV\udcca+\udccdMJ-R\udcb2R0\udcd4QP*\udcc9,\udcc9I\u0005\udcb2\udc95RR\udccb\udcf2\u000b\udc8a\u0015\udc92\udcf3\udcf3J\udc8a\u0012\udc93K\udc94j\udcab\u0007N!\u0000u\u00116\udcbd" + ], + "reply": ":2\r\n" + }, + { + "command": [ + "HSCAN", + "devops-contract:hscan_bytes:hash", + "0", + "COUNT", + "500" + ], + "reply": "*2\r\n$1\r\n0\r\n*4\r\n$1\r\n1\r\n$51\r\nx\udc9c\udcabV\udcca+\udccdMJ-R\udcb2R0\udcd4QP*\udcc9,\udcc9I\u0005\udcb2\udc95RR\udccb\udcf2\u000b\udc8a\u0015\udc92\udcf3\udcf3J\udc8a\u0012\udc93K\udc94j\udcab\u0007N!\u0000u\u00116\udcbd\r\n$1\r\n2\r\n$51\r\nx\udc9c\udcabV\udcca+\udccdMJ-R\udcb2R0\udcd4QP*\udcc9,\udcc9I\u0005\udcb2\udc95RR\udccb\udcf2\u000b\udc8a\u0015\udc92\udcf3\udcf3J\udc8a\u0012\udc93K\udc94j\udcab\u0007N!\u0000u\u00116\udcbd\r\n" + }, + { + "command": [ + "HGET", + "devops-contract:hscan_bytes:hash", + "1" + ], + "reply": "$51\r\nx\udc9c\udcabV\udcca+\udccdMJ-R\udcb2R0\udcd4QP*\udcc9,\udcc9I\u0005\udcb2\udc95RR\udccb\udcf2\u000b\udc8a\u0015\udc92\udcf3\udcf3J\udc8a\u0012\udc93K\udc94j\udcab\u0007N!\u0000u\u00116\udcbd\r\n" + }, + { + "command": [ + "DEL", + "devops-contract:hscan_bytes:hash" + ], + "reply": ":1\r\n" + } + ], + "rename_hash_ttl": [ + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-NAME", + "valkey-py" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-VER", + "6.2.0" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "HSET", + "devops-contract:rename_hash_ttl:hash", + "1", + "old", + "2", + "old" + ], + "reply": ":2\r\n" + }, + { + "command": [ + "HSET", + "devops-contract:rename_hash_ttl:next", + "1", + "new" + ], + "reply": ":1\r\n" + }, + { + "command": [ + "EXPIRE", + "devops-contract:rename_hash_ttl:next", + "600" + ], + "reply": ":1\r\n" + }, + { + "command": [ + "RENAME", + "devops-contract:rename_hash_ttl:next", + "devops-contract:rename_hash_ttl:hash" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "TTL", + "devops-contract:rename_hash_ttl:hash" + ], + "reply": ":600\r\n" + }, + { + "command": [ + "HGETALL", + "devops-contract:rename_hash_ttl:hash" + ], + "reply": "*2\r\n$1\r\n1\r\n$3\r\nnew\r\n" + }, + { + "command": [ + "EXISTS", + "devops-contract:rename_hash_ttl:next" + ], + "reply": ":0\r\n" + }, + { + "command": [ + "DEL", + "devops-contract:rename_hash_ttl:hash" + ], + "reply": ":1\r\n" + } + ], + "expire_hdel_unlink": [ + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-NAME", + "valkey-py" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "CLIENT", + "SETINFO", + "LIB-VER", + "6.2.0" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "HSET", + "devops-contract:expire_hdel_unlink:hash", + "meta", + "m", + "1", + "a", + "2", + "b" + ], + "reply": ":3\r\n" + }, + { + "command": [ + "SET", + "devops-contract:expire_hdel_unlink:other", + "x" + ], + "reply": "+OK\r\n" + }, + { + "command": [ + "EXPIRE", + "devops-contract:expire_hdel_unlink:hash", + "60" + ], + "reply": ":1\r\n" + }, + { + "command": [ + "TTL", + "devops-contract:expire_hdel_unlink:hash" + ], + "reply": ":60\r\n" + }, + { + "command": [ + "HDEL", + "devops-contract:expire_hdel_unlink:hash", + "2", + "3" + ], + "reply": ":1\r\n" + }, + { + "command": [ + "HKEYS", + "devops-contract:expire_hdel_unlink:hash" + ], + "reply": "*2\r\n$4\r\nmeta\r\n$1\r\n1\r\n" + }, + { + "command": [ + "UNLINK", + "devops-contract:expire_hdel_unlink:hash", + "devops-contract:expire_hdel_unlink:other", + "devops-contract:expire_hdel_unlink:missing" + ], + "reply": ":2\r\n" + }, + { + "command": [ + "EXISTS", + "devops-contract:expire_hdel_unlink:hash" + ], + "reply": ":0\r\n" + } ] } } From 5747462f0bd8fb803bcbd7d1c75c7613c054504b Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 01:57:43 +0000 Subject: [PATCH 14/20] fix(valkey): reset the memory tiers by a generation, not a registry The test-tree row refused the registry of the tiered mappings as a container that the floor does not reset. reset_tiered_mappings now starts a new generation, and a mapping empties its memory tier at its next access. The proposal gives the measured load in place of the path of the script. --- .../proposal.md | 2 +- .../tasks.md | 2 +- src/devops_cli/valkey/tiered.py | 39 +++++++++++-------- 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md index 99c2572e85..e0755ae5d9 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md @@ -61,7 +61,7 @@ Each premise was checked on 2026-11-21 against `origin/main` at ddad1a45e and th - The size of the snapshot, measured in the body on 2026-11-11: 4,615 records, 23.31 MB raw and 9.21 MB with zlib, p99 28,340 B and max 65,177 B for one record. Measured again on 2026-11-21 from the local snapshot of devops-cli (full read at 2026-11-20T22:13Z): 6,571 records, 37.54 MB raw, 14.13 MB with zlib for each record apart, p99 29,598 B and max 65,177 B raw, and max 23,700 B with zlib. Each record is far under the bound of 1 MiB, and the whole snapshot is over it, so the snapshot needs one field for each record. - The memory of `valkey-devops`, from the owner comment of 2026-11-19: `redis_config_maxmemory{job="valkey-devops"}` is 100,663,296 (96 MiB). The old pod peaked at 95.97 MiB and evicted 3,600 keys in 7 days, with a hit ratio of 98.9 %. The new pod held 40.9 MiB in 2,871 keys with 0 evictions. The live Deployment runs `valkey/valkey:9.1.4-alpine` with a 128Mi limit. The snapshots of the 6 public repositories add about 15 MB, so 256 MiB keeps the embeddings, the snapshots and the facts with room to spare. - The value of the shared snapshot comes with #4567, which is open. Today the Service runs intake in its own pod and keeps the snapshots on the volume `roadmap-service-home`, a PersistentVolumeClaim (`k8s/devops/roadmap-service/deployment.yaml:210`), so its rounds already read only the changes. The intake pods of #4567 start with no snapshot. The fact caches give value at once: the Service restarts at each release, and each restart empties the memory of the process. -- The load time of the shared devops-cli snapshot, measured on 2026-11-21 against a temporary Valkey pod `valkey-snapshot-load` of `valkey/valkey:9.1.4-alpine` (`--maxmemory 256mb`, limit `384Mi`) through a loopback port-forward from the devcontainer, never against the live `valkey-devops`: the 6,571 records of the local snapshot took 3.09 s to write and 15,714,823 bytes in Valkey (`MEMORY USAGE`). Five cold loads through `ValkeySnapshotStore` took 1.89, 1.56, 1.51, 2.14 and 2.61 s: a median of 1.89 s and a maximum of 2.61 s, under the budget of 20 s. The script is `.data/agent/scratch/4668/measure_load.py`, which is not in git. +- The load time of the shared devops-cli snapshot, measured on 2026-11-21 against a temporary Valkey pod `valkey-snapshot-load` of `valkey/valkey:9.1.4-alpine` (`--maxmemory 256mb`, limit `384Mi`) through a loopback port-forward from the devcontainer, never against the live `valkey-devops`: the 6,571 records of the local snapshot took 3.09 s to write and 15,714,823 bytes in Valkey (`MEMORY USAGE`). Five cold loads through `ValkeySnapshotStore` took 1.89, 1.56, 1.51, 2.14 and 2.61 s: a median of 1.89 s and a maximum of 2.61 s, under the budget of 20 s. Each load used a new client and a new store, and read `meta` and then the records with `HSCAN COUNT 500`. ## Existing Tool Considered diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index fa49f2afc9..17abc79ecc 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -25,7 +25,7 @@ Adds: `TieredMapping`, `reset_tiered_mappings`, `schema_key_of`, `count_read`, ` - [x] 3.1 Write `tests/valkey/test_tiered.py`: `test_a_shared_read_fills_the_memory_tier` (T1); `test_a_down_shared_tier_gives_the_source_value_and_keeps_the_write_in_memory` (T2: `connected = False`, two reads through `cachetools.cached` within one cooldown, one command reaches the fake, `result="fallback"` and `result="skipped"` counted); `test_an_oversize_value_stays_in_memory_and_each_key_has_a_ttl` (T5: an encoded value of 1 MiB and one byte sends no command, and each key on the fake has a TTL above 0); `test_a_value_of_an_old_kind_or_schema_is_read_from_the_source` (T6); and `test_the_brain_counters_send_only_fixed_labels` for the requirement `The brain counters have bounded labels`, on the OTLP fake - Verification: `$ uv run devops ci test tests/valkey/test_tiered.py` fails on the base -- [x] 3.2 Add `TieredMapping` to the new `src/devops_cli/valkey/tiered.py`: a `MutableMapping` with text keys, a key prefix, a pydantic `TypeAdapter` of its value type, a JSON value with its schema key in front (`:`), a TTL, an in-process `cachetools.TTLCache` of `DEFAULT_BRAIN_MEMORY_ENTRIES`, and the tier of `shared_cache_tier()`, built on first use. Each value in Valkey holds the schema key of its type (the first 16 hex characters of the sha256 of its JSON schema); another schema key is a miss. A read counts `BRAIN_READS_TOTAL` and a write `BRAIN_WRITES_TOTAL`; a value over `DEFAULT_BRAIN_VALUE_MAX_BYTES` (1 MiB) stays in memory and counts `oversize`. `__iter__` and `__len__` cover the in-process tier. Each mapping joins a registry that `reset_tiered_mappings` clears, and `tests/conftest.py` adds `"devops_cli.valkey.tiered": ("reset_tiered_mappings",)` to `_PROCESS_STATE_RESETS`. Add the defaults and the key prefixes `valkey:brain:v1` and `valkey:roadmap:v1` (`CONST_VALKEY_BRAIN_PREFIX`, `CONST_VALKEY_ROADMAP_PREFIX`) +- [x] 3.2 Add `TieredMapping` to the new `src/devops_cli/valkey/tiered.py`: a `MutableMapping` with text keys, a key prefix, a pydantic `TypeAdapter` of its value type, a JSON value with its schema key in front (`:`), a TTL, an in-process `cachetools.TTLCache` of `DEFAULT_BRAIN_MEMORY_ENTRIES`, and the tier of `shared_cache_tier()`, built on first use. Each value in Valkey holds the schema key of its type (the first 16 hex characters of the sha256 of its JSON schema); another schema key is a miss. A read counts `BRAIN_READS_TOTAL` and a write `BRAIN_WRITES_TOTAL`; a value over `DEFAULT_BRAIN_VALUE_MAX_BYTES` (1 MiB) stays in memory and counts `oversize`. `__iter__` and `__len__` cover the in-process tier. `reset_tiered_mappings` starts a new generation of the memory tiers, which each mapping empties at its next access, and `tests/conftest.py` adds `"devops_cli.valkey.tiered": ("reset_tiered_mappings",)` to `_PROCESS_STATE_RESETS`. Add the defaults and the key prefixes `valkey:brain:v1` and `valkey:roadmap:v1` (`CONST_VALKEY_BRAIN_PREFIX`, `CONST_VALKEY_ROADMAP_PREFIX`) - Verification: `$ uv run devops ci test tests/valkey/test_tiered.py` passes ## 4. Share the listing snapshot through the shared tier diff --git a/src/devops_cli/valkey/tiered.py b/src/devops_cli/valkey/tiered.py index 1b52595bae..811f8a2f5d 100644 --- a/src/devops_cli/valkey/tiered.py +++ b/src/devops_cli/valkey/tiered.py @@ -31,7 +31,6 @@ import json import logging import threading -import weakref from collections.abc import Iterator, MutableMapping from typing import Any, Final @@ -51,9 +50,10 @@ # The length of a schema key, in hex characters. _SCHEMA_KEY_CHARS: Final = 16 -# Each mapping of the process by its id, so `reset_tiered_mappings` empties their memory tiers. A -# mapping compares as a mapping and has no hash, so a weak set cannot hold it. -_MAPPINGS: weakref.WeakValueDictionary[int, TieredMapping[Any]] = weakref.WeakValueDictionary() +# The generation of the memory tiers of the process. `reset_tiered_mappings` starts a new one, and +# a mapping empties its memory tier when it next sees a new generation, so no registry keeps the +# mappings. +_generation = 0 def schema_key_of(adapter: TypeAdapter[Any]) -> str: @@ -101,7 +101,7 @@ def __init__( self._schema_key: str | None = None self._memory: TTLCache[str, V] = TTLCache(maxsize=entries, ttl=ttl, timer=_monotonic) self._lock = threading.Lock() - _MAPPINGS[id(self)] = self + self._generation = _generation @property def schema_key(self) -> str: @@ -116,7 +116,8 @@ def shared_key(self, key: str) -> str: def __getitem__(self, key: str) -> V: with self._lock: - held = [self._memory[key]] if key in self._memory else [] + memory = self._current() + held = [memory[key]] if key in memory else [] if held: count_read(self.store, BrainRead.MEMORY) return held[0] @@ -125,7 +126,7 @@ def __getitem__(self, key: str) -> V: found = [] if text is None else self._decoded(text) if found: with self._lock: - self._memory[key] = found[0] + self._current()[key] = found[0] count_read(self.store, BrainRead.SHARED) return found[0] down = tier is None or tier.is_open @@ -134,7 +135,7 @@ def __getitem__(self, key: str) -> V: def __setitem__(self, key: str, value: V) -> None: with self._lock: - self._memory[key] = value + self._current()[key] = value encoded = self.schema_key.encode() + _SEPARATOR.encode() + self._adapter.dump_json(value) if len(encoded) > DEFAULT_BRAIN_VALUE_MAX_BYTES: count_write(self.store, BrainWrite.OVERSIZE) @@ -145,24 +146,27 @@ def __setitem__(self, key: str, value: V) -> None: def __delitem__(self, key: str) -> None: with self._lock: - self._memory.pop(key, None) + self._current().pop(key, None) tier = shared_cache_tier() if tier is not None: tier.unlink(self.shared_key(key)) def __iter__(self) -> Iterator[str]: with self._lock: - keys = list(self._memory) + keys = list(self._current()) return iter(keys) def __len__(self) -> int: with self._lock: - return len(self._memory) + return len(self._current()) - def clear_memory(self) -> None: - """Empty the memory tier, as a new process starts; Valkey keeps its values.""" - with self._lock: + def _current(self) -> TTLCache[str, V]: + """The memory tier, emptied first when `reset_tiered_mappings` started a new generation. + The caller holds the lock.""" + if self._generation != _generation: self._memory.clear() + self._generation = _generation + return self._memory def _decoded(self, text: str) -> list[V]: """The value that `text` from Valkey holds, or nothing for another schema key or a value @@ -182,9 +186,10 @@ def _decoded(self, text: str) -> list[V]: def reset_tiered_mappings() -> None: - """Empty the memory tier of each mapping of the process.""" - for mapping in list(_MAPPINGS.values()): - mapping.clear_memory() + """Empty the memory tier of each mapping of the process, as a new process starts; Valkey keeps + its values.""" + global _generation + _generation += 1 __all__ = [ From a481d61f6e5dbd795df144dff2dfe1addeeac745 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 02:10:00 +0000 Subject: [PATCH 15/20] test(valkey): read the silent Valkey host through the tiered mapping T3 now reads two facts through cachetools.cached over a TieredMapping: each read gives the source value, the first Valkey read counts a timeout, and no later command opens a second connection. --- tests/valkey/test_valkey_cache_tier.py | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/tests/valkey/test_valkey_cache_tier.py b/tests/valkey/test_valkey_cache_tier.py index 1aef582b1a..100d31786c 100644 --- a/tests/valkey/test_valkey_cache_tier.py +++ b/tests/valkey/test_valkey_cache_tier.py @@ -377,13 +377,17 @@ def test_a_silent_valkey_times_out_and_opens_the_breaker( ) -> None: """T3: a Valkey host that accepts the connection and answers no command costs one timeout. - The tier waits at most 0.25 s for a connection and `valkey.timeout` for a reply. The first - read is a miss that counts `timeout`, the breaker opens, and the next read opens no second - connection to the host. + The tier waits at most 0.25 s for a connection and `valkey.timeout` for a reply. A fact read + through the tiered mapping gets the source value; its Valkey read counts `timeout` and opens + the breaker, and no later command opens a second connection to the host. """ + from cachetools import cached + from pydantic import TypeAdapter + from devops_cli.config.defaults import DEFAULT_VALKEY_CACHE_CONNECT_TIMEOUT_SECONDS from devops_cli.config.settings import reset_settings_cache from devops_cli.valkey.cache import shared_cache_tier + from devops_cli.valkey.tiered import TieredMapping monkeypatch.setenv("DEVOPS_CLI_VALKEY_URL", f"valkey://127.0.0.1:{silent_valkey.port}") monkeypatch.setenv("DEVOPS_CLI_VALKEY_TIMEOUT", "0.05") @@ -391,7 +395,11 @@ def test_a_silent_valkey_times_out_and_opens_the_breaker( tier = shared_cache_tier() assert tier is not None - reads = (tier.get("fact"), tier.get("fact")) + @cached(TieredMapping("valkey:brain:v1:fact:test", TypeAdapter(str), ttl=60), key=str) + def read(name: str) -> str: + return f"source {name}" + + reads = (read("a"), read("b")) assert ( tier.client.connect_timeout <= DEFAULT_VALKEY_CACHE_CONNECT_TIMEOUT_SECONDS, @@ -399,4 +407,10 @@ def test_a_silent_valkey_times_out_and_opens_the_breaker( tier.is_open, silent_valkey.connections, _errors(otlp), - ) == (True, (None, None), True, 1, {("get", "timeout"): 1.0, ("get", "open"): 1.0}) + ) == ( + True, + ("source a", "source b"), + True, + 1, + {("get", "timeout"): 1.0, ("get", "open"): 1.0, ("set", "open"): 2.0}, + ) From 798ef26f9b48c11155ce3399685edc9c9f88bcbd Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 02:38:09 +0000 Subject: [PATCH 16/20] test(roadmap): check the shared snapshot writes, misses, private keys and counts A save of the records that the shared copy holds writes no record. A new meta of the same records during a load keeps the shared copy. A time with no UTC offset or a record past 1 MiB is a miss. A repository that became private leaves the shared tier. One key holds each spelling of a name. A load from the local file counts local. A lost connection in a WATCH transaction opens the breaker. The Valkey fake runs a test action after each command, in place of test subclasses of the cache tier. --- tests/roadmap/stores/test_listing_shared.py | 270 +++++++++++++++++--- tests/support/fakes/valkey.py | 52 +++- tests/valkey/test_valkey_cache_tier.py | 34 +++ 3 files changed, 318 insertions(+), 38 deletions(-) diff --git a/tests/roadmap/stores/test_listing_shared.py b/tests/roadmap/stores/test_listing_shared.py index 7b621570e1..89b1ec1fc0 100644 --- a/tests/roadmap/stores/test_listing_shared.py +++ b/tests/roadmap/stores/test_listing_shared.py @@ -324,22 +324,19 @@ def test_a_trial_after_the_cooldown_lets_the_newer_snapshot_replace_the_older( ) -class _RacingTier(ValkeyCacheTier): - """A cache tier whose WATCH transaction lets another writer write before its EXEC.""" +def _between_watch_and_exec(action: Callable[[], None]) -> Callable[[tuple[Any, ...]], None]: + """An `after_command` hook of the fake that runs `action` once, after the read of the first + WATCH transaction and before its EXEC.""" + watched: list[tuple[Any, ...]] = [] - def __init__(self, server: FakeServer, race: Callable[[], None]) -> None: - super().__init__(valkey_client_on(server)) - self._race = race + def hook(command: tuple[Any, ...]) -> None: + if command[0] == "WATCH": + watched.append(command) + elif command[0] == "HGET" and len(watched) == 1: + watched.append(command) + action() - def watch_and_write( - self, key: str, field: str, decide: Callable[[bytes | None], Any] - ) -> bool | None: - def racing(meta: bytes | None) -> Any: - commands = decide(meta) - self._race() - return commands - - return super().watch_and_write(key, field, racing) + return hook def test_an_older_writer_loses_its_watch_transaction( @@ -350,8 +347,13 @@ def test_an_older_writer_loses_its_watch_transaction( leaves no temporary key.""" _valkey_store(shared_valkey).save(_snapshot(STARTED, 1)) other = _valkey_store(ValkeyCacheTier(valkey_client_on(valkey_server))) - racing = _RacingTier( - valkey_server, lambda: other.save(_snapshot(STARTED + timedelta(minutes=30), 3, 1)) + racing = ValkeyCacheTier( + valkey_client_on( + valkey_server, + after_command=_between_watch_and_exec( + lambda: other.save(_snapshot(STARTED + timedelta(minutes=30), 3, 1)) + ), + ) ) otlp.clear() @@ -465,22 +467,6 @@ def test_no_visibility_read_without_the_shared_tier( assert runner.calls == [] -class _SlowTier(ValkeyCacheTier): - """A cache tier whose second `HSCAN` takes 21 s on the `clock` fixture.""" - - def __init__(self, server: FakeServer, clock: ClockFake) -> None: - super().__init__(valkey_client_on(server)) - self._clock = clock - self.scans = 0 - - def hscan(self, key: str, cursor: int, count: int) -> tuple[int, dict[str, bytes]] | None: - self.scans += 1 - step = super().hscan(key, cursor, count) - if self.scans == 2: - self._clock.shift(21) - return step - - def test_a_shared_load_past_its_budget_falls_back( tmp_path: Path, valkey_server: FakeServer, @@ -493,14 +479,228 @@ def test_a_shared_load_past_its_budget_falls_back( local = _snapshot(STARTED - timedelta(hours=1), 1) FileSnapshotStore(tmp_path).save(local) _valkey_store(shared_valkey).save(_snapshot(STARTED, *range(1200, 0, -1))) - slow = _SlowTier(valkey_server, clock) + scans: list[tuple[Any, ...]] = [] + + def slow(command: tuple[Any, ...]) -> None: + if command[0] == "HSCAN": + scans.append(command) + if len(scans) == 2: + clock.shift(21) + + slow_tier = ValkeyCacheTier(valkey_client_on(valkey_server, after_command=slow)) otlp.clear() - loaded = _tiered(tmp_path, shared=lambda: _valkey_store(slow)).load(REPO) + loaded = _tiered(tmp_path, shared=lambda: _valkey_store(slow_tier)).load(REPO) - assert (loaded, slow.scans, _errors(otlp), _reads(otlp)) == ( + assert (loaded, len(scans), _errors(otlp), _reads(otlp)) == ( local, 2, {("hscan", "budget"): 1.0}, {("snapshot", "fallback"): 1.0}, ) + + +def _meta(server: FakeServer) -> bytes | None: + """The `meta` field of the shared snapshot as Valkey holds it.""" + value: bytes | None = FakeValkey(server=server).hget(SNAPSHOT_KEY, "meta") + return value + + +def test_a_save_of_the_records_that_the_shared_copy_holds_writes_no_record( + tmp_path: Path, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """Two lanes of one process hold the same 1,200 records and watermark, with full reads at + 08:00 and 09:00, and a new process holds them too. After the first save of each lane, a save + sends no record and no transaction, keeps `meta` as it is, and counts `unchanged`.""" + sent: list[str] = [] + lanes = _valkey_store( + ValkeyCacheTier( + valkey_client_on(valkey_server, after_command=lambda command: sent.append(command[0])) + ) + ) + records = range(1200, 0, -1) + older = _snapshot(STARTED, *records, full_at=STARTED - timedelta(hours=2)) + newer = _snapshot(STARTED, *records, full_at=STARTED - timedelta(hours=1)) + lane_a = _tiered(tmp_path / "a", shared=lambda: lanes) + lane_b = _tiered(tmp_path / "b", shared=lambda: lanes) + lane_a.save(older) + lane_b.save(newer) + first = _meta(valkey_server) + sent.clear() + otlp.clear() + + for _ in range(2): + lane_a.save(older) + lane_b.save(newer) + new_process = _valkey_store(ValkeyCacheTier(valkey_client_on(valkey_server))) + _tiered(tmp_path / "c", shared=lambda: new_process).save(older) + + assert (set(sent), _meta(valkey_server) == first, _writes(otlp), _keys(valkey_server)) == ( + {"HGET", "EXPIRE"}, + True, + {("snapshot", "unchanged"): 5.0}, + [SNAPSHOT_KEY], + ) + + +def test_a_new_meta_of_the_same_records_during_a_load_keeps_the_shared_copy( + tmp_path: Path, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """A writer saves the same 1,200 records with a newer full read while a cold process scans + them. The reader still takes the shared copy, because the records that it read are the ones + that the new `meta` names.""" + writer = _valkey_store(ValkeyCacheTier(valkey_client_on(valkey_server))) + records = range(1200, 0, -1) + writer.save(_snapshot(STARTED, *records, full_at=STARTED - timedelta(hours=2))) + + def write_during_the_scan(command: tuple[Any, ...]) -> None: + if command[0] == "HSCAN" and command[2] == 0: + writer.save(_snapshot(STARTED, *records, full_at=STARTED - timedelta(hours=1))) + + reader = _valkey_store( + ValkeyCacheTier(valkey_client_on(valkey_server, after_command=write_during_the_scan)) + ) + otlp.clear() + + loaded = _tiered(tmp_path, shared=lambda: reader).load(REPO) + + assert (None if loaded is None else len(loaded.issues), _reads(otlp)) == ( + 1200, + {("snapshot", "shared"): 1.0}, + ) + + +def _naive_meta(server: FakeServer) -> None: + """Write the times of `meta` with no UTC offset.""" + import json + + writer = FakeValkey(server=server) + raw = writer.hget(SNAPSHOT_KEY, "meta") + assert raw is not None + meta = json.loads(raw) + meta |= {"full_at": "2026-01-01T09:00:00", "watermark": "2026-01-01T10:00:00"} + writer.hset(SNAPSHOT_KEY, "meta", json.dumps(meta)) + + +def _expanding_record(server: FakeServer) -> None: + """Write a record whose zlib value expands to more than 1 MiB of JSON.""" + import zlib + + from devops_cli.config.defaults import DEFAULT_BRAIN_VALUE_MAX_BYTES + + record = IssueRecord( + number=2, + title="Issue 2", + url=f"https://github.com/{REPO}/issues/2", + body="x" * DEFAULT_BRAIN_VALUE_MAX_BYTES, + updated_at=STARTED, + ) + FakeValkey(server=server).hset( + SNAPSHOT_KEY, "2", zlib.compress(record.model_dump_json().encode()) + ) + + +def _no_change(server: FakeServer) -> None: + """Leave the shared copy as the writer wrote it.""" + + +@pytest.mark.parametrize( + ("spoil", "naive_record"), + [ + pytest.param(_naive_meta, False, id="naive-meta"), + pytest.param(_no_change, True, id="naive-record"), + pytest.param(_expanding_record, False, id="record-past-the-bound"), + ], +) +def test_a_shared_copy_with_a_time_with_no_offset_or_a_record_past_the_bound_is_a_miss( + tmp_path: Path, + valkey_server: FakeServer, + shared_valkey: ValkeyCacheTier, + spoil: Callable[[FakeServer], None], + naive_record: bool, +) -> None: + """The shared copy is newer than the local one, but its `meta` or a record holds a time with + no UTC offset, or a record expands past 1 MiB. The load takes the local copy, and the next + save replaces the shared copy.""" + local = _snapshot(STARTED - timedelta(hours=1), 1) + FileSnapshotStore(tmp_path).save(local) + shared = _snapshot(STARTED, 2, 1) + if naive_record: + naive_time = STARTED.replace(tzinfo=None) - timedelta(hours=1) + naive = shared.issues[0].model_copy(update={"updated_at": naive_time}) + shared = shared.model_copy(update={"issues": (naive, *shared.issues[1:])}) + _valkey_store(shared_valkey).save(shared) + spoil(valkey_server) + + loaded = _tiered(tmp_path).load(REPO) + _tiered(tmp_path).save(_snapshot(STARTED + timedelta(hours=1), 3, 2, 1)) + + assert (loaded, _shared(valkey_server)) == (local, ("2026-01-01T11:00:00Z", ["3", "2", "1"])) + + +@pytest.mark.usefixtures("shared_valkey") +def test_a_repository_that_became_private_leaves_the_shared_tier( + github_api: GitHubApiFake, tmp_path: Path, valkey_server: FakeServer, otlp: FakeCollector +) -> None: + """A round of a public repository writes its shared copy. A round after the repository + became private removes the key, uses no shared copy and counts `removed`.""" + github_api.route("GET", FULL, github_json([_issue(2), _issue(1)])) + github_api.route("GET", _since("2026-01-01T08:59:00Z"), github_json([])) + _round(_tiered(tmp_path)) + public_round = _keys(valkey_server) + _new_process() + otlp.clear() + later = STARTED + timedelta(hours=1) + + _round(_tiered(tmp_path, at=later, is_public=lambda repo: False), at=later) + + assert (public_round, _keys(valkey_server), _reads(otlp), _writes(otlp)) == ( + [SNAPSHOT_KEY], + [], + {("snapshot", "private"): 1.0}, + {("snapshot", "removed"): 1.0, ("snapshot", "private"): 1.0}, + ) + + +@pytest.mark.usefixtures("shared_valkey") +def test_one_shared_key_and_one_visibility_read_hold_a_repository_in_each_spelling( + tmp_path: Path, valkey_server: FakeServer +) -> None: + """GitHub names ignore case: a save as `Dan-Petty/DevOps-CLI` and a load as + `dan-petty/devops-cli` use one key, and the visibility of the two is read once.""" + from devops_cli.roadmap.stores.listing_shared import repository_is_public + + spelled = "Dan-Petty/DevOps-CLI" + runner = RecordedGh({"isPrivate": {"data": {"repository": {"isPrivate": False}}}}) + _tiered(tmp_path / "a").save(_snapshot(STARTED, 2, 1).model_copy(update={"repo": spelled})) + _new_process() + + loaded = _tiered(tmp_path / "b").load(REPO) + answers = ( + repository_is_public(spelled, runner=runner), + repository_is_public(REPO, runner=runner), + ) + + assert ( + _keys(valkey_server), + None if loaded is None else [issue.number for issue in loaded.issues], + answers, + len(runner.calls), + ) == ([SNAPSHOT_KEY], [2, 1], (True, True), 1) + + +@pytest.mark.usefixtures("shared_valkey") +def test_a_load_counts_the_tier_that_gave_the_snapshot(tmp_path: Path, otlp: FakeCollector) -> None: + """With no copy in either tier the load counts `source`. With the same watermark in both + tiers, the local copy wins and the load counts `local`, not `source`.""" + snapshot = _snapshot(STARTED, 2, 1) + empty = _tiered(tmp_path).load(REPO) + _tiered(tmp_path).save(snapshot) + + loaded = _tiered(tmp_path).load(REPO) + + assert (empty, loaded, _reads(otlp)) == ( + None, + snapshot, + {("snapshot", "source"): 1.0, ("snapshot", "local"): 1.0}, + ) diff --git a/tests/support/fakes/valkey.py b/tests/support/fakes/valkey.py index 71e9825c31..509ceccd9c 100644 --- a/tests/support/fakes/valkey.py +++ b/tests/support/fakes/valkey.py @@ -12,7 +12,9 @@ holds a silent or slow server only as a connection that fails; a test of a timeout binds a loopback listener that never answers (`silent_valkey`), as the floor's `refusing_port` does for a refused port. `shared_valkey` installs a cache tier over the fake as the one tier of the process, -which the shared tier of the project brain reads (#4668). +which the shared tier of the project brain reads (#4668). A client of `valkey_client_on` with +`after_command` runs a test action after each command that it sends alone, so a test changes +the world between a WATCH and its EXEC, or between two `HSCAN` steps, with no double of its own. The pool is the fake's own, so a test of what the client's own password, the database of its endpoint and its decoding send and read binds a loopback listener that records the commands it receives. That @@ -26,12 +28,14 @@ import socket import ssl import threading -from collections.abc import Iterator, Mapping +from collections.abc import Callable, Iterator, Mapping from contextlib import contextmanager from typing import TYPE_CHECKING, Any import pytest from fakeredis import FakeServer, FakeValkey +from redis.exceptions import ConnectionError as RedisConnectionError +from valkey import exceptions as valkey_exceptions from devops_cli.valkey.client import ValkeyClient from tests.support.waits import POLL_INTERVAL_SECONDS, THREAD_HANDOFF_BOUND_SECONDS @@ -52,18 +56,60 @@ def valkey_endpoint(url: str) -> ValkeyEndpoint: return parse_valkey_url(url, setting="valkey.url") -def valkey_client_on(server: FakeServer, *, password: str | None = None) -> ValkeyClient: +AfterCommand = Callable[[tuple[Any, ...]], None] +"""A test action that runs after the server did one command that a client sent alone: it gets +the words of the command, such as `("HGET", key, field)`.""" + + +def valkey_client_on( + server: FakeServer, + *, + password: str | None = None, + after_command: AfterCommand | None = None, +) -> ValkeyClient: """A `ValkeyClient` connected to an in-memory server. The pool is the fake's own, so the client's password, the database of its endpoint and its decoding play no part. + + `after_command` runs after the server did each command that the client sends alone, and + before the client reads the reply: a plain command, and the WATCH and each read of a WATCH + transaction before its MULTI. It does not see the commands of a MULTI/EXEC block. A test uses + it to change the world at that point: another client writes the watched key before the EXEC, + `server.connected = False` stops the server before the next command, or the `clock` fixture + moves between two `HSCAN` steps. """ pool = FakeValkey( server=server, password=password, decode_responses=True, encoding_errors="replace" ).connection_pool + pool.connection_class = _fake_connection_class(pool.connection_class, after_command) return ValkeyClient(valkey_endpoint("valkey://127.0.0.1"), connection_pool=pool) +def _fake_connection_class(base: type[Any], after_command: AfterCommand | None) -> type[Any]: + """The connection class of the fake, with `after_command` after each command sent alone. + + The fake's server does a command while the client sends it, so the action sees its effect. + A connection that is open when `server.connected` turns False fails its next write with the + `ConnectionError` of redis-py from fakeredis's socket, where a real socket fails with an + `OSError` that valkey-py gives as its own `ConnectionError`. The class gives valkey-py's. + """ + + class _FakeConnection(base): # type: ignore[misc, valid-type] + def send_command(self, *args: Any, **kwargs: Any) -> None: + super().send_command(*args, **kwargs) + if after_command is not None: + after_command(args) + + def send_packed_command(self, command: Any, check_health: bool = True) -> None: + try: + super().send_packed_command(command, check_health) + except RedisConnectionError as exc: + raise valkey_exceptions.ConnectionError(str(exc)) from exc + + return _FakeConnection + + @pytest.fixture def valkey_server() -> FakeServer: """An empty in-memory Valkey server that needs no password.""" diff --git a/tests/valkey/test_valkey_cache_tier.py b/tests/valkey/test_valkey_cache_tier.py index 100d31786c..62c7f2f13e 100644 --- a/tests/valkey/test_valkey_cache_tier.py +++ b/tests/valkey/test_valkey_cache_tier.py @@ -352,6 +352,40 @@ def won(meta: bytes | None) -> list[tuple[str, ...]]: ) == (False, b"other", False, True, b"mine", [b"first", b"other"]) +@pytest.mark.parametrize( + "last_command", + [ + pytest.param("WATCH", id="the-watched-read-fails"), + pytest.param("HGET", id="the-exec-fails"), + ], +) +def test_a_valkey_that_goes_away_in_a_watch_transaction_opens_the_breaker( + valkey_server: FakeServer, otlp: FakeCollector, last_command: str +) -> None: + """valkey-py gives a `WatchError` for a connection that fails while the client watches a + key. The tier tells it from a lost race: it counts `error="connection"`, opens the breaker + and gives None, as for each other command that fails.""" + + def go_away(command: tuple[object, ...]) -> None: + if command[0] == last_command: + valkey_server.connected = False + + client = valkey_client_on(valkey_server, after_command=go_away) + tier = _tier(client) + try: + written = tier.watch_and_write( + "snapshot", "meta", lambda meta: [("HSET", "snapshot", "meta", "mine")] + ) + finally: + client.close() + + assert (written, tier.is_open, _errors(otlp)) == ( + None, + True, + {("watch", "connection"): 1.0}, + ) + + def test_a_failed_tier_command_counts_its_command_and_error( valkey_server: FakeServer, valkey_client: ValkeyClient, otlp: FakeCollector ) -> None: From 15dc17728d97a9410e60578f33d72facece20efe Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 02:43:52 +0000 Subject: [PATCH 17/20] fix(roadmap): write the shared snapshot only when it changes The meta of the shared snapshot holds a digest of its records in place of a token that each save made new. A save of the records that the shared copy holds sends only EXPIRE and counts unchanged; a save of known records sends only the changes. A load uses the records only when they have the digest of meta, so a new meta of the same records does not spoil a scan. The values of the shared tier are untrusted: a time with no UTC offset and a record that expands past 1 MiB make the copy a miss. The key and the visibility answers use RepoRef.key. A round removes the key of a repository that became private and counts removed. A load from the local file counts local. A lost connection in a WATCH transaction raises its connection error, so the breaker opens. The roadmap-intake-listing spec gets a MODIFIED delta for the full read and the reads of the Service through the shared tier. --- docs/TELEMETRY.md | 4 +- docs/roadmap/intake.md | 4 +- k8s/README.md | 2 +- .../design.md | 17 +- .../proposal.md | 6 +- .../specs/project-brain/shared-cache/spec.md | 50 ++++- .../specs/roadmap-intake-listing/spec.md | 39 ++++ .../tasks.md | 12 ++ src/devops_cli/config/constants.py | 16 +- src/devops_cli/config/defaults.py | 4 +- .../roadmap/stores/listing_shared.py | 199 +++++++++++++----- src/devops_cli/telemetry/instruments.py | 14 +- src/devops_cli/valkey/client.py | 42 +++- tests/valkey/test_valkey_cache_tier.py | 14 +- 14 files changed, 324 insertions(+), 99 deletions(-) create mode 100644 openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 24498d9744..658d146e01 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -175,8 +175,8 @@ writes by name. | `devops_cli_roadmap_stage_gate_problems` | Histogram | `1` | Findings of the stage checks in one reply of a plan, one observation for each reply that the checks judged, by repo and reply: 0 for the first reply of a plan run and 1 more for each return, so at most roadmap.stage.gate_returns plus roadmap.stage.gate_return_extensions plus 1 values (#4851, #5440). A reply that passes the checks observes 0. One repository adds at most 17 series, at the ceilings of the two settings. | | `devops_cli_roadmap_stage_gate_refusals_total` | Counter | `1` | Replies of the stage model that a gate found a problem in, one count for each gate that found at least one problem in a reply, by repo and gate. A reply that two gates refuse adds 1 to each. The gates run again on the reply that answers a problem, so the count is of refused replies and not of refused items. One repository adds 17 series, one for each gate. | | `devops_cli_embedding_cache_lookups_total` | Counter | `1` | Embedding cache lookups, one for each text that an embedding request gets, by result: hit or miss. A hit names its tier: memory for the cache of the process, valkey, or disk for the cache file that keeps the vectors of intake between runs. | -| `devops_cli_brain_reads_total` | Counter | `1` | Reads of the project brain (#4668), by store (snapshot or fact) and result: memory or shared for the tier that gave the value, source when no tier held it, fallback when the shared tier failed or its breaker was open, and private for a repository that the shared tier does not hold. | -| `devops_cli_brain_writes_total` | Counter | `1` | Writes of the project brain to the shared tier (#4668), by store and result: shared, skipped while the tier failed, oversize for a value over 1 MiB that stays in memory, older when the shared snapshot is newer or another writer won, and private. | +| `devops_cli_brain_reads_total` | Counter | `1` | Reads of the project brain (#4668), by store (snapshot or fact) and result: memory, local or shared for the tier that gave the value (local is the snapshot file of the process), source when no tier held it, fallback when the shared tier failed or its breaker was open, and private for a repository that the shared tier does not hold. | +| `devops_cli_brain_writes_total` | Counter | `1` | Writes of the project brain to the shared tier (#4668), by store and result: shared, unchanged when the shared snapshot already holds the same records, skipped while the tier failed, oversize for a value over 1 MiB that stays in memory, older when the shared snapshot is newer or another writer won, private, and removed for the shared snapshot of a repository that became private. | | `devops_cli_valkey_cache_errors_total` | Counter | `1` | Commands of the Valkey cache tier that failed or that its open breaker did not send (#4668), by command (op) and error: timeout, connection, auth, reply, open, or budget for a load of a shared snapshot that passed its time budget. | | `devops_cli_brain_github_requests_saved_total` | Counter | `1` | Listing pages of a full read that a process did not send because it took the shared snapshot (#4668), by store. | | `devops_cli_embedding_cache_size` | Gauge | `1` | Embeddings that the memory cache of the process held after its last embedding request. | diff --git a/docs/roadmap/intake.md b/docs/roadmap/intake.md index ff31695fab..3000732f16 100644 --- a/docs/roadmap/intake.md +++ b/docs/roadmap/intake.md @@ -115,10 +115,10 @@ Intake compares each candidate with every item and with every issue closed as no - A run reads only the issues and pull requests that changed since the watermark: `state=all`, `sort=updated`, `direction=desc` and `since=`. Each changed issue replaces its record, so intake parses only the bodies of the changed issues. When 100 or fewer issues changed, the read is one request. - The new watermark is the earlier of the start of the read and the newest `updated_at` that GitHub gave, less 60 seconds. Thus a local clock ahead of GitHub's clock skips no change. - GitHub does not move the `updated_at` of a parent when a sub-issue joins or leaves it. A changed issue that joined or left a parent moves the sub-issue count of that parent by one. -- A run reads the whole listing and writes a new snapshot when no snapshot is kept, when the snapshot cannot be read, when its schema key is not the current one, when its last full read is 24 hours old or older, and on `--full`. The full read removes an issue that left the repository. +- A run reads the whole listing and writes a new snapshot when neither its local file nor the shared tier (below) keeps a fit snapshot, and on `--full`. A snapshot is fit when it can be read, its schema key is the current one, and its last full read is younger than 24 hours. The full read removes an issue that left the repository. - The snapshot is a copy of GitHub, which stays the source of truth. A snapshot that intake cannot read or write gives a warning. A failed write keeps the earlier file, because intake writes a temporary file and renames it. -In the Service, the lane of `intake` runs its intake rounds and the scoped intake of each delivery one at a time, so one writer keeps the snapshot of each repository. Thus a scoped round with a kept snapshot sends one listing request when 100 or fewer issues changed. The poll still reconciles each change that moved an `updated_at` (ADR 0017), and the full read of each day removes an issue that left the repository. Each other lane reads every issue through a snapshot of its own, in `listing-` of the state directory, which only its worker writes (#4854, #5553). Each local file sits under a shared copy of each public repository in the cache Valkey `valkey-devops` (`TieredSnapshotStore` in `src/devops_cli/roadmap/stores/listing_shared.py`, #4668). A run takes the fit copy with the newer watermark, so a pod with no local snapshot reads only the changes since the shared watermark. A writer replaces the shared copy only when its watermark is not older. While Valkey is down, a run reads and writes its local file only. The shared tier holds no copy of a private repository until `valkey-devops` has role ACL users (#4704), and a failed read of the visibility counts as private. `devops_cli_brain_reads_total{store="snapshot"}` counts where each load came from, and `devops_cli_brain_github_requests_saved_total` counts the listing pages that a shared copy saved. +In the Service, the lane of `intake` runs its intake rounds and the scoped intake of each delivery one at a time, so one writer keeps the snapshot of each repository. Thus a scoped round with a kept snapshot sends one listing request when 100 or fewer issues changed. The poll still reconciles each change that moved an `updated_at` (ADR 0017), and the full read of each day removes an issue that left the repository. Each other lane reads every issue through a snapshot of its own, in `listing-` of the state directory, which only its worker writes (#4854, #5553). Each local file sits under a shared copy of each public repository in the cache Valkey `valkey-devops` (`TieredSnapshotStore` in `src/devops_cli/roadmap/stores/listing_shared.py`, #4668). A run takes the fit copy with the newer watermark, so a pod with no local snapshot reads only the changes since the shared watermark. A writer replaces the shared copy only when its watermark is not older. A save of the records that the shared copy already holds sends no record, so a round of a lane of a quiet repository sends only reads of `meta` and one TTL command to Valkey. While Valkey is down, a run reads and writes its local file only. The shared tier holds no copy of a private repository until `valkey-devops` has role ACL users (#4704): a failed read of the visibility counts as private, and a round removes the shared copy of a repository that became private, at most one hour after the change. `devops_cli_brain_reads_total{store="snapshot"}` counts where each load came from (`local`, `shared`, or `source` for a full read), and `devops_cli_brain_github_requests_saved_total` counts the listing pages that a shared copy saved. ## A failed write diff --git a/k8s/README.md b/k8s/README.md index 53f3cd7de0..cf4105c385 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -282,7 +282,7 @@ The cache Valkey's policy `valkey-perimeter` (`llm/valkey.yaml`) admits Open Web The cache Valkey keeps at most 1536 MiB of data (`--maxmemory`), three quarters of its 2048Mi limit. The rest of the limit holds fragmentation and Valkey's own overhead. At the bound, Valkey refuses writes and evicts no key (`--maxmemory-policy noeviction`). Open WebUI keeps its session pools and token revocations there, and an evicted revocation makes a signed-out token valid again. The run index (`llm/valkey-runs.yaml`) uses the same policy with a bound of 512 MiB. `ValkeyMemoryNearBound` warns when the cache Valkey keeps its data above 80% of the bound for 10 minutes. The rule selects each exported Valkey with the policy `noeviction`, and the run index has no exporter, so the rule does not watch it. -devops-cli's cache Valkey (`llm/valkey-devops.yaml`) holds the caches of the roadmap Service and the cluster jobs: the embeddings that `EmbeddingsEngine` writes, the threat-intelligence reads, the listing snapshots of the public repositories (`valkey:roadmap:v1:snapshot:/`, 7 days) and the PyPI and deps.dev facts of the alternatives check (`valkey:brain:v1:fact::`, 24 hours) (#4668). It holds no key of a private repository until it has role ACL users (#4704). Each round of the Service and each job is a new process with an empty memory cache, so without it intake embeds every item of the roadmap again on each round. The devops ConfigMap names it in `valkey.url`, and its password reaches the pods from `devops/devops-cli` as `DEVOPS_CLI_VALKEY_PASSWORD`, the variable of `valkey.password`. Its policy `valkey-devops-perimeter` admits namespace `devops` on TCP 6379 and the `monitoring` namespace on the exporter port 9121, and allows no egress. `llm-default-perimeter` leaves its pods out, and `devops-default-perimeter` lets namespace `devops` reach namespace `llm` on 6379 beside the gateway's 4000. It keeps at most 256 MiB of data, two thirds of its 384Mi limit, writes no RDB or AOF, and at the bound evicts the least recently used key (`--maxmemory-policy allkeys-lru`): an evicted key costs one more embedding request or listing read. While it is down, each process reads and writes its local tiers only and makes one connection attempt in each cooldown of 60 s. It can't share the cache Valkey, which must not evict Open WebUI's state. +devops-cli's cache Valkey (`llm/valkey-devops.yaml`) holds the caches of the roadmap Service and the cluster jobs: the embeddings that `EmbeddingsEngine` writes, the threat-intelligence reads, the listing snapshots of the public repositories (`valkey:roadmap:v1:snapshot:/`, 7 days) and the PyPI and deps.dev facts of the alternatives check (`valkey:brain:v1:fact::`, 24 hours) (#4668). It holds no key of a private repository until it has role ACL users (#4704): a round removes the snapshot of a repository that became private, at most one hour after the change. Each round of the Service and each job is a new process with an empty memory cache, so without it intake embeds every item of the roadmap again on each round. The devops ConfigMap names it in `valkey.url`, and its password reaches the pods from `devops/devops-cli` as `DEVOPS_CLI_VALKEY_PASSWORD`, the variable of `valkey.password`. Its policy `valkey-devops-perimeter` admits namespace `devops` on TCP 6379 and the `monitoring` namespace on the exporter port 9121, and allows no egress. `llm-default-perimeter` leaves its pods out, and `devops-default-perimeter` lets namespace `devops` reach namespace `llm` on 6379 beside the gateway's 4000. It keeps at most 256 MiB of data, two thirds of its 384Mi limit, writes no RDB or AOF, and at the bound evicts the least recently used key (`--maxmemory-policy allkeys-lru`): an evicted key costs one more embedding request or listing read. While it is down, each process reads and writes its local tiers only and makes one connection attempt in each cooldown of 60 s. It can't share the cache Valkey, which must not evict Open WebUI's state. Qdrant requires the key of `llm/qdrant-api-key` (see Cluster Secrets) on every REST and gRPC request. Only `/`, `/healthz`, `/readyz`, `/livez` and the files of its web UI need no key. The qdrant container reads `api-key` as `QDRANT__SERVICE__API_KEY` and `read-only-api-key` as `QDRANT__SERVICE__READ_ONLY_API_KEY` through `env` in `llm/values-qdrant.yaml`. Open WebUI names the Service in `QDRANT_URI` and sends the admin key as `QDRANT_API_KEY`; the devops ConfigMap names it in `qdrant.url`, and a pod that loads `devops/devops-cli` with `envFrom`, such as a Job of CronJob `devops-cli` or the MCP server, gets the read-only key as `DEVOPS_CLI_QDRANT_API_KEY` (#3823). The runner pod and the roadmap Service hold no Qdrant key (#6518). So a devops pod holds the search path and no write or delete path. Only WorkflowTemplate `rag-ingest` writes, with the admin key. `devops-default-perimeter` admits namespace `llm` on TCP 6333, and `llm-default-perimeter` admits namespace `devops` on 6333 and no other new peer. Alloy scrapes `/metrics` with the admin key as a bearer token. Helm drops a key of `llm/values-qdrant.yaml` that the chart does not declare with no error, so read the values of the chart (`helm show values qdrant/qdrant --version `) when you add a key or bump the chart. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md index 76eabbe501..213032e3a9 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md @@ -4,22 +4,24 @@ - **The memory bound of `valkey-devops` is `--maxmemory 256mb` inside a container limit of `384Mi`.**: The owner comment of 2026-11-19 on #4668 found four targets that do not agree (ADR 0023 line 134, #4624 item 6, the refined design of #4624, and the body of #4668). Only 256mb inside 384Mi keeps the owner decision 6 of #4624 (256 MB) and the rule of `openspec/specs/llm-valkey/spec.md` that `--maxmemory` is at most three quarters of the limit: 256 MiB is two thirds of 384Mi. The pull request comment on #4668 names this target and says that 240mb/320Mi and 256MB/320Mi in the bodies are replaced. The bodies of #4668 and #4624 stay as they are. - **ADR 0023 does not change.**: Its line 134 already says that the item raises the `maxmemory` of `valkey-devops` from 96 MB to 256 MB, which is the decided bound, and it names no limit. `docs/adr/README.md` forbids an edit of the body of an accepted record, and `tests/invariants/test_adr_records.py` fails on a changed body hash. A Status History line is only for a fact that a change makes wrong, and no fact of the record becomes wrong. The limit is a value of the manifest and of the spec of this change, as the length rule of the ADR README asks. -- **The memory bound has a validator command and a live check as its proof, and no test.**: `docs/TESTING.md` forbids a test that asserts a value of a manifest, and the `test-tree` row refuses one (`tests/gate/tree_checks/config_values.py`). The proof is `uv run devops ci --check --only k8s` before the merge, and after the Argo CD sync `kubectl -n llm get deployment valkey-devops -o jsonpath=...` (the `--maxmemory 256mb` argument and the `384Mi` limit) and `redis_config_maxmemory{job="valkey-devops"}` at 268,435,456. +- **The memory bound has a live check as its proof, and no test.**: `docs/TESTING.md` forbids a test that asserts a value of a manifest, and the `test-tree` row refuses one (`tests/gate/tree_checks/config_values.py`). `uv run devops ci --check --only k8s` before the merge proves only that `k8s/llm` renders: it does not compare `--maxmemory` with the limit, and `ValkeyMemoryNearBound` selects only the Valkeys with the policy `noeviction`. The proof of the bound is the live check after the Argo CD sync: `kubectl -n llm get deployment valkey-devops -o jsonpath=...` (the `--maxmemory 256mb` argument and the `384Mi` limit) and `redis_config_maxmemory{job="valkey-devops"}` at 268,435,456. A continuous check of the three-quarters rule for each Valkey (a Prometheus rule over the exporter and the container limit) is a change of the alerting of every Valkey, so the pull request comments it on #4992, which sizes the containers. - **`TieredMapping` is a `MutableMapping` over a `cachetools.TTLCache` and the `ValkeyCacheTier`.**: No library gives a mapping over an in-process LRU and a Valkey tier with a breaker, a schema check and a bound for each value. As a `MutableMapping`, it plugs into `cachetools.cached`, so `_read_pypi` and `_linked_packages` keep their bodies and get a decorator. `__iter__` and `__len__` cover the in-process tier only, because a scan of the shared tier for each call has no use. - **A read goes memory, then Valkey, then the source, and a hit fills the tiers above it.**: ADR 0023 section 2 sets this order for content-addressed data. A write goes to Valkey and then to memory. A failed Valkey write is a later miss, never an error of the caller. - **The mapping encodes each value through a pydantic `TypeAdapter` of its value type, and stores the schema key of that type in front of the value (`:`).**: The facts are small JSON texts, so the mapping does not compress them; the snapshot store compresses its records itself. The keys are text, so each `cachetools.cached` read gives a `key` function. A reader that finds another schema key, or a key of an older kind version, treats it as a miss, reads the source and writes the value under the current key. This is the rule of T6. The schema key is the first 16 hex characters of the sha256 of the JSON schema of the type, as `LISTING_SCHEMA_KEY` already does for the snapshot. - **A value over 1 MiB stays in the in-process tier.**: The mapping measures the encoded value before it sends it. Over the bound, it sends no command, keeps the value in memory and counts `devops_cli_brain_writes_total{result="oversize"}`. ADR 0023 section 2 says that a value over 1 MiB stays local. `cachetools.cached` ignores a `ValueError` on a write, so the mapping does not raise one. - **Each key has a TTL.**: Each write of the mapping sends `SET ... EX `, and each write of the snapshot store ends with `EXPIRE` in the same MULTI/EXEC. The facts get 24 hours (`DEFAULT_BRAIN_FACT_TTL_SECONDS`) and the snapshot 7 days (`DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS`). A temporary key of a full write gets 600 s, so a killed writer leaves no key without an end. -- **`ValkeySnapshotStore` is the Valkey implementation of the `SnapshotStore` protocol.**: The protocol of #4552 is the seam that `IncrementalListing` reads, so no caller changes. `FileSnapshotStore` keeps one JSON file and cannot hold a shared copy. The hash `valkey:roadmap:v1:snapshot:/` holds the field `meta` (`schema_key`, `full_at`, `watermark`, and a `token` that is new for each write, so two writes never give the same `meta`) and one zlib JSON `IssueRecord` for each issue number. One field for each record keeps each value under the bound: the snapshot of devops-cli is 14.13 MB with zlib, and its largest record is 23,700 B with zlib. +- **`ValkeySnapshotStore` is the Valkey implementation of the `SnapshotStore` protocol.**: The protocol of #4552 is the seam that `IncrementalListing` reads, so no caller changes. `FileSnapshotStore` keeps one JSON file and cannot hold a shared copy. The hash `valkey:roadmap:v1:snapshot:/`, with the casefolded name of `RepoRef.key` (ADR 0022), holds the field `meta` (`schema_key`, `full_at`, `watermark`, and `digest`, a blake2b digest of the digests of the JSON of the records by number, so two equal `meta` values name the same records) and one zlib JSON `IssueRecord` for each issue number. One field for each record keeps each value under the bound: the snapshot of devops-cli is 14.13 MB with zlib, and its largest record is 23,700 B with zlib. - **`TieredSnapshotStore` combines the local and the shared store.**: ADR 0023 section 2 says that a reader loads the local and the shared copy, drops a copy with another schema or a full read older than 24 hours, and takes the copy with the newer watermark. The rule needs both copies at one place, so it is a store of its own and not a change of `IncrementalListing`. A save writes the shared tier first and then the local file, the order of ADR 0023 section 2. - **The newest watermark wins.**: A writer WATCHes the snapshot key, reads `meta`, and writes in one MULTI/EXEC only when its watermark is not older than the stored one, or when the stored copy has another schema. An EXEC that another client made fail writes nothing, and the writer does not retry: the other writer is newer or equal. This is the safe stop of ADR 0023 section 4. -- **A save writes only the changed fields when it can, and a full write goes through a temporary key and RENAME.**: The store keeps a digest of each record that it loaded from or wrote to the shared tier in this process. When the stored `meta` is the `meta` that the store last saw, it sends `HSET` for the changed records, `HDEL` for the removed ones and the new `meta`. In every other case (a full read, no shared copy in this process, or a changed `meta`) it writes all records to `:next:` in pipelined batches and then, under the WATCH of the snapshot key, RENAMEs the temporary key onto it and sets its TTL. A full read so removes each issue that left the repository. -- **A load reads `meta` first, then the records with `HSCAN COUNT 500`, within a budget of 20 s.**: The budget (`DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`) is checked between two scans. Past it, the load is a miss: the reader takes the local copy or reads GitHub, and the store counts `devops_cli_valkey_cache_errors_total{op="hscan",error="budget"}`. Each command keeps the 2 s bound of `valkey.timeout`, which is shorter than the budget, as ADR 0023 section 2 asks. The values come back as bytes through `NEVER_DECODE`. -- **The shared tier holds data of public repositories only.**: ADR 0023 section 8 keeps a private repository in the local tier until `valkey-devops` has role ACL users (#4704). `TieredSnapshotStore` asks a visibility check before it uses the shared tier for a repository. The check reads `isPrivate` through the GraphQL query of `is_private_args`, once for each repository and process in each hour (`DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS`). A failed read counts as private and is not kept. The store reads the visibility only after the shared tier answered the read of `meta`, so a run with no reachable Valkey, such as a workstation, sends no visibility read. For a private repository the store drops what that read gave, reads no record, writes no key and counts `result="private"`. +- **A save of unchanged records writes none, a save of known records writes only the changes, and any other save goes through a temporary key and RENAME.**: The Service runs a lane for each job, about 24 for each repository, and each lane saves after each round with a full read of its own time. When the stored `meta` has the schema key and the digest of the snapshot and a watermark and a full read that are not older, the save sends only `EXPIRE` and counts `unchanged`. When the store knows the stored records (the stored digest is the digest of the snapshot, or of the copy that this process last wrote or read), it sends `HSET` for the changed records, `HDEL` for the removed ones and the new `meta` in one WATCH transaction on the stored `meta`. Under the WATCH, the stored records are the known ones, so the result is the same as a RENAME, and a full read so removes each issue that left the repository. In every other case it writes all records to `:next:` in batches and then, under the WATCH of the snapshot key, RENAMEs the temporary key onto it and sets its TTL. A rewrite of the 14 MB of devops-cli took 3.09 s on the temporary pod, so the lanes of a quiet repository must not send one on each round. +- **A load reads `meta` first, then the records with `HSCAN COUNT 500`, within a budget of 20 s.**: The budget (`DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`) is checked between two scans. Past it, the load is a miss: the reader takes the local copy or reads GitHub, and the store counts `devops_cli_valkey_cache_errors_total{op="hscan",error="budget"}`. Each command keeps the 2 s bound of `valkey.timeout`, which is shorter than the budget, as ADR 0023 section 2 asks. The values come back as bytes through `NEVER_DECODE`. The load uses the records only when their digest is the `digest` of the `meta` that it read first: a write of other records during the scan makes it a miss, and a new `meta` of the same records does not. +- **The values of the shared tier are untrusted.**: Each client with the password can write a key. `SharedMeta` declares its times as pydantic `AwareDatetime`, and each record goes through a model of its times with `AwareDatetime`, so a time with no UTC offset is a miss and never a `TypeError` in a compare. A record expands with `zlib.decompressobj` up to `DEFAULT_BRAIN_VALUE_MAX_BYTES` (1 MiB), and a record that does not end there is a miss, so one value cannot fill the memory of the reader. The writer keeps both the JSON and the zlib form of each record under the same bound, so a reader refuses no record that the store wrote. +- **The shared tier holds data of public repositories only.**: ADR 0023 section 8 keeps a private repository in the local tier until `valkey-devops` has role ACL users (#4704). `TieredSnapshotStore` asks a visibility check before it uses the shared tier for a repository. The check reads `isPrivate` through the GraphQL query of `is_private_args`, once for each repository and process in each hour (`DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS`). A failed read counts as private and is not kept. The store reads the visibility only after the shared tier answered the read of `meta`, so a run with no reachable Valkey, such as a workstation, sends no visibility read. For a private repository the store drops what that read gave, reads no record, writes no key and counts `result="private"`. When the read of `meta` found a key of a repository that is not public, the store sends `UNLINK` of the key and counts `devops_cli_brain_writes_total{result="removed"}`. A repository that becomes private can so keep its shared copy, and get writes to it, for at most the hour of the visibility answer of a process; a shorter answer would cost a GraphQL read for each repository and round. - **The fact cache reads public sources only.**: PyPI and deps.dev answer the same text to each client. The key is `valkey:brain:v1:fact:pypi:` with the name in the canonical form of `packaging.utils.canonicalize_name` (ADR 0023 section 6), and `valkey:brain:v1:fact:deps-dev:` with the deps.dev project key in lower case. An answer of "no such package" is a fact too, with the same TTL. A failed read raises as before and keeps nothing. - **The tier commands that this item needs go into `ValkeyClient` and `ValkeyCacheTier`.**: `hget`, `hset`, `hdel`, `hscan`, `expire`, `unlink`, `rename` and `watch_and_write`. The tier keeps one client, one pool and one breaker for each process, so the new stores share the cooldown of the embeddings and the threat-intel caches: while Valkey is down, the process makes one connection attempt in each cooldown. +- **A lost connection in a WATCH transaction is a failure, not a lost race.**: valkey-py gives a `WatchError` when the connection fails or times out while the pipeline watches a key, at the read after the WATCH and at the EXEC, with the failure as its context. `ValkeyClient.watch_and_write` raises that failure as its `ValkeyConnectionError` or `ValkeyTimeoutError`, so the breaker opens and the error counter names the cause. Only a `WatchError` with no such context is a lost race. - **The read of a binary value uses `NEVER_DECODE`.**: The pool of `ValkeyClient` decodes each reply as UTF-8 with `encoding_errors="replace"`, which spoils zlib bytes. valkey-py gives the per-command option `NEVER_DECODE`, and fakeredis 2.40.0 honours it. A write of bytes needs no option, because the encoder sends bytes as they are. -- **Four counters, each with bounded labels.**: `devops_cli_brain_reads_total{store,result}` with `store` in `snapshot`, `fact` and `result` in `memory`, `shared`, `source`, `fallback`, `private`. `devops_cli_brain_writes_total{store,result}` with `result` in `shared`, `skipped`, `oversize`, `older`, `private`. `devops_cli_valkey_cache_errors_total{op,error}` with `op` the command and `error` in `timeout`, `connection`, `auth`, `reply`, `open`, `budget`. `devops_cli_brain_github_requests_saved_total{store}` with `store` in `snapshot`: a load that takes the shared copy when the local copy is missing or unfit adds the page count of the full read that it saves (the record count over `DEFAULT_GH_REST_PER_PAGE`, rounded up). The body names three counters. The fourth counts the skipped writes that the body asks to count ("each write is skipped and counted"). +- **Four counters, each with bounded labels.**: `devops_cli_brain_reads_total{store,result}` with `store` in `snapshot`, `fact` and `result` in `memory`, `local`, `shared`, `source`, `fallback`, `private`: `local` is a load that gives the fit local snapshot file, and `source` is kept for a load with no fit copy in any tier, which reads the whole listing. `devops_cli_brain_writes_total{store,result}` with `result` in `shared`, `unchanged`, `skipped`, `oversize`, `older`, `private`, `removed`. `devops_cli_valkey_cache_errors_total{op,error}` with `op` the command and `error` in `timeout`, `connection`, `auth`, `reply`, `open`, `budget`. `devops_cli_brain_github_requests_saved_total{store}` with `store` in `snapshot`: a load that takes the shared copy when the local copy is missing or unfit adds the page count of the full read that it saves (the record count over `DEFAULT_GH_REST_PER_PAGE`, rounded up). The body names three counters. The fourth counts the skipped writes that the body asks to count ("each write is skipped and counted"). - **The error counter has no label `instance`.**: The collector sets the labels `job` and `instance` from the resource after it copies the attributes, so an attribute `instance` never reaches Prometheus, and `test_no_emit_sends_an_attribute_that_the_resource_sets` (`tests/telemetry/test_telemetry_instruments.py:480`, #3240) refuses an `emit` that sends one. Each process has one cache tier, so the label would hold one value. - **The load time of the shared snapshot is measured against a temporary Valkey pod.**: The build starts a hardened pod of `valkey/valkey:9.1.4-alpine` (the image tag of the live `valkey-devops`) in namespace `llm`, with `activeDeadlineSeconds`, forwards a loopback port to it, writes the 6,571 records of the local devops-cli snapshot through `ValkeySnapshotStore`, and times a cold load. Then it deletes the pod and stops the port-forward. It never reads or writes the live `valkey-devops`. The same pod records the new contract scenarios. - **The live drill waits for the release.**: The drill (`valkey-devops` at 0 replicas for 10 minutes; no job fails; the share of `result="fallback"` shows in Prometheus) needs the merged code in the cluster. The pull request body names it as the live check after the release, and `tasks.md` names it as a check for a person. @@ -46,6 +48,9 @@ - **Caches of GitHub answers (the SBOM of the inventory, the ADR index, the repository facts) on the mapping.**: ADR 0023 section 2 keeps the stored GitHub answers in the process until the two-token probe of ADR 0021 section 6 passes. The conditional item of #4624 holds them. - **A per-process LRU only for the facts.**: Each release restarts the Service, and each Job is a new process, so an LRU alone is cold at each start. - **The label `instance` on `devops_cli_valkey_cache_errors_total`.**: The collector replaces it with the label of the resource, and the test of #3240 refuses it, as the decision above says. +- **A token that is new for each write in `meta`.**: Each save then changed `meta`, so another process never knew the stored records and wrote all 14 MB again, and each change spoiled a load that was scanning. The digest of the records names the same thing for each writer. +- **A full write after each full read.**: Under the WATCH of `meta`, a write of the changed and removed records gives the same records as a RENAME, at the cost of the changes only. +- **A Prometheus rule for the three-quarters rule of each Valkey in this item.**: It changes the alerting of every Valkey, not the shared tier, so the pull request comments it on #4992. ## Unchanged references diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md index e0755ae5d9..9d300686fc 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md @@ -12,14 +12,14 @@ - `src/devops_cli/valkey/client.py`: `ValkeyClient` gets the hash commands `hget`, `hset`, `hdel` and `hscan`, and `expire`, `unlink` and `rename`. A read of a binary value uses the `NEVER_DECODE` option of valkey-py, so a zlib value comes back as bytes. A new method `watch_and_write` runs one WATCH, a check of the current value, and one MULTI/EXEC, and it says when another client changed the key first. It does not retry. - `src/devops_cli/valkey/cache.py`: `ValkeyCacheTier` gets the same commands behind its circuit breaker. A command that fails, or that the open breaker does not send, is a miss or a skipped write, and the tier counts it in `devops_cli_valkey_cache_errors_total`. - `src/devops_cli/valkey/tiered.py` (new): `TieredMapping`, a `MutableMapping` over an in-process `cachetools.TTLCache` and the shared `ValkeyCacheTier`. It has a key prefix, a JSON value with the schema key of its pydantic `TypeAdapter` in front, a TTL for each key, a bound of 1 MiB for each value, and the read and write counters. A read from the shared tier fills the in-process tier. A value of another schema is a miss. -- `src/devops_cli/roadmap/stores/listing_shared.py` (new): `ValkeySnapshotStore` and `TieredSnapshotStore` behind the `SnapshotStore` protocol. The snapshot of a repository is one hash, `valkey:roadmap:v1:snapshot:/`, with the field `meta` and one zlib JSON `IssueRecord` for each issue, and a TTL of 7 days. A load reads the hash with `HSCAN COUNT 500` within a budget of 20 s. A writer writes only when its watermark is not older than the stored one, in one WATCH and MULTI/EXEC. A full read writes a temporary key and RENAMEs it. The store uses the shared copy and writes a key only for a public repository. +- `src/devops_cli/roadmap/stores/listing_shared.py` (new): `ValkeySnapshotStore` and `TieredSnapshotStore` behind the `SnapshotStore` protocol. The snapshot of a repository is one hash, `valkey:roadmap:v1:snapshot:/` with the casefolded name of `RepoRef`, with the field `meta` (with a digest of the records) and one zlib JSON `IssueRecord` for each issue, and a TTL of 7 days. A load reads the hash with `HSCAN COUNT 500` within a budget of 20 s, and uses the records only when they have the digest of `meta`. A writer writes only when its watermark is not older than the stored one, in one WATCH and MULTI/EXEC. A save of the records that the shared copy holds writes none; a save of known records writes only the changes; any other save writes a temporary key and RENAMEs it. The store uses the shared copy and writes a key only for a public repository, and removes the key of a repository that became private. - `src/devops_cli/roadmap/stores/listing_snapshot.py`: `intake_listing` and `lane_listing` give `IncrementalListing` a `TieredSnapshotStore` over the `FileSnapshotStore` of today and the shared tier of the process. The callers of the two factories do not change. - `src/devops_cli/roadmap/alternatives.py` and `src/devops_cli/roadmap/inventory.py`: the PyPI and deps.dev reads go through one fact `TieredMapping`, `valkey:brain:v1:fact::`, with a TTL of 24 hours. A miss reads the source. - `src/devops_cli/telemetry/instruments.py`: four counters with bounded labels: `devops_cli_brain_reads_total{store,result}`, `devops_cli_brain_writes_total{store,result}`, `devops_cli_valkey_cache_errors_total{op,error}` and `devops_cli_brain_github_requests_saved_total{store}`. - `src/devops_cli/config/defaults.py` and `src/devops_cli/config/constants.py`: the TTLs, the load budget, the value bound, the HSCAN count, the size of the in-process tier, the key prefixes and the label values. - `k8s/llm/valkey-devops.yaml`: `--maxmemory 256mb` in place of `96mb`, and a container limit of `384Mi` in place of `128Mi`. 256 MiB is two thirds of 384Mi, so the rule of `openspec/specs/llm-valkey/spec.md` (at most three quarters of the limit) holds, and so does the owner decision 6 of #4624 (256 MB). - The contract suite of #4557 gets scenarios for WATCH with a lost transaction, `HSCAN` of binary values, `RENAME` of a hash with a TTL, `EXPIRE` and `UNLINK`, recorded from a real `valkey-server` of the image of `valkey-devops`. -- Documents: `k8s/README.md` (the memory bound and the new keys of `valkey-devops`), `docs/roadmap/intake.md` (the shared copy of the snapshot), `docs/roadmap/alternatives.md` (the fact cache) and the generated `docs/TELEMETRY.md`. +- Documents: `k8s/README.md` (the memory bound and the new keys of `valkey-devops`), `docs/roadmap/intake.md` (the shared copy of the snapshot and the conditions of the full read), `docs/roadmap/alternatives.md` (the fact cache) and the generated `docs/TELEMETRY.md`. - The change adds service behavior that a consumer observes (the keys, the counters, the fallback and the memory bound), so it has a spec delta: the new nested capability `project-brain/shared-cache`, as ADR 0023 requires for each item of #4624. - The change fits one pull request. @@ -37,7 +37,7 @@ Out of scope, with the reason: ### Modified Capabilities -None. +- `roadmap-intake-listing`: a run reads the whole listing only when neither the local file nor the shared tier keeps a fit snapshot ("Full read"), and the snapshot files of the Service sit under the shared tier, where a read starts from the fit copy with the newer watermark ("The Service reads through the snapshot"). ## Impact diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md index ff9e3c1dd7..3254052287 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md @@ -14,6 +14,13 @@ When a process has no local snapshot of a public repository and the shared tier - **WHEN** the local file holds a snapshot with the watermark 09:00 and the shared tier holds one with the watermark 10:00, both with the current schema key and a full read of less than 24 hours - **THEN** the listing read sends `since=` with the watermark 10:00 +### Requirement: A load counts the tier that gave the snapshot +A load of the tiered snapshot store SHALL count `devops_cli_brain_reads_total{store="snapshot"}` with `result="local"` when it gives the fit local copy, `result="shared"` when it gives the shared copy, and `result="source"` only when no tier holds a fit copy, so the run reads the whole listing. + +#### Scenario: Local and source loads +- **WHEN** a load runs with no copy in either tier, and a second load runs after a save that put the same snapshot in both tiers +- **THEN** the first load counts `source`, and the second load returns the local copy and counts `local` + ### Requirement: A read of the shared tier fills the in-process tier A `TieredMapping` read that misses the in-process tier and hits the shared tier SHALL put the value in the in-process tier, and the next read of the key SHALL send no command to Valkey. @@ -32,6 +39,10 @@ While the shared tier fails or its breaker is open, a read SHALL return the valu - **WHEN** the shared tier is a loopback listener that accepts the connection and answers no command, and `valkey.timeout` is 0.05 s - **THEN** the tier's client has a connect timeout of at most 0.25 s, the first read ends with `devops_cli_valkey_cache_errors_total{error="timeout"}` and returns the source value, the breaker opens, and the next read sends nothing to the listener +#### Scenario: A lost connection in a WATCH transaction +- **WHEN** the `valkey_server` fake stops after the WATCH, or after the read of the watched field and before the EXEC +- **THEN** the WATCH transaction gives no result, `devops_cli_valkey_cache_errors_total{op="watch",error="connection"}` rises by one, and the breaker opens, as for each other failed command, and not as for a lost race + ### Requirement: A trial after the cooldown and the newest watermark After the cooldown the first command SHALL be a trial that closes the breaker when it succeeds. A writer of the shared snapshot SHALL write only when its watermark is not older than the stored watermark or the stored copy has another schema key, and a writer whose WATCH transaction another client made fail SHALL write nothing and SHALL NOT retry. @@ -43,13 +54,31 @@ After the cooldown the first command SHALL be a trial that closes the breaker wh - **WHEN** the shared snapshot has watermark 10:00 and a writer saves a snapshot with watermark 09:00 and the same schema key - **THEN** the shared snapshot keeps watermark 10:00 and its records, and the local file holds the snapshot with watermark 09:00 -### Requirement: A full read replaces the shared snapshot whole -A save of a snapshot whose last full read is newer than the stored one SHALL write the records to a temporary key with a TTL and RENAME it onto the snapshot key in one transaction, so the shared snapshot holds no issue that the full read did not list. +### Requirement: A save leaves the shared snapshot with its records only +A save that may replace the shared snapshot SHALL leave it with the records of the saved snapshot only, so it holds no issue that a full read did not list. A save that knows the stored records SHALL send only the changed and removed records and the new `meta` in one WATCH transaction. Any other save SHALL write the records to a temporary key with a TTL and RENAME it onto the snapshot key in one transaction. #### Scenario: An issue left the repository - **WHEN** the shared snapshot holds issues 1, 2 and 3, and a full read lists issues 1 and 3 - **THEN** the shared snapshot holds issues 1 and 3 only, and no temporary key stays +### Requirement: A save of the records that the shared copy holds writes no record +A save whose records, schema key and watermark the shared snapshot already holds, with a full read that is not newer than the stored one, SHALL send no record and no transaction: it SHALL set the TTL of the key again, keep the stored `meta`, and count `devops_cli_brain_writes_total{result="unchanged"}`. + +#### Scenario: Two lanes and a new process with the same records +- **WHEN** two lanes of one process save the same 1,200 records and watermark with full reads at 08:00 and 09:00, and then each saves them again twice, and a new process saves them once +- **THEN** after the first save of each lane, the lanes send only `HGET` and `EXPIRE` commands, the stored `meta` does not change, `devops_cli_brain_writes_total{result="unchanged"}` rises by five, and no temporary key stays + +### Requirement: A load uses only the records that its meta names +A load SHALL use the records of the shared snapshot only when their digest is the digest of the `meta` that the load read first. A new `meta` of the same records during the scan SHALL NOT make the load a miss. A value of the shared tier is untrusted: a `meta` or a record with a time with no UTC offset, and a record that expands past 1 MiB, SHALL make the shared copy a miss, and the next save SHALL replace it. + +#### Scenario: A new meta of the same records during a load +- **WHEN** a writer saves the same 1,200 records with a newer full read after the first `HSCAN` of a cold load +- **THEN** the load gives the 1,200 records of the shared copy and counts `result="shared"` + +#### Scenario: A time with no offset or a record past the bound +- **WHEN** the shared snapshot is newer than the local one, and its `meta` holds a time with no UTC offset, or a record holds one, or a record expands to more than 1 MiB of JSON +- **THEN** the load gives the local snapshot and raises no error, and the next save leaves the shared snapshot with its own watermark and records + ### Requirement: Each value has a bound and each key a TTL The shared tier SHALL NOT receive a value whose encoded form is over 1 MiB; such a value SHALL stay in the in-process tier and count `devops_cli_brain_writes_total{result="oversize"}`. Each key that the mapping or the snapshot store writes SHALL have a TTL: 24 hours for a fact and 7 days for a snapshot. @@ -65,7 +94,7 @@ A reader SHALL treat a shared value under an older key version, or with another - **THEN** each read returns the value of the source, and the shared tier then holds the source value under the current key with the current schema key ### Requirement: No key of a private repository -The snapshot store SHALL write no key of a repository that the visibility check does not give as public, SHALL NOT use a shared copy of it, and SHALL count `result="private"`. A failed visibility read SHALL count as private. +The snapshot store SHALL write no key of a repository that the visibility check does not give as public, SHALL NOT use a shared copy of it, and SHALL count `result="private"`. A failed visibility read SHALL count as private. When the shared tier holds a copy of a repository that the check does not give as public, the store SHALL remove the key and count `devops_cli_brain_writes_total{result="removed"}`. #### Scenario: Private repository - **WHEN** a listing round runs for a repository whose visibility read gives `isPrivate: true`, and a second round runs for a repository whose visibility read fails @@ -75,6 +104,17 @@ The snapshot store SHALL write no key of a repository that the visibility check - **WHEN** the `valkey_server` fake has `connected = False` and a listing round runs - **THEN** the round sends no visibility read to GitHub +#### Scenario: A repository that became private +- **WHEN** a round of a public repository writes its shared snapshot, and a round in a new process finds that the repository is not public +- **THEN** the `valkey_server` fake holds no key, the round uses no shared copy, and `devops_cli_brain_writes_total{result="removed"}` rises by one + +### Requirement: One key for each repository +The key of a shared snapshot and the visibility answer of a process SHALL use the casefolded name of `RepoRef.key`, so each spelling of a repository name gives one key and one visibility read. + +#### Scenario: Two spellings of one name +- **WHEN** a process saves the snapshot of `Dan-Petty/DevOps-CLI`, a new process loads `dan-petty/devops-cli`, and the visibility of both spellings is read +- **THEN** the fake holds one key, the load gives the saved records, and GitHub gets one visibility read + ### Requirement: A shared load has a budget A load of a shared snapshot SHALL stop when it passes `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS` (20 s), SHALL count `devops_cli_valkey_cache_errors_total{op="hscan",error="budget"}`, and the reader SHALL take the local copy or read GitHub. @@ -105,9 +145,9 @@ The counters `devops_cli_brain_reads_total`, `devops_cli_brain_writes_total`, `d - **THEN** each exported data point of the four counters has only the labels `store`, `result`, `op` or `error`, each value is one of the fixed values, and no value names the repository or the package ### Requirement: The cache Valkey keeps its data bound below its limit -The valkey container of the Deployment `valkey-devops` SHALL start valkey-server with `--maxmemory 256mb` under a container memory limit of `384Mi`, so its data bound is two thirds of its limit. +The valkey container of the Deployment `valkey-devops` SHALL start valkey-server with `--maxmemory 256mb` under a container memory limit of `384Mi`, so its data bound is two thirds of its limit. The live check after the Argo CD sync is the proof of the bound. The `k8s` row of `devops ci` proves only that the manifests render: it does not compare `--maxmemory` with the limit. -#### Scenario: Manifest bound +#### Scenario: The manifests render - **WHEN** a person runs `uv run devops ci --check --only k8s` on the pull request - **THEN** the `k8s` row renders `k8s/llm` with no error diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md new file mode 100644 index 0000000000..07c27d7e3e --- /dev/null +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md @@ -0,0 +1,39 @@ +## MODIFIED Requirements + +### Requirement: Full read +Intake SHALL read the whole listing and replace the snapshot when neither the local file nor the shared tier of `valkey-devops` keeps a fit snapshot of the repository, and on `--full`. A snapshot is fit when it can be read, its schema key is the key of the current `IssueRecord` schema, and its last full read is younger than 24 hours. The shared tier keeps no snapshot of a private repository. A local snapshot file that cannot be read SHALL give a warning that names its file. + +#### Scenario: First run +- **WHEN** No snapshot is kept for the repository in the local file or in the shared tier +- **THEN** The request holds no `since` parameter, and the run keeps a snapshot with every issue of the listing + +#### Scenario: The flag, another version or an old full read +- **WHEN** A snapshot is kept and the run has `--full`, or each kept snapshot holds the schema key of another version of `IssueRecord`, or the last full read of each kept snapshot is 25 hours old +- **THEN** The request holds no `since` parameter, and the new snapshot replaces the old one + +#### Scenario: A snapshot that cannot be read +- **WHEN** The snapshot file holds no valid JSON, and the shared tier keeps no fit snapshot of the repository +- **THEN** The run logs a warning that names the file, reads the whole listing and keeps a new snapshot + +#### Scenario: A fit shared snapshot and no local file +- **WHEN** No local snapshot is kept, and the shared tier keeps a fit snapshot of the public repository +- **THEN** The run sends the listing requests with `since=` of the shared snapshot, and keeps a local snapshot with every issue + +### Requirement: The Service reads through the snapshot +The rounds of the lane that holds `intake` and the scoped intake of each delivery SHALL read every issue through the snapshot that the Service keeps in `listing` of its state directory. Each other lane SHALL read every issue through its own snapshot in `listing-` of the state directory. Each of these snapshot files SHALL sit under the shared tier of `valkey-devops`, and a read SHALL start from the fit copy with the newer watermark of the two. + +#### Scenario: A scoped intake with a kept snapshot +- **WHEN** The Service keeps a snapshot of 250 items, and a delivery says that issue 251 opened +- **THEN** The scoped intake sends one listing request, with `since=`, and places issue 251 + +#### Scenario: The store of each lane +- **WHEN** The lanes `metrics`, `intake` and `refine` each open their store for a poll +- **THEN** The store of `metrics` reads through the snapshot in `listing-metrics`, the store of `intake` through the snapshot in `listing`, and the store of `refine` through the snapshot in `listing-refine`, each under the shared tier + +#### Scenario: A status round with a kept snapshot +- **WHEN** The lane `stage_ready` ran one round, and a second round is due +- **THEN** The second round sends one listing request, with `since=` + +#### Scenario: The newer copy of the two tiers +- **WHEN** The snapshot file of a lane has the watermark 09:00, and the shared tier keeps a fit snapshot of the public repository with the watermark 10:00 +- **THEN** The round sends the listing request with `since=` the watermark 10:00 diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index 17abc79ecc..d2fa73fbac 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -71,6 +71,18 @@ Kind: other. Reads: `k8s/README.md`, `docs/roadmap/intake.md`, `docs/roadmap/alt - [x] 8.2 Regenerate `docs/TELEMETRY.md` with `uv run devops docs generate` for the four new counters. Change no text of the page by hand - Verification: `$ uv run devops ci docs` passes +## 9. Fix the findings of the review + +Kind: behavior. Reads: `src/devops_cli/roadmap/stores/listing_shared.py`, `src/devops_cli/valkey/client.py`, `src/devops_cli/github/repo_ref.py`, `openspec/specs/roadmap-intake-listing/spec.md`, `docs/TESTING.md`. Changes: `src/devops_cli/roadmap/stores/listing_shared.py`, `src/devops_cli/valkey/client.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/telemetry/instruments.py`, `tests/roadmap/stores/test_listing_shared.py`, `tests/valkey/test_valkey_cache_tier.py`, `tests/support/fakes/valkey.py`, `docs/roadmap/intake.md`, `docs/TELEMETRY.md`, `k8s/README.md`, `openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md`. + +- [x] 9.1 Give `valkey_client_on` of `tests/support/fakes/valkey.py` an `after_command` action, which runs after each command that a client sends alone, and make its connection give valkey-py's `ConnectionError` for a write to a stopped server. Replace the test subclasses of `ValkeyCacheTier` in `tests/roadmap/stores/test_listing_shared.py` with it. Write `test_a_save_of_the_records_that_the_shared_copy_holds_writes_no_record`, `test_a_new_meta_of_the_same_records_during_a_load_keeps_the_shared_copy`, `test_a_shared_copy_with_a_time_with_no_offset_or_a_record_past_the_bound_is_a_miss`, `test_a_repository_that_became_private_leaves_the_shared_tier`, `test_one_shared_key_and_one_visibility_read_hold_a_repository_in_each_spelling` and `test_a_load_counts_the_tier_that_gave_the_snapshot` in `tests/roadmap/stores/test_listing_shared.py`, and `test_a_valkey_that_goes_away_in_a_watch_transaction_opens_the_breaker` in `tests/valkey/test_valkey_cache_tier.py`. Make `test_a_silent_valkey_times_out_and_opens_the_breaker` wait for the accept thread with `THREAD_HANDOFF_BOUND_SECONDS` + - Verification: `$ uv run devops ci test tests/roadmap/stores/test_listing_shared.py tests/valkey/test_valkey_cache_tier.py` fails on the commit before 9.2 +- [x] 9.2 Put a `digest` of the records in `SharedMeta` in place of the `token`, and declare its times `AwareDatetime`. A save of the records that the stored copy holds with no newer full read or watermark sends only `EXPIRE` and counts `unchanged`; a save of known records sends the changes in one WATCH transaction; a load uses the records only when they have the digest of `meta`, refuses a record time with no UTC offset, and expands a record with `zlib.decompressobj` up to `DEFAULT_BRAIN_VALUE_MAX_BYTES`. The key and the visibility answers use `RepoRef.key`. A load or a save that finds the key of a repository that is not public removes it and counts `removed`; a load from the fit local file counts `local`. `ValkeyClient.watch_and_write` raises the connection failure or the timeout that a `WatchError` holds as its context. Add `BrainRead.LOCAL`, `BrainWrite.UNCHANGED` and `BrainWrite.REMOVED` + - Verification: `$ uv run devops ci test tests/roadmap/stores/test_listing_shared.py tests/valkey/test_valkey_cache_tier.py tests/valkey/test_tiered.py tests/valkey/test_valkey_contract.py` passes +- [x] 9.3 Add the MODIFIED delta of `roadmap-intake-listing` ("Full read" and "The Service reads through the snapshot"), change the full-read bullet of `docs/roadmap/intake.md`, name the removal of the snapshot of a repository that became private in `k8s/README.md`, say in the memory-bound requirement that the `k8s` row proves only the render, and regenerate `docs/TELEMETRY.md` + - Verification: `$ uv run devops openspec check` passes + - Verification: `$ uv run devops ci docs` passes + ## Criteria - Group 4: A test: a cold process with a warm shared snapshot reads at most 2 listing pages. diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index b215ffa2f7..add5a280aa 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -2906,11 +2906,13 @@ class BrainStore(StrEnum): class BrainRead(StrEnum): - """The `result` label of `devops_cli_brain_reads_total` (#4668): the tier that gave the value, - the source when no tier held it, the fallback when the shared tier failed or its breaker was - open, and a private repository, which the shared tier does not hold.""" + """The `result` label of `devops_cli_brain_reads_total` (#4668): the tier that gave the value + (`memory`, `local` for the local snapshot file, `shared`), the source when no tier held it, + the fallback when the shared tier failed or its breaker was open, and a private repository, + which the shared tier does not hold.""" MEMORY = "memory" + LOCAL = "local" SHARED = "shared" SOURCE = "source" FALLBACK = "fallback" @@ -2919,14 +2921,18 @@ class BrainRead(StrEnum): class BrainWrite(StrEnum): """The `result` label of `devops_cli_brain_writes_total` (#4668): written to the shared tier, - skipped while it failed, kept local because the value is over its bound, refused because the - shared copy is newer, or kept local for a private repository.""" + not written because the shared copy already holds the same records, skipped while the tier + failed, kept local because the value is over its bound, refused because the shared copy is + newer, kept local for a private repository, or the shared copy of a repository that became + private removed.""" SHARED = "shared" + UNCHANGED = "unchanged" SKIPPED = "skipped" OVERSIZE = "oversize" OLDER = "older" PRIVATE = "private" + REMOVED = "removed" class ValkeyCacheError(StrEnum): diff --git a/src/devops_cli/config/defaults.py b/src/devops_cli/config/defaults.py index 55e62feee6..126bd05084 100644 --- a/src/devops_cli/config/defaults.py +++ b/src/devops_cli/config/defaults.py @@ -734,7 +734,9 @@ # of the homelab took at most 0.4 ms, so the bound is more than 400 times the slowest connect. DEFAULT_VALKEY_CACHE_CONNECT_TIMEOUT_SECONDS: float = 0.25 # The project brain in the cache Valkey (#4668, ADR 0023 section 2). A value whose encoded form is -# over this bound stays in the in-process tier: ADR 0023 section 2 sets 1 MiB. +# over this bound stays in the in-process tier: ADR 0023 section 2 sets 1 MiB. A record of a +# shared snapshot keeps both its JSON and its zlib form under it, so a reader expands no value +# past it. DEFAULT_BRAIN_VALUE_MAX_BYTES: int = 1_048_576 # The entries of the in-process tier of one tiered mapping. A PyPI fact holds about 1 KB, so a # full tier holds about 1 MB. diff --git a/src/devops_cli/roadmap/stores/listing_shared.py b/src/devops_cli/roadmap/stores/listing_shared.py index be8e8a34ba..964f396574 100644 --- a/src/devops_cli/roadmap/stores/listing_shared.py +++ b/src/devops_cli/roadmap/stores/listing_shared.py @@ -7,23 +7,28 @@ again in full. `ValkeySnapshotStore` keeps the snapshot of a repository in one hash, -`valkey:roadmap:v1:snapshot:/`, with the field `meta` (the schema key, the time of -the last full read, the watermark, and a token of each write) and one zlib JSON `IssueRecord` -for each issue number. One field for each record keeps each value far under the bound of 1 MiB; -the whole snapshot of devops-cli is about 14 MB. The key lives -`DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS` after its last write. +`valkey:roadmap:v1:snapshot:/` with the casefolded name of `RepoRef.key`, with the +field `meta` (the schema key, the time of the last full read, the watermark, and a digest of the +records) and one zlib JSON `IssueRecord` for each issue number. One field for each record keeps +each value far under the bound of 1 MiB; the whole snapshot of devops-cli is about 14 MB. The key +lives `DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS` after its last save. - A load reads `meta`, then the records with `HSCAN`, and stops when it passes - `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`. It reads `meta` again at the end, so a copy that - another writer changed during the scan is not used. + `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`. It uses the records only when their digest is the + one of `meta`, so a copy that another writer changed during the scan is not used, and a new + `meta` of the same records does not spoil the scan. A value that does not parse, a time with + no UTC offset and a record that expands past `DEFAULT_BRAIN_VALUE_MAX_BYTES` make the copy a + miss: the values are untrusted. - A write is made only when its watermark is not older than the stored one, or when the stored copy has another schema key (ADR 0023 section 4). The check and the write are one WATCH and MULTI/EXEC; a writer whose EXEC fails writes nothing and does not try again, because the other writer is as new or newer. -- When the stored `meta` is the one that this process last wrote or read, a write sends only the - changed and removed records. Else, and after each full read, it writes all records to a - temporary key with a TTL and RENAMEs it onto the snapshot key, so an issue that left the - repository leaves the shared copy. +- A save of the records that the stored copy already holds, with no newer full read or + watermark, writes no record: it sets the TTL again and counts `unchanged`. When the store knows + the stored records (they have the digest of the snapshot, or of the copy that this process + last wrote or read), a write sends only the changed and removed records and the new `meta`. + Else it writes all records to a temporary key with a TTL and RENAMEs it onto the snapshot key. + Either way an issue that left the repository leaves the shared copy. `TieredSnapshotStore` is the `SnapshotStore` that intake and the lanes read through. It loads the local and the shared copy, drops a copy with another schema key or a full read older than @@ -31,7 +36,8 @@ saves the shared copy first and then the local file. While Valkey fails, it reads and writes the local file only. Until `valkey-devops` has role ACL users (#4704), the shared tier holds no data of a private repository (ADR 0023 section 8): the store reads the visibility of a repository only -after Valkey answered, and a failed visibility read counts as private. +after Valkey answered, a failed visibility read counts as private, and the store removes the +shared copy of a repository that became private. """ from __future__ import annotations @@ -48,7 +54,7 @@ from itertools import batched from typing import Any, Final -from pydantic import BaseModel, ConfigDict, ValidationError +from pydantic import AwareDatetime, BaseModel, ConfigDict, ValidationError from devops_cli.config.constants import ( CONST_VALKEY_ROADMAP_PREFIX, @@ -69,6 +75,7 @@ ) from devops_cli.core import clock from devops_cli.exceptions import DevOpsCLIError +from devops_cli.github.repo_ref import RepoRef from devops_cli.roadmap.stores.github_store import GhRunner, GitHubRoadmapStore from devops_cli.roadmap.stores.listing_snapshot import ( LISTING_SCHEMA_KEY, @@ -92,15 +99,27 @@ class SharedMeta(BaseModel): - """The `meta` field of a shared snapshot. `token` is new for each write, so two writes never - give the same `meta`.""" + """The `meta` field of a shared snapshot. `digest` is the digest of its records (see + `_records_digest`), so two `meta` values that are equal name the same records. Each time + names its UTC offset: a value with no offset does not parse, and the copy is a miss.""" model_config = ConfigDict(frozen=True) schema_key: str - full_at: datetime - watermark: datetime - token: str + full_at: AwareDatetime + watermark: AwareDatetime + digest: str + + +class _RecordTimes(BaseModel): + """The times of a record of a shared snapshot. Each names its UTC offset, so the merge and + the watermark can compare it with the times that GitHub gives.""" + + model_config = ConfigDict(from_attributes=True) + + created_at: AwareDatetime | None = None + updated_at: AwareDatetime | None = None + closed_at: AwareDatetime | None = None @dataclass(frozen=True) @@ -113,23 +132,31 @@ class HeldMeta: @dataclass(frozen=True) class _Seen: - """What the shared copy of a repository held when this process last wrote or read it: its - `meta`, the time of its full read, and a digest of the JSON of each record by number.""" + """The records of a shared copy that a store knows: the bytes of its `meta` and a digest of + the JSON of each record by number.""" raw: bytes - full_at: datetime digests: Mapping[str, bytes] def snapshot_key(repo: str) -> str: - """The Valkey key of the shared snapshot of `repo`.""" - return f"{CONST_VALKEY_ROADMAP_PREFIX}:snapshot:{repo}" + """The Valkey key of the shared snapshot of `repo`, with the casefolded name of `RepoRef`, so + each spelling of a name gives one key.""" + return f"{CONST_VALKEY_ROADMAP_PREFIX}:snapshot:{RepoRef(repo).key}" def _digest(text: bytes) -> bytes: return hashlib.blake2b(text, digest_size=16).digest() +def _records_digest(digests: Mapping[str, bytes]) -> str: + """One digest of the records whose digests by number are `digests`.""" + total = hashlib.blake2b(digest_size=16) + for number in sorted(digests): + total.update(number.encode() + b"\0" + digests[number]) + return total.hexdigest() + + def _parsed(raw: bytes) -> SharedMeta | None: """The facts of a `meta` field; None when it does not parse.""" try: @@ -176,7 +203,8 @@ def meta(self, repo: str) -> HeldMeta | None: def records(self, repo: str, held: HeldMeta) -> ListingSnapshot | None: """The shared snapshot whose `meta` is `held`; None when the read fails, passes its - budget, finds a record that does not parse, or finds that another writer changed it.""" + budget, finds a record that does not parse, or finds records that are not the ones that + `held` names, because another writer changed them.""" if held.meta is None: return None key = snapshot_key(repo) @@ -199,19 +227,24 @@ def records(self, repo: str, held: HeldMeta) -> ListingSnapshot | None: ) _count_budget() return None - if values.pop(META_FIELD, None) != held.raw or self.tier.hget(key, META_FIELD) != held.raw: - return None + values.pop(META_FIELD, None) texts = _decompressed(repo, values) if texts is None: return None + digests = _digests(texts) + if _records_digest(digests) != held.meta.digest: + logger.info("The shared snapshot of %s changed during its load.", repo) + return None try: issues = [IssueRecord.model_validate_json(text) for text in texts.values()] + for issue in issues: + _RecordTimes.model_validate(issue) except ValidationError as exc: logger.info("A record of the shared snapshot of %s does not parse: %s", repo, exc) return None meta = held.meta with self._lock: - self._seen[repo] = _Seen(held.raw, meta.full_at, _digests(texts)) + self._seen[repo] = _Seen(held.raw, digests) return ListingSnapshot( repo=repo, schema_key=meta.schema_key, @@ -232,29 +265,43 @@ def write(self, snapshot: ListingSnapshot, held: HeldMeta | None) -> BrainWrite: """Write `snapshot` over the shared copy whose `meta` was `held`, and return the result.""" texts = {str(issue.number): issue.model_dump_json().encode() for issue in snapshot.issues} records = {number: zlib.compress(text) for number, text in texts.items()} - if any(len(value) > DEFAULT_BRAIN_VALUE_MAX_BYTES for value in records.values()): + if any( + len(value) > DEFAULT_BRAIN_VALUE_MAX_BYTES + for value in (*texts.values(), *records.values()) + ): return BrainWrite.OVERSIZE + digests = _digests(texts) meta = SharedMeta( schema_key=snapshot.schema_key, full_at=snapshot.full_at, watermark=snapshot.watermark, - token=uuid.uuid4().hex, + digest=_records_digest(digests), ) - if held is not None and not may_replace(held.meta, meta): + stored = None if held is None else held.meta + if held is not None and not may_replace(stored, meta): return BrainWrite.OLDER - seen = _Seen(meta.model_dump_json().encode(), meta.full_at, _digests(texts)) - with self._lock: - before = self._seen.get(snapshot.repo) - if ( - before is not None - and held is not None - and before.raw == held.raw - and before.full_at == snapshot.full_at - and self._update(snapshot.repo, before, seen, records) - ): + if held is not None and stored is not None and _holds(stored, meta): + self.tier.expire(snapshot_key(snapshot.repo), DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS) + return self._kept(snapshot.repo, _Seen(held.raw, digests), BrainWrite.UNCHANGED) + seen = _Seen(meta.model_dump_json().encode(), digests) + known = self._known(snapshot.repo, held, seen) + if known is not None and self._update(snapshot.repo, known, seen, records): return self._kept(snapshot.repo, seen) return self._replace(snapshot.repo, meta, seen, records) + def _known(self, repo: str, held: HeldMeta | None, mine: _Seen) -> _Seen | None: + """The records of the stored copy whose `meta` is `held`, when the store knows them: they + are the records of `mine`, or the records that this process last wrote or read.""" + stored = None if held is None else held.meta + if held is None or stored is None: + return None + with self._lock: + before = self._seen.get(repo) + for digests in (mine.digests, None if before is None else before.digests): + if digests is not None and stored.digest == _records_digest(digests): + return _Seen(held.raw, digests) + return None + def _update(self, repo: str, before: _Seen, seen: _Seen, records: dict[str, bytes]) -> bool: """Send the changed and removed records and the new `meta` in one transaction, when the stored `meta` is still the one of `before`.""" @@ -285,7 +332,7 @@ def _replace( """Write every record to a temporary key, then RENAME it onto the snapshot key when the stored copy may still be replaced.""" key = snapshot_key(repo) - temporary = f"{key}:next:{meta.token}" + temporary = f"{key}:next:{uuid.uuid4().hex}" written = self.tier.hset(temporary, {META_FIELD: seen.raw}) is not None and ( self.tier.expire(temporary, DEFAULT_BRAIN_SNAPSHOT_TEMPORARY_TTL_SECONDS) ) @@ -306,10 +353,27 @@ def decide(current: bytes | None) -> list[tuple[Any, ...]]: self.tier.unlink(temporary) return BrainWrite.SKIPPED if renamed is None else BrainWrite.OLDER - def _kept(self, repo: str, seen: _Seen) -> BrainWrite: + def _kept(self, repo: str, seen: _Seen, result: BrainWrite = BrainWrite.SHARED) -> BrainWrite: with self._lock: self._seen[repo] = seen - return BrainWrite.SHARED + return result + + def remove(self, repo: str) -> bool: + """Remove the shared snapshot of `repo`; whether Valkey removed a key.""" + with self._lock: + self._seen.pop(repo, None) + return bool(self.tier.unlink(snapshot_key(repo))) + + +def _holds(stored: SharedMeta, mine: SharedMeta) -> bool: + """Whether the stored copy already holds what `mine` would write: the same schema key and + records, and a full read and a watermark that are not older.""" + return ( + stored.schema_key == mine.schema_key + and stored.digest == mine.digest + and stored.watermark >= mine.watermark + and stored.full_at >= mine.full_at + ) def _digests(texts: Mapping[str, bytes]) -> dict[str, bytes]: @@ -317,12 +381,25 @@ def _digests(texts: Mapping[str, bytes]) -> dict[str, bytes]: def _decompressed(repo: str, values: Mapping[str, bytes]) -> dict[str, bytes] | None: - """The JSON of each record; None when a value is not zlib data.""" - try: - return {number: zlib.decompress(value) for number, value in values.items()} - except zlib.error as exc: - logger.info("A record of the shared snapshot of %s is not zlib data: %s", repo, exc) - return None + """The JSON of each record; None when a value is not whole zlib data or expands past + `DEFAULT_BRAIN_VALUE_MAX_BYTES`, which no writer of the store writes.""" + texts: dict[str, bytes] = {} + for number, value in values.items(): + expander = zlib.decompressobj() + try: + text = expander.decompress(value, DEFAULT_BRAIN_VALUE_MAX_BYTES) + except zlib.error as exc: + logger.info("A record of the shared snapshot of %s is not zlib data: %s", repo, exc) + return None + if expander.unconsumed_tail or not expander.eof: + logger.info( + "A record of the shared snapshot of %s is cut off or expands past %s bytes.", + repo, + DEFAULT_BRAIN_VALUE_MAX_BYTES, + ) + return None + texts[number] = text + return texts _STORE_LOCK = threading.Lock() @@ -342,7 +419,8 @@ def shared_snapshot_store() -> ValkeySnapshotStore | None: _VISIBILITY_LOCK = threading.Lock() -# The visibility of each repository that this process read: whether it is public, and when. +# The visibility of each repository that this process read, by `RepoRef.key`: whether it is +# public, and when. _visibility: dict[str, tuple[bool, float]] = {} @@ -351,8 +429,9 @@ def repository_is_public(repo: str, *, runner: GhRunner | None = None) -> bool: `DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS`. A failed read counts as private and is not kept, so the shared tier gets no data that could be private (ADR 0023 section 8).""" now = clock.monotonic() + name = RepoRef(repo).key with _VISIBILITY_LOCK: - held = _visibility.get(repo) + held = _visibility.get(name) if held is not None and now - held[1] < DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS: return held[0] store = GitHubRoadmapStore(repo) if runner is None else GitHubRoadmapStore(repo, runner=runner) @@ -366,7 +445,7 @@ def repository_is_public(repo: str, *, runner: GhRunner | None = None) -> bool: ) return False with _VISIBILITY_LOCK: - _visibility[repo] = (public, now) + _visibility[name] = (public, now) return public @@ -405,7 +484,7 @@ def load(self, repo: str) -> ListingSnapshot | None: if shared is None or (held is None and shared.tier.is_open): count_read(BrainStore.SNAPSHOT, BrainRead.FALLBACK) return local - if not self.is_public(repo): + if not self._public(shared, repo, held): count_read(BrainStore.SNAPSHOT, BrainRead.PRIVATE) return local now = self.clock() @@ -417,7 +496,7 @@ def load(self, repo: str) -> ListingSnapshot | None: or not self._fit(meta, now) or (local is not None and local_fit and local.watermark >= meta.watermark) ): - count_read(BrainStore.SNAPSHOT, BrainRead.SOURCE) + count_read(BrainStore.SNAPSHOT, BrainRead.LOCAL if local_fit else BrainRead.SOURCE) return local copy = shared.records(repo, held) if copy is None: @@ -439,10 +518,20 @@ def _share(self, snapshot: ListingSnapshot) -> BrainWrite: held = None if shared is None else shared.meta(snapshot.repo) if shared is None or (held is None and shared.tier.is_open): return BrainWrite.SKIPPED - if not self.is_public(snapshot.repo): + if not self._public(shared, snapshot.repo, held): return BrainWrite.PRIVATE return shared.write(snapshot, held) + def _public(self, shared: ValkeySnapshotStore, repo: str, held: HeldMeta | None) -> bool: + """Whether `repo` is public. The shared copy of a repository that is not public is + removed, so the shared tier keeps no copy of a repository that became private.""" + if self.is_public(repo): + return True + if held is not None and shared.remove(repo): + logger.info("The shared tier held the listing of %s, which is not public now.", repo) + count_write(BrainStore.SNAPSHOT, BrainWrite.REMOVED) + return False + def _fit(self, held: ListingSnapshot | SharedMeta | None, now: datetime) -> bool: """Whether a run can read the changes from `held`: it has this schema key, and its last full read is younger than the max age.""" diff --git a/src/devops_cli/telemetry/instruments.py b/src/devops_cli/telemetry/instruments.py index 54fb59e51b..4edd7dee55 100644 --- a/src/devops_cli/telemetry/instruments.py +++ b/src/devops_cli/telemetry/instruments.py @@ -711,18 +711,20 @@ class Instrument: "devops_cli_brain_reads_total", InstrumentKind.COUNTER, "1", - "Reads of the project brain (#4668), by store (snapshot or fact) and result: memory or " - "shared for the tier that gave the value, source when no tier held it, fallback when the " - "shared tier failed or its breaker was open, and private for a repository that the shared " - "tier does not hold", + "Reads of the project brain (#4668), by store (snapshot or fact) and result: memory, local " + "or shared for the tier that gave the value (local is the snapshot file of the process), " + "source when no tier held it, fallback when the shared tier failed or its breaker was open, " + "and private for a repository that the shared tier does not hold", ) BRAIN_WRITES_TOTAL = Instrument( "devops_cli_brain_writes_total", InstrumentKind.COUNTER, "1", "Writes of the project brain to the shared tier (#4668), by store and result: shared, " - "skipped while the tier failed, oversize for a value over 1 MiB that stays in memory, older " - "when the shared snapshot is newer or another writer won, and private", + "unchanged when the shared snapshot already holds the same records, skipped while the tier " + "failed, oversize for a value over 1 MiB that stays in memory, older when the shared " + "snapshot is newer or another writer won, private, and removed for the shared snapshot of a " + "repository that became private", ) VALKEY_CACHE_ERRORS_TOTAL = Instrument( "devops_cli_valkey_cache_errors_total", diff --git a/src/devops_cli/valkey/client.py b/src/devops_cli/valkey/client.py index 091b6975ab..5f862f0752 100644 --- a/src/devops_cli/valkey/client.py +++ b/src/devops_cli/valkey/client.py @@ -347,29 +347,49 @@ def watch_and_write( `decide`. When `decide` gives no command, nothing is written. When another client changed `key` after the WATCH, EXEC writes nothing. In both cases the result is False, and the client does not try again, unlike `Valkey.transaction` of valkey-py, which tries again. + + valkey-py also gives a `WatchError` when the connection fails or times out while the + client watches the key, with that failure as its context. The client raises that failure + as the `ValkeyError` of its kind, so a lost connection is never a lost race. """ # valkey-py's pipeline has no type hints. pipe: Any = self._raw.pipeline(transaction=True) with _valkey_failures(self.host, self.port, self.timeout), pipe: - pipe.watch(key) - value = pipe.execute_command("HGET", key, field, **{NEVER_DECODE: True}) - commands = decide(None if value is None else bytes(value)) - if not commands: - return False - pipe.multi() - for command in commands: - pipe.execute_command(*command) try: - pipe.execute() - except valkey_exceptions.WatchError: + return _watched_write(pipe, key, field, decide) + except valkey_exceptions.WatchError as exc: + failure = exc.__context__ + if isinstance( + failure, valkey_exceptions.ConnectionError | valkey_exceptions.TimeoutError + ): + raise failure from None return False - return True def close(self) -> None: """Close every connection the client holds.""" self._valkey.connection_pool.disconnect() +def _watched_write( + pipe: Any, + key: str, + field: str, + decide: Callable[[bytes | None], Sequence[Sequence[Any]]], +) -> bool: + """WATCH `key`, give `decide` the bytes of `field`, and send its commands in one MULTI/EXEC + on `pipe`. False when `decide` gives no command; a lost race raises `WatchError`.""" + pipe.watch(key) + value = pipe.execute_command("HGET", key, field, **{NEVER_DECODE: True}) + commands = decide(None if value is None else bytes(value)) + if not commands: + return False + pipe.multi() + for command in commands: + pipe.execute_command(*command) + pipe.execute() + return True + + _VALKEY_CLIENT_OVERRIDE: ValkeyProtocol | None = None diff --git a/tests/valkey/test_valkey_cache_tier.py b/tests/valkey/test_valkey_cache_tier.py index 62c7f2f13e..79985cd76e 100644 --- a/tests/valkey/test_valkey_cache_tier.py +++ b/tests/valkey/test_valkey_cache_tier.py @@ -20,6 +20,7 @@ from tests.support.fakes.clock import ClockFake from tests.support.fakes.otlp import FakeCollector from tests.support.fakes.valkey import SilentValkey, valkey_client_on +from tests.support.waits import THREAD_HANDOFF_BOUND_SECONDS, wait_until if TYPE_CHECKING: from pathlib import Path @@ -27,6 +28,8 @@ from devops_cli.valkey.cache import ValkeyCacheTier _TIER_LOGGER = "devops_cli.valkey.cache" +# The window of a wait that checks that the listener accepts no second connection. +_QUIET_SECONDS: float = 0.2 _STATE_CHANGE = "The circuit breaker of the Valkey cache tier changed" @@ -434,17 +437,24 @@ def read(name: str) -> str: return f"source {name}" reads = (read("a"), read("b")) + # The accept thread of the listener records the connection; wait for it with the bound. + accepted = wait_until(lambda: silent_valkey.connections >= 1, THREAD_HANDOFF_BOUND_SECONDS) + # A second connection would wait in the backlog of the listener. This short window checks + # that the thread accepts none, and opens only once it has accepted the first. + second = wait_until(lambda: silent_valkey.connections > 1, _QUIET_SECONDS) assert ( tier.client.connect_timeout <= DEFAULT_VALKEY_CACHE_CONNECT_TIMEOUT_SECONDS, reads, tier.is_open, - silent_valkey.connections, + accepted, + second, _errors(otlp), ) == ( True, ("source a", "source b"), True, - 1, + True, + False, {("get", "timeout"): 1.0, ("get", "open"): 1.0, ("set", "open"): 2.0}, ) From 61090f9fd77cccf3ca7a42431bc22c18a1dfd691 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 02:53:38 +0000 Subject: [PATCH 18/20] test(roadmap): the lanes of one process scan a shared copy once Lane A of a process saves a newer watermark. Lane B, whose local copy is older, takes the records that the store of the process holds, and sends no HSCAN. --- tests/roadmap/stores/test_listing_shared.py | 25 +++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/roadmap/stores/test_listing_shared.py b/tests/roadmap/stores/test_listing_shared.py index 89b1ec1fc0..cb42ccc77b 100644 --- a/tests/roadmap/stores/test_listing_shared.py +++ b/tests/roadmap/stores/test_listing_shared.py @@ -704,3 +704,28 @@ def test_a_load_counts_the_tier_that_gave_the_snapshot(tmp_path: Path, otlp: Fak snapshot, {("snapshot", "source"): 1.0, ("snapshot", "local"): 1.0}, ) + + +def test_the_lanes_of_one_process_scan_the_records_of_a_shared_copy_once( + tmp_path: Path, valkey_server: FakeServer +) -> None: + """Lane A of a process saves a newer watermark. Lane B, whose local copy is older, takes the + shared copy that the store of the process holds: it reads `meta` and sends no `HSCAN`.""" + sent: list[str] = [] + store = _valkey_store( + ValkeyCacheTier( + valkey_client_on(valkey_server, after_command=lambda command: sent.append(command[0])) + ) + ) + lane_a = _tiered(tmp_path / "a", shared=lambda: store) + lane_b = _tiered(tmp_path / "b", shared=lambda: store) + lane_b.save(_snapshot(STARTED - timedelta(hours=1), 2, 1)) + lane_a.save(_snapshot(STARTED, 3, 2, 1)) + sent.clear() + + loaded = lane_b.load(REPO) + + assert ( + None if loaded is None else ([issue.number for issue in loaded.issues], loaded.watermark), + sent, + ) == (([3, 2, 1], STARTED), ["HGET"]) From a3b747013a8e36c1c0ff316d04c44fda205f7e4d Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 02:54:38 +0000 Subject: [PATCH 19/20] perf(roadmap): the lanes of one process scan a shared copy once In a busy repository the watermark moves on each round, so the local copy of each lane is older than the shared copy that the last lane wrote, and each lane round scanned the 14 MB of devops-cli again behind the lock of the breaker. The shared store of the process keeps the records of the last copy that it wrote or read, and a load whose meta names them sends no HSCAN. --- docs/roadmap/intake.md | 2 +- .../design.md | 2 + .../specs/project-brain/shared-cache/spec.md | 7 ++ .../tasks.md | 4 +- .../roadmap/stores/listing_shared.py | 100 ++++++++++++------ 5 files changed, 77 insertions(+), 38 deletions(-) diff --git a/docs/roadmap/intake.md b/docs/roadmap/intake.md index 3000732f16..23870725f3 100644 --- a/docs/roadmap/intake.md +++ b/docs/roadmap/intake.md @@ -118,7 +118,7 @@ Intake compares each candidate with every item and with every issue closed as no - A run reads the whole listing and writes a new snapshot when neither its local file nor the shared tier (below) keeps a fit snapshot, and on `--full`. A snapshot is fit when it can be read, its schema key is the current one, and its last full read is younger than 24 hours. The full read removes an issue that left the repository. - The snapshot is a copy of GitHub, which stays the source of truth. A snapshot that intake cannot read or write gives a warning. A failed write keeps the earlier file, because intake writes a temporary file and renames it. -In the Service, the lane of `intake` runs its intake rounds and the scoped intake of each delivery one at a time, so one writer keeps the snapshot of each repository. Thus a scoped round with a kept snapshot sends one listing request when 100 or fewer issues changed. The poll still reconciles each change that moved an `updated_at` (ADR 0017), and the full read of each day removes an issue that left the repository. Each other lane reads every issue through a snapshot of its own, in `listing-` of the state directory, which only its worker writes (#4854, #5553). Each local file sits under a shared copy of each public repository in the cache Valkey `valkey-devops` (`TieredSnapshotStore` in `src/devops_cli/roadmap/stores/listing_shared.py`, #4668). A run takes the fit copy with the newer watermark, so a pod with no local snapshot reads only the changes since the shared watermark. A writer replaces the shared copy only when its watermark is not older. A save of the records that the shared copy already holds sends no record, so a round of a lane of a quiet repository sends only reads of `meta` and one TTL command to Valkey. While Valkey is down, a run reads and writes its local file only. The shared tier holds no copy of a private repository until `valkey-devops` has role ACL users (#4704): a failed read of the visibility counts as private, and a round removes the shared copy of a repository that became private, at most one hour after the change. `devops_cli_brain_reads_total{store="snapshot"}` counts where each load came from (`local`, `shared`, or `source` for a full read), and `devops_cli_brain_github_requests_saved_total` counts the listing pages that a shared copy saved. +In the Service, the lane of `intake` runs its intake rounds and the scoped intake of each delivery one at a time, so one writer keeps the snapshot of each repository. Thus a scoped round with a kept snapshot sends one listing request when 100 or fewer issues changed. The poll still reconciles each change that moved an `updated_at` (ADR 0017), and the full read of each day removes an issue that left the repository. Each other lane reads every issue through a snapshot of its own, in `listing-` of the state directory, which only its worker writes (#4854, #5553). Each local file sits under a shared copy of each public repository in the cache Valkey `valkey-devops` (`TieredSnapshotStore` in `src/devops_cli/roadmap/stores/listing_shared.py`, #4668). A run takes the fit copy with the newer watermark, so a pod with no local snapshot reads only the changes since the shared watermark. A writer replaces the shared copy only when its watermark is not older. The lanes of the Service share one store, which keeps the records of the last shared copy that it wrote or read, so a lane takes a copy that another lane wrote with no scan of Valkey. A save of the records that the shared copy already holds sends no record, so a round of a lane of a quiet repository sends only reads of `meta` and one TTL command to Valkey. While Valkey is down, a run reads and writes its local file only. The shared tier holds no copy of a private repository until `valkey-devops` has role ACL users (#4704): a failed read of the visibility counts as private, and a round removes the shared copy of a repository that became private, at most one hour after the change. `devops_cli_brain_reads_total{store="snapshot"}` counts where each load came from (`local`, `shared`, or `source` for a full read), and `devops_cli_brain_github_requests_saved_total` counts the listing pages that a shared copy saved. ## A failed write diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md index 213032e3a9..d34312400d 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md @@ -14,6 +14,7 @@ - **`TieredSnapshotStore` combines the local and the shared store.**: ADR 0023 section 2 says that a reader loads the local and the shared copy, drops a copy with another schema or a full read older than 24 hours, and takes the copy with the newer watermark. The rule needs both copies at one place, so it is a store of its own and not a change of `IncrementalListing`. A save writes the shared tier first and then the local file, the order of ADR 0023 section 2. - **The newest watermark wins.**: A writer WATCHes the snapshot key, reads `meta`, and writes in one MULTI/EXEC only when its watermark is not older than the stored one, or when the stored copy has another schema. An EXEC that another client made fail writes nothing, and the writer does not retry: the other writer is newer or equal. This is the safe stop of ADR 0023 section 4. - **A save of unchanged records writes none, a save of known records writes only the changes, and any other save goes through a temporary key and RENAME.**: The Service runs a lane for each job, about 24 for each repository, and each lane saves after each round with a full read of its own time. When the stored `meta` has the schema key and the digest of the snapshot and a watermark and a full read that are not older, the save sends only `EXPIRE` and counts `unchanged`. When the store knows the stored records (the stored digest is the digest of the snapshot, or of the copy that this process last wrote or read), it sends `HSET` for the changed records, `HDEL` for the removed ones and the new `meta` in one WATCH transaction on the stored `meta`. Under the WATCH, the stored records are the known ones, so the result is the same as a RENAME, and a full read so removes each issue that left the repository. In every other case it writes all records to `:next:` in batches and then, under the WATCH of the snapshot key, RENAMEs the temporary key onto it and sets its TTL. A rewrite of the 14 MB of devops-cli took 3.09 s on the temporary pod, so the lanes of a quiet repository must not send one on each round. +- **The shared store of a process keeps the records of the last shared copy that it wrote or read.**: In a busy repository, the watermark moves on each round, so the local copy of each lane is older than the shared copy that the last lane wrote, and each lane round would scan the 14 MB of devops-cli again (about 2 s, and pybreaker holds the lock of the process for each command). The lanes of the Service share the store of the process, so a load whose `meta` names the records that the store holds takes them with no `HSCAN`. The cost is one copy of each public repository in the memory of the process, about 40 MB for devops-cli, and the lanes share its records. - **A load reads `meta` first, then the records with `HSCAN COUNT 500`, within a budget of 20 s.**: The budget (`DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS`) is checked between two scans. Past it, the load is a miss: the reader takes the local copy or reads GitHub, and the store counts `devops_cli_valkey_cache_errors_total{op="hscan",error="budget"}`. Each command keeps the 2 s bound of `valkey.timeout`, which is shorter than the budget, as ADR 0023 section 2 asks. The values come back as bytes through `NEVER_DECODE`. The load uses the records only when their digest is the `digest` of the `meta` that it read first: a write of other records during the scan makes it a miss, and a new `meta` of the same records does not. - **The values of the shared tier are untrusted.**: Each client with the password can write a key. `SharedMeta` declares its times as pydantic `AwareDatetime`, and each record goes through a model of its times with `AwareDatetime`, so a time with no UTC offset is a miss and never a `TypeError` in a compare. A record expands with `zlib.decompressobj` up to `DEFAULT_BRAIN_VALUE_MAX_BYTES` (1 MiB), and a record that does not end there is a miss, so one value cannot fill the memory of the reader. The writer keeps both the JSON and the zlib form of each record under the same bound, so a reader refuses no record that the store wrote. - **The shared tier holds data of public repositories only.**: ADR 0023 section 8 keeps a private repository in the local tier until `valkey-devops` has role ACL users (#4704). `TieredSnapshotStore` asks a visibility check before it uses the shared tier for a repository. The check reads `isPrivate` through the GraphQL query of `is_private_args`, once for each repository and process in each hour (`DEFAULT_BRAIN_VISIBILITY_TTL_SECONDS`). A failed read counts as private and is not kept. The store reads the visibility only after the shared tier answered the read of `meta`, so a run with no reachable Valkey, such as a workstation, sends no visibility read. For a private repository the store drops what that read gave, reads no record, writes no key and counts `result="private"`. When the read of `meta` found a key of a repository that is not public, the store sends `UNLINK` of the key and counts `devops_cli_brain_writes_total{result="removed"}`. A repository that becomes private can so keep its shared copy, and get writes to it, for at most the hour of the visibility answer of a process; a shorter answer would cost a GraphQL read for each repository and round. @@ -49,6 +50,7 @@ - **A per-process LRU only for the facts.**: Each release restarts the Service, and each Job is a new process, so an LRU alone is cold at each start. - **The label `instance` on `devops_cli_valkey_cache_errors_total`.**: The collector replaces it with the label of the resource, and the test of #3240 refuses it, as the decision above says. - **A token that is new for each write in `meta`.**: Each save then changed `meta`, so another process never knew the stored records and wrote all 14 MB again, and each change spoiled a load that was scanning. The digest of the records names the same thing for each writer. +- **Take the shared copy only when the local copy is missing or unfit.**: It would remove the scans of the lanes too, but ADR 0023 section 2 sets the newer watermark, and a local copy that is fit but many hours old would then read more pages from GitHub. - **A full write after each full read.**: Under the WATCH of `meta`, a write of the changed and removed records gives the same records as a RENAME, at the cost of the changes only. - **A Prometheus rule for the three-quarters rule of each Valkey in this item.**: It changes the alerting of every Valkey, not the shared tier, so the pull request comments it on #4992. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md index 3254052287..83c4b9ad41 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md @@ -61,6 +61,13 @@ A save that may replace the shared snapshot SHALL leave it with the records of t - **WHEN** the shared snapshot holds issues 1, 2 and 3, and a full read lists issues 1 and 3 - **THEN** the shared snapshot holds issues 1 and 3 only, and no temporary key stays +### Requirement: The lanes of one process scan a shared copy once +A load SHALL take the records of the shared snapshot from the shared store of the process, and SHALL send no `HSCAN`, when the process last wrote or read the records that the stored `meta` names. + +#### Scenario: A lane after another lane of the process +- **WHEN** lane B of a process saved a snapshot with the watermark 09:00, lane A of the same process saved one with the watermark 10:00, and lane B loads +- **THEN** lane B gets the records and the watermark 10:00 of lane A, and sends only the read of `meta` to Valkey + ### Requirement: A save of the records that the shared copy holds writes no record A save whose records, schema key and watermark the shared snapshot already holds, with a full read that is not newer than the stored one, SHALL send no record and no transaction: it SHALL set the TTL of the key again, keep the stored `meta`, and count `devops_cli_brain_writes_total{result="unchanged"}`. diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md index d2fa73fbac..998d97e0ee 100644 --- a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md +++ b/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md @@ -75,9 +75,9 @@ Kind: other. Reads: `k8s/README.md`, `docs/roadmap/intake.md`, `docs/roadmap/alt Kind: behavior. Reads: `src/devops_cli/roadmap/stores/listing_shared.py`, `src/devops_cli/valkey/client.py`, `src/devops_cli/github/repo_ref.py`, `openspec/specs/roadmap-intake-listing/spec.md`, `docs/TESTING.md`. Changes: `src/devops_cli/roadmap/stores/listing_shared.py`, `src/devops_cli/valkey/client.py`, `src/devops_cli/config/constants.py`, `src/devops_cli/config/defaults.py`, `src/devops_cli/telemetry/instruments.py`, `tests/roadmap/stores/test_listing_shared.py`, `tests/valkey/test_valkey_cache_tier.py`, `tests/support/fakes/valkey.py`, `docs/roadmap/intake.md`, `docs/TELEMETRY.md`, `k8s/README.md`, `openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md`. -- [x] 9.1 Give `valkey_client_on` of `tests/support/fakes/valkey.py` an `after_command` action, which runs after each command that a client sends alone, and make its connection give valkey-py's `ConnectionError` for a write to a stopped server. Replace the test subclasses of `ValkeyCacheTier` in `tests/roadmap/stores/test_listing_shared.py` with it. Write `test_a_save_of_the_records_that_the_shared_copy_holds_writes_no_record`, `test_a_new_meta_of_the_same_records_during_a_load_keeps_the_shared_copy`, `test_a_shared_copy_with_a_time_with_no_offset_or_a_record_past_the_bound_is_a_miss`, `test_a_repository_that_became_private_leaves_the_shared_tier`, `test_one_shared_key_and_one_visibility_read_hold_a_repository_in_each_spelling` and `test_a_load_counts_the_tier_that_gave_the_snapshot` in `tests/roadmap/stores/test_listing_shared.py`, and `test_a_valkey_that_goes_away_in_a_watch_transaction_opens_the_breaker` in `tests/valkey/test_valkey_cache_tier.py`. Make `test_a_silent_valkey_times_out_and_opens_the_breaker` wait for the accept thread with `THREAD_HANDOFF_BOUND_SECONDS` +- [x] 9.1 Give `valkey_client_on` of `tests/support/fakes/valkey.py` an `after_command` action, which runs after each command that a client sends alone, and make its connection give valkey-py's `ConnectionError` for a write to a stopped server. Replace the test subclasses of `ValkeyCacheTier` in `tests/roadmap/stores/test_listing_shared.py` with it. Write `test_a_save_of_the_records_that_the_shared_copy_holds_writes_no_record`, `test_a_new_meta_of_the_same_records_during_a_load_keeps_the_shared_copy`, `test_a_shared_copy_with_a_time_with_no_offset_or_a_record_past_the_bound_is_a_miss`, `test_a_repository_that_became_private_leaves_the_shared_tier`, `test_one_shared_key_and_one_visibility_read_hold_a_repository_in_each_spelling` `test_a_load_counts_the_tier_that_gave_the_snapshot` and `test_the_lanes_of_one_process_scan_the_records_of_a_shared_copy_once` in `tests/roadmap/stores/test_listing_shared.py`, and `test_a_valkey_that_goes_away_in_a_watch_transaction_opens_the_breaker` in `tests/valkey/test_valkey_cache_tier.py`. Make `test_a_silent_valkey_times_out_and_opens_the_breaker` wait for the accept thread with `THREAD_HANDOFF_BOUND_SECONDS` - Verification: `$ uv run devops ci test tests/roadmap/stores/test_listing_shared.py tests/valkey/test_valkey_cache_tier.py` fails on the commit before 9.2 -- [x] 9.2 Put a `digest` of the records in `SharedMeta` in place of the `token`, and declare its times `AwareDatetime`. A save of the records that the stored copy holds with no newer full read or watermark sends only `EXPIRE` and counts `unchanged`; a save of known records sends the changes in one WATCH transaction; a load uses the records only when they have the digest of `meta`, refuses a record time with no UTC offset, and expands a record with `zlib.decompressobj` up to `DEFAULT_BRAIN_VALUE_MAX_BYTES`. The key and the visibility answers use `RepoRef.key`. A load or a save that finds the key of a repository that is not public removes it and counts `removed`; a load from the fit local file counts `local`. `ValkeyClient.watch_and_write` raises the connection failure or the timeout that a `WatchError` holds as its context. Add `BrainRead.LOCAL`, `BrainWrite.UNCHANGED` and `BrainWrite.REMOVED` +- [x] 9.2 Put a `digest` of the records in `SharedMeta` in place of the `token`, and declare its times `AwareDatetime`. A save of the records that the stored copy holds with no newer full read or watermark sends only `EXPIRE` and counts `unchanged`; a save of known records sends the changes in one WATCH transaction; a load uses the records only when they have the digest of `meta`, and takes them with no `HSCAN` from the store of the process when the store last wrote or read them, refuses a record time with no UTC offset, and expands a record with `zlib.decompressobj` up to `DEFAULT_BRAIN_VALUE_MAX_BYTES`. The key and the visibility answers use `RepoRef.key`. A load or a save that finds the key of a repository that is not public removes it and counts `removed`; a load from the fit local file counts `local`. `ValkeyClient.watch_and_write` raises the connection failure or the timeout that a `WatchError` holds as its context. Add `BrainRead.LOCAL`, `BrainWrite.UNCHANGED` and `BrainWrite.REMOVED` - Verification: `$ uv run devops ci test tests/roadmap/stores/test_listing_shared.py tests/valkey/test_valkey_cache_tier.py tests/valkey/test_tiered.py tests/valkey/test_valkey_contract.py` passes - [x] 9.3 Add the MODIFIED delta of `roadmap-intake-listing` ("Full read" and "The Service reads through the snapshot"), change the full-read bullet of `docs/roadmap/intake.md`, name the removal of the snapshot of a repository that became private in `k8s/README.md`, say in the memory-bound requirement that the `k8s` row proves only the render, and regenerate `docs/TELEMETRY.md` - Verification: `$ uv run devops openspec check` passes diff --git a/src/devops_cli/roadmap/stores/listing_shared.py b/src/devops_cli/roadmap/stores/listing_shared.py index 964f396574..7e13f244e6 100644 --- a/src/devops_cli/roadmap/stores/listing_shared.py +++ b/src/devops_cli/roadmap/stores/listing_shared.py @@ -51,6 +51,7 @@ from collections.abc import Callable, Mapping from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta +from functools import cached_property from itertools import batched from typing import Any, Final @@ -132,11 +133,18 @@ class HeldMeta: @dataclass(frozen=True) class _Seen: - """The records of a shared copy that a store knows: the bytes of its `meta` and a digest of - the JSON of each record by number.""" + """The records of a shared copy that a store knows: the bytes of its `meta`, a digest of the + JSON of each record by number, and the records, the highest number first, when the store + wrote or read them.""" raw: bytes digests: Mapping[str, bytes] + issues: tuple[IssueRecord, ...] | None = None + + @cached_property + def digest(self) -> str: + """The digest of the records, as `meta` names it.""" + return _records_digest(self.digests) def snapshot_key(repo: str) -> str: @@ -157,6 +165,21 @@ def _records_digest(digests: Mapping[str, bytes]) -> str: return total.hexdigest() +def _listing(repo: str, meta: SharedMeta, issues: tuple[IssueRecord, ...]) -> ListingSnapshot: + """The snapshot of `repo` with the facts of `meta` and the records `issues`.""" + return ListingSnapshot( + repo=repo, + schema_key=meta.schema_key, + full_at=meta.full_at, + watermark=meta.watermark, + issues=issues, + ) + + +def _newest_first(issues: tuple[IssueRecord, ...] | list[IssueRecord]) -> tuple[IssueRecord, ...]: + return tuple(sorted(issues, key=lambda issue: issue.number, reverse=True)) + + def _parsed(raw: bytes) -> SharedMeta | None: """The facts of a `meta` field; None when it does not parse.""" try: @@ -186,8 +209,9 @@ def _count_budget() -> None: class ValkeySnapshotStore: """The snapshots of the repositories in the cache Valkey, one hash for each repository. - The store keeps what the shared copy of each repository held when the store last wrote or - read it, so a later write sends only the changed records. One store lives for a process + The store keeps the records of the shared copy of each repository that it last wrote or + read, so a later write sends only the changed records, and a later load of the same records, + such as by another lane of the process, sends no `HSCAN`. One store lives for a process (`shared_snapshot_store`). """ @@ -207,6 +231,36 @@ def records(self, repo: str, held: HeldMeta) -> ListingSnapshot | None: `held` names, because another writer changed them.""" if held.meta is None: return None + with self._lock: + before = self._seen.get(repo) + if before is not None and before.issues is not None and before.digest == held.meta.digest: + return _listing(repo, held.meta, before.issues) + values = self._scan(repo) + if values is None: + return None + values.pop(META_FIELD, None) + texts = _decompressed(repo, values) + if texts is None: + return None + digests = _digests(texts) + if _records_digest(digests) != held.meta.digest: + logger.info("The shared snapshot of %s changed during its load.", repo) + return None + try: + issues = [IssueRecord.model_validate_json(text) for text in texts.values()] + for issue in issues: + _RecordTimes.model_validate(issue) + except ValidationError as exc: + logger.info("A record of the shared snapshot of %s does not parse: %s", repo, exc) + return None + newest_first = _newest_first(issues) + with self._lock: + self._seen[repo] = _Seen(held.raw, digests, newest_first) + return _listing(repo, held.meta, newest_first) + + def _scan(self, repo: str) -> dict[str, bytes] | None: + """Every field of the shared snapshot of `repo` by `HSCAN`; None when a step fails or the + scan passes its budget.""" key = snapshot_key(repo) started = clock.monotonic() values: dict[str, bytes] = {} @@ -218,7 +272,7 @@ def records(self, repo: str, held: HeldMeta) -> ListingSnapshot | None: cursor, fields = step values |= fields if cursor == 0: - break + return values if clock.monotonic() - started > DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS: logger.info( "The load of the shared snapshot of %s passed its budget of %s s.", @@ -227,31 +281,6 @@ def records(self, repo: str, held: HeldMeta) -> ListingSnapshot | None: ) _count_budget() return None - values.pop(META_FIELD, None) - texts = _decompressed(repo, values) - if texts is None: - return None - digests = _digests(texts) - if _records_digest(digests) != held.meta.digest: - logger.info("The shared snapshot of %s changed during its load.", repo) - return None - try: - issues = [IssueRecord.model_validate_json(text) for text in texts.values()] - for issue in issues: - _RecordTimes.model_validate(issue) - except ValidationError as exc: - logger.info("A record of the shared snapshot of %s does not parse: %s", repo, exc) - return None - meta = held.meta - with self._lock: - self._seen[repo] = _Seen(held.raw, digests) - return ListingSnapshot( - repo=repo, - schema_key=meta.schema_key, - full_at=meta.full_at, - watermark=meta.watermark, - issues=tuple(sorted(issues, key=lambda issue: issue.number, reverse=True)), - ) def load(self, repo: str) -> ListingSnapshot | None: held = self.meta(repo) @@ -280,10 +309,11 @@ def write(self, snapshot: ListingSnapshot, held: HeldMeta | None) -> BrainWrite: stored = None if held is None else held.meta if held is not None and not may_replace(stored, meta): return BrainWrite.OLDER + issues = _newest_first(snapshot.issues) if held is not None and stored is not None and _holds(stored, meta): self.tier.expire(snapshot_key(snapshot.repo), DEFAULT_BRAIN_SNAPSHOT_TTL_SECONDS) - return self._kept(snapshot.repo, _Seen(held.raw, digests), BrainWrite.UNCHANGED) - seen = _Seen(meta.model_dump_json().encode(), digests) + return self._kept(snapshot.repo, _Seen(held.raw, digests, issues), BrainWrite.UNCHANGED) + seen = _Seen(meta.model_dump_json().encode(), digests, issues) known = self._known(snapshot.repo, held, seen) if known is not None and self._update(snapshot.repo, known, seen, records): return self._kept(snapshot.repo, seen) @@ -297,9 +327,9 @@ def _known(self, repo: str, held: HeldMeta | None, mine: _Seen) -> _Seen | None: return None with self._lock: before = self._seen.get(repo) - for digests in (mine.digests, None if before is None else before.digests): - if digests is not None and stored.digest == _records_digest(digests): - return _Seen(held.raw, digests) + for known in (mine, before): + if known is not None and stored.digest == known.digest: + return _Seen(held.raw, known.digests) return None def _update(self, repo: str, before: _Seen, seen: _Seen, records: dict[str, bytes]) -> bool: From 84a24acce4a7d2bd2f5567294b5258838b6fb315 Mon Sep 17 00:00:00 2001 From: Daniel Petty Date: Sat, 21 Nov 2026 02:55:04 +0000 Subject: [PATCH 20/20] docs(openspec): archive the shared listing snapshot and tool facts in Valkey --- .../.openspec.yaml | 0 .../design.md | 0 .../proposal.md | 0 .../specs/project-brain/shared-cache/spec.md | 0 .../specs/roadmap-intake-listing/spec.md | 0 .../tasks.md | 0 .../specs/project-brain/shared-cache/spec.md | 165 ++++++++++++++++++ openspec/specs/roadmap-intake-listing/spec.md | 20 ++- 8 files changed, 179 insertions(+), 6 deletions(-) rename openspec/changes/{4668-share-the-listing-snapshot-in-valkey => archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey}/.openspec.yaml (100%) rename openspec/changes/{4668-share-the-listing-snapshot-in-valkey => archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey}/design.md (100%) rename openspec/changes/{4668-share-the-listing-snapshot-in-valkey => archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey}/proposal.md (100%) rename openspec/changes/{4668-share-the-listing-snapshot-in-valkey => archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey}/specs/project-brain/shared-cache/spec.md (100%) rename openspec/changes/{4668-share-the-listing-snapshot-in-valkey => archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey}/specs/roadmap-intake-listing/spec.md (100%) rename openspec/changes/{4668-share-the-listing-snapshot-in-valkey => archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey}/tasks.md (100%) create mode 100644 openspec/specs/project-brain/shared-cache/spec.md diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/.openspec.yaml b/openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/.openspec.yaml similarity index 100% rename from openspec/changes/4668-share-the-listing-snapshot-in-valkey/.openspec.yaml rename to openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/.openspec.yaml diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md b/openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/design.md similarity index 100% rename from openspec/changes/4668-share-the-listing-snapshot-in-valkey/design.md rename to openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/design.md diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md b/openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/proposal.md similarity index 100% rename from openspec/changes/4668-share-the-listing-snapshot-in-valkey/proposal.md rename to openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/proposal.md diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md b/openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md similarity index 100% rename from openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md rename to openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/specs/project-brain/shared-cache/spec.md diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md b/openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md similarity index 100% rename from openspec/changes/4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md rename to openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/specs/roadmap-intake-listing/spec.md diff --git a/openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md b/openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/tasks.md similarity index 100% rename from openspec/changes/4668-share-the-listing-snapshot-in-valkey/tasks.md rename to openspec/changes/archive/2026-11-21-4668-share-the-listing-snapshot-in-valkey/tasks.md diff --git a/openspec/specs/project-brain/shared-cache/spec.md b/openspec/specs/project-brain/shared-cache/spec.md new file mode 100644 index 0000000000..704f6df27d --- /dev/null +++ b/openspec/specs/project-brain/shared-cache/spec.md @@ -0,0 +1,165 @@ +# project-brain/shared-cache Specification + +## Purpose +The shared tier of the project brain in the cache Valkey `valkey-devops` (ADR 0023 section 2): the listing snapshot of each public repository and the tool facts that the alternatives check reads, over the in-process tier, with a fallback to the local tier or the source when Valkey is slow or down, and the memory bound of the cache Valkey that holds them. + +## Requirements + +### Requirement: A cold process reads the shared listing snapshot +When a process has no local snapshot of a public repository and the shared tier holds a fit snapshot of it, the listing read SHALL start from the shared snapshot and read only the issues changed since its watermark, and SHALL count the full read that it saved in `devops_cli_brain_github_requests_saved_total{store="snapshot"}`. + +#### Scenario: Warm shared snapshot, cold process +- **WHEN** a test saves a snapshot of 250 issues of a public repository through one `TieredSnapshotStore` on the `valkey_server` fake, and a new `TieredSnapshotStore` with an empty local directory reads the listing of that repository through `IncrementalListing` while GitHub lists 3 issues as changed +- **THEN** the read sends at most 2 listing requests, each with `since=`, it returns 250 issues with the new title of each changed issue, the local file holds the new snapshot, and `devops_cli_brain_github_requests_saved_total{store="snapshot"}` rises by 3 + +#### Scenario: The newer of the two copies +- **WHEN** the local file holds a snapshot with the watermark 09:00 and the shared tier holds one with the watermark 10:00, both with the current schema key and a full read of less than 24 hours +- **THEN** the listing read sends `since=` with the watermark 10:00 + +### Requirement: A load counts the tier that gave the snapshot +A load of the tiered snapshot store SHALL count `devops_cli_brain_reads_total{store="snapshot"}` with `result="local"` when it gives the fit local copy, `result="shared"` when it gives the shared copy, and `result="source"` only when no tier holds a fit copy, so the run reads the whole listing. + +#### Scenario: Local and source loads +- **WHEN** a load runs with no copy in either tier, and a second load runs after a save that put the same snapshot in both tiers +- **THEN** the first load counts `source`, and the second load returns the local copy and counts `local` + +### Requirement: A read of the shared tier fills the in-process tier +A `TieredMapping` read that misses the in-process tier and hits the shared tier SHALL put the value in the in-process tier, and the next read of the key SHALL send no command to Valkey. + +#### Scenario: T1 read fills the in-process tier +- **WHEN** one `TieredMapping` writes a fact on the `valkey_server` fake, and a second `TieredMapping` with an empty in-process tier reads the key twice +- **THEN** both reads return the fact, the fake receives one read command for the key, and `devops_cli_brain_reads_total{store="fact"}` counts one `shared` and one `memory` + +### Requirement: The tiers fall back while the shared tier is down +While the shared tier fails or its breaker is open, a read SHALL return the value of the in-process tier, the local tier or the source, a write SHALL stay in the in-process tier or the local file, and the counters SHALL count `fallback` and `skipped`. After one failed command the process SHALL send no command to Valkey until the cooldown of 60 s ends. + +#### Scenario: T2 disconnected tier +- **WHEN** the `valkey_server` fake has `connected = False` and a listing round and two fact reads run within one cooldown +- **THEN** the round returns the issues that GitHub lists, the local file holds the new snapshot, each fact read returns the source value, the fake receives no second command after the first failure, `devops_cli_brain_reads_total{result="fallback"}` and `devops_cli_brain_writes_total{result="skipped"}` rise, and no error reaches the caller + +#### Scenario: T3 silent shared tier +- **WHEN** the shared tier is a loopback listener that accepts the connection and answers no command, and `valkey.timeout` is 0.05 s +- **THEN** the tier's client has a connect timeout of at most 0.25 s, the first read ends with `devops_cli_valkey_cache_errors_total{error="timeout"}` and returns the source value, the breaker opens, and the next read sends nothing to the listener + +#### Scenario: A lost connection in a WATCH transaction +- **WHEN** the `valkey_server` fake stops after the WATCH, or after the read of the watched field and before the EXEC +- **THEN** the WATCH transaction gives no result, `devops_cli_valkey_cache_errors_total{op="watch",error="connection"}` rises by one, and the breaker opens, as for each other failed command, and not as for a lost race + +### Requirement: A trial after the cooldown and the newest watermark +After the cooldown the first command SHALL be a trial that closes the breaker when it succeeds. A writer of the shared snapshot SHALL write only when its watermark is not older than the stored watermark or the stored copy has another schema key, and a writer whose WATCH transaction another client made fail SHALL write nothing and SHALL NOT retry. + +#### Scenario: T4 trial, newer local copy and lost WATCH +- **WHEN** the breaker is open with a shared snapshot of watermark 09:00, the `clock` fixture passes the cooldown, a process saves a snapshot of watermark 10:00, and then a second writer with watermark 09:30 loses its WATCH transaction to a write of watermark 10:30 by another client +- **THEN** the trial closes the breaker, the shared snapshot has watermark 10:00 after the first save, the second writer's transaction writes nothing, the shared snapshot keeps watermark 10:30, and `devops_cli_brain_writes_total{result="older"}` rises by one + +#### Scenario: An older writer +- **WHEN** the shared snapshot has watermark 10:00 and a writer saves a snapshot with watermark 09:00 and the same schema key +- **THEN** the shared snapshot keeps watermark 10:00 and its records, and the local file holds the snapshot with watermark 09:00 + +### Requirement: A save leaves the shared snapshot with its records only +A save that may replace the shared snapshot SHALL leave it with the records of the saved snapshot only, so it holds no issue that a full read did not list. A save that knows the stored records SHALL send only the changed and removed records and the new `meta` in one WATCH transaction. Any other save SHALL write the records to a temporary key with a TTL and RENAME it onto the snapshot key in one transaction. + +#### Scenario: An issue left the repository +- **WHEN** the shared snapshot holds issues 1, 2 and 3, and a full read lists issues 1 and 3 +- **THEN** the shared snapshot holds issues 1 and 3 only, and no temporary key stays + +### Requirement: The lanes of one process scan a shared copy once +A load SHALL take the records of the shared snapshot from the shared store of the process, and SHALL send no `HSCAN`, when the process last wrote or read the records that the stored `meta` names. + +#### Scenario: A lane after another lane of the process +- **WHEN** lane B of a process saved a snapshot with the watermark 09:00, lane A of the same process saved one with the watermark 10:00, and lane B loads +- **THEN** lane B gets the records and the watermark 10:00 of lane A, and sends only the read of `meta` to Valkey + +### Requirement: A save of the records that the shared copy holds writes no record +A save whose records, schema key and watermark the shared snapshot already holds, with a full read that is not newer than the stored one, SHALL send no record and no transaction: it SHALL set the TTL of the key again, keep the stored `meta`, and count `devops_cli_brain_writes_total{result="unchanged"}`. + +#### Scenario: Two lanes and a new process with the same records +- **WHEN** two lanes of one process save the same 1,200 records and watermark with full reads at 08:00 and 09:00, and then each saves them again twice, and a new process saves them once +- **THEN** after the first save of each lane, the lanes send only `HGET` and `EXPIRE` commands, the stored `meta` does not change, `devops_cli_brain_writes_total{result="unchanged"}` rises by five, and no temporary key stays + +### Requirement: A load uses only the records that its meta names +A load SHALL use the records of the shared snapshot only when their digest is the digest of the `meta` that the load read first. A new `meta` of the same records during the scan SHALL NOT make the load a miss. A value of the shared tier is untrusted: a `meta` or a record with a time with no UTC offset, and a record that expands past 1 MiB, SHALL make the shared copy a miss, and the next save SHALL replace it. + +#### Scenario: A new meta of the same records during a load +- **WHEN** a writer saves the same 1,200 records with a newer full read after the first `HSCAN` of a cold load +- **THEN** the load gives the 1,200 records of the shared copy and counts `result="shared"` + +#### Scenario: A time with no offset or a record past the bound +- **WHEN** the shared snapshot is newer than the local one, and its `meta` holds a time with no UTC offset, or a record holds one, or a record expands to more than 1 MiB of JSON +- **THEN** the load gives the local snapshot and raises no error, and the next save leaves the shared snapshot with its own watermark and records + +### Requirement: Each value has a bound and each key a TTL +The shared tier SHALL NOT receive a value whose encoded form is over 1 MiB; such a value SHALL stay in the in-process tier and count `devops_cli_brain_writes_total{result="oversize"}`. Each key that the mapping or the snapshot store writes SHALL have a TTL: 24 hours for a fact and 7 days for a snapshot. + +#### Scenario: T5 oversize value +- **WHEN** a `TieredMapping` stores a value whose encoded form is 1 MiB and one byte, and then a value of 1 KiB +- **THEN** no command carries the first value, a read in the same process returns it from the in-process tier, the shared tier holds the second value, and each key on the `valkey_server` fake has a TTL above 0 + +### Requirement: A value of another kind or schema is a miss +A reader SHALL treat a shared value under an older key version, or with another schema key, as a miss, SHALL read the source, and SHALL write the value under the current key. + +#### Scenario: T6 old kind +- **WHEN** the shared tier holds a PyPI fact under an older key version and a fact under the current key with another schema key +- **THEN** each read returns the value of the source, and the shared tier then holds the source value under the current key with the current schema key + +### Requirement: No key of a private repository +The snapshot store SHALL write no key of a repository that the visibility check does not give as public, SHALL NOT use a shared copy of it, and SHALL count `result="private"`. A failed visibility read SHALL count as private. When the shared tier holds a copy of a repository that the check does not give as public, the store SHALL remove the key and count `devops_cli_brain_writes_total{result="removed"}`. + +#### Scenario: Private repository +- **WHEN** a listing round runs for a repository whose visibility read gives `isPrivate: true`, and a second round runs for a repository whose visibility read fails +- **THEN** the `valkey_server` fake holds no key that names either repository, each round reads the local file or GitHub, and `devops_cli_brain_writes_total{store="snapshot",result="private"}` rises by two + +#### Scenario: No visibility read without the shared tier +- **WHEN** the `valkey_server` fake has `connected = False` and a listing round runs +- **THEN** the round sends no visibility read to GitHub + +#### Scenario: A repository that became private +- **WHEN** a round of a public repository writes its shared snapshot, and a round in a new process finds that the repository is not public +- **THEN** the `valkey_server` fake holds no key, the round uses no shared copy, and `devops_cli_brain_writes_total{result="removed"}` rises by one + +### Requirement: One key for each repository +The key of a shared snapshot and the visibility answer of a process SHALL use the casefolded name of `RepoRef.key`, so each spelling of a repository name gives one key and one visibility read. + +#### Scenario: Two spellings of one name +- **WHEN** a process saves the snapshot of `Dan-Petty/DevOps-CLI`, a new process loads `dan-petty/devops-cli`, and the visibility of both spellings is read +- **THEN** the fake holds one key, the load gives the saved records, and GitHub gets one visibility read + +### Requirement: A shared load has a budget +A load of a shared snapshot SHALL stop when it passes `DEFAULT_BRAIN_SNAPSHOT_LOAD_BUDGET_SECONDS` (20 s), SHALL count `devops_cli_valkey_cache_errors_total{op="hscan",error="budget"}`, and the reader SHALL take the local copy or read GitHub. + +#### Scenario: Slow shared tier +- **WHEN** the `clock` fixture moves 21 s during the second `HSCAN` of a shared load of 1,200 records +- **THEN** the load sends no third `HSCAN`, the reader returns the local snapshot, and the budget counter rises by one + +### Requirement: The tool facts come from the shared cache +A second read of the same PyPI package or the same deps.dev project within the TTL SHALL come from the shared or the in-process tier and SHALL send no request to PyPI or deps.dev. A failed source read SHALL keep nothing. + +#### Scenario: PyPI fact reuse across processes +- **WHEN** two `pypi_package` calls for `Scanner` and `scanner` run with an empty in-process tier between them on one `valkey_server` fake +- **THEN** the `web` fake receives one request to PyPI, and both calls return the same facts + +#### Scenario: deps.dev fact reuse +- **WHEN** two inventory reads link the packages of `github.com/example/tool` with an empty in-process tier between them +- **THEN** the `web` fake receives one request to deps.dev + +#### Scenario: A failed PyPI read +- **WHEN** PyPI answers 503 for a package, and then 200 +- **THEN** the first call answers the failure as text, and the second call sends a request and returns the facts + +### Requirement: The brain counters have bounded labels +The counters `devops_cli_brain_reads_total`, `devops_cli_brain_writes_total`, `devops_cli_valkey_cache_errors_total` and `devops_cli_brain_github_requests_saved_total` SHALL take each label value from a fixed set in the source, and SHALL NOT hold a repository name, a key, an issue number or a package name. + +#### Scenario: The labels of a round +- **WHEN** a test runs a listing round and two fact reads on the OTLP fake, one with the shared tier up and one with it down +- **THEN** each exported data point of the four counters has only the labels `store`, `result`, `op` or `error`, each value is one of the fixed values, and no value names the repository or the package + +### Requirement: The cache Valkey keeps its data bound below its limit +The valkey container of the Deployment `valkey-devops` SHALL start valkey-server with `--maxmemory 256mb` under a container memory limit of `384Mi`, so its data bound is two thirds of its limit. The live check after the Argo CD sync is the proof of the bound. The `k8s` row of `devops ci` proves only that the manifests render: it does not compare `--maxmemory` with the limit. + +#### Scenario: The manifests render +- **WHEN** a person runs `uv run devops ci --check --only k8s` on the pull request +- **THEN** the `k8s` row renders `k8s/llm` with no error + +#### Scenario: Live memory bound +- **WHEN** a person runs `kubectl -n llm get deployment valkey-devops -o jsonpath='{.spec.template.spec.containers[0].command}{.spec.template.spec.containers[0].resources.limits.memory}'` after the Argo CD sync, and reads `redis_config_maxmemory{job="valkey-devops"}` in Prometheus +- **THEN** the command holds `--maxmemory 256mb` and the limit is `384Mi`, and the metric is 268435456 diff --git a/openspec/specs/roadmap-intake-listing/spec.md b/openspec/specs/roadmap-intake-listing/spec.md index f876be92f0..295674a2e5 100644 --- a/openspec/specs/roadmap-intake-listing/spec.md +++ b/openspec/specs/roadmap-intake-listing/spec.md @@ -28,20 +28,24 @@ Intake MUST store as the next watermark the earlier of the start of the read and - **THEN** The snapshot stores 09:59:00 as its watermark ### Requirement: Full read -Intake SHALL read the whole listing and replace the snapshot when no snapshot is kept, when it cannot be read, when its schema key is not the key of the current `IssueRecord` schema, when its last full read is 24 hours old or older, and on `--full`. A snapshot that cannot be read SHALL give a warning that names its file. +Intake SHALL read the whole listing and replace the snapshot when neither the local file nor the shared tier of `valkey-devops` keeps a fit snapshot of the repository, and on `--full`. A snapshot is fit when it can be read, its schema key is the key of the current `IssueRecord` schema, and its last full read is younger than 24 hours. The shared tier keeps no snapshot of a private repository. A local snapshot file that cannot be read SHALL give a warning that names its file. #### Scenario: First run -- **WHEN** No snapshot is kept for the repository +- **WHEN** No snapshot is kept for the repository in the local file or in the shared tier - **THEN** The request holds no `since` parameter, and the run keeps a snapshot with every issue of the listing #### Scenario: The flag, another version or an old full read -- **WHEN** A snapshot is kept and the run has `--full`, or the snapshot holds the schema key of another version of `IssueRecord`, or its last full read is 25 hours old +- **WHEN** A snapshot is kept and the run has `--full`, or each kept snapshot holds the schema key of another version of `IssueRecord`, or the last full read of each kept snapshot is 25 hours old - **THEN** The request holds no `since` parameter, and the new snapshot replaces the old one #### Scenario: A snapshot that cannot be read -- **WHEN** The snapshot file holds no valid JSON +- **WHEN** The snapshot file holds no valid JSON, and the shared tier keeps no fit snapshot of the repository - **THEN** The run logs a warning that names the file, reads the whole listing and keeps a new snapshot +#### Scenario: A fit shared snapshot and no local file +- **WHEN** No local snapshot is kept, and the shared tier keeps a fit snapshot of the public repository +- **THEN** The run sends the listing requests with `since=` of the shared snapshot, and keeps a local snapshot with every issue + ### Requirement: Sub-issue count When a changed issue joined or left a parent that the read did not return, intake SHALL move the sub-issue count of that parent by one. @@ -71,7 +75,7 @@ The file store SHALL refuse a repository name that holds a `..` segment. - **THEN** The store raises `SecurityError` ### Requirement: The Service reads through the snapshot -The rounds of the lane that holds `intake` and the scoped intake of each delivery SHALL read every issue through the snapshot that the Service keeps in `listing` of its state directory. Each other lane SHALL read every issue through its own snapshot in `listing-` of the state directory. +The rounds of the lane that holds `intake` and the scoped intake of each delivery SHALL read every issue through the snapshot that the Service keeps in `listing` of its state directory. Each other lane SHALL read every issue through its own snapshot in `listing-` of the state directory. Each of these snapshot files SHALL sit under the shared tier of `valkey-devops`, and a read SHALL start from the fit copy with the newer watermark of the two. #### Scenario: A scoped intake with a kept snapshot - **WHEN** The Service keeps a snapshot of 250 items, and a delivery says that issue 251 opened @@ -79,12 +83,16 @@ The rounds of the lane that holds `intake` and the scoped intake of each deliver #### Scenario: The store of each lane - **WHEN** The lanes `metrics`, `intake` and `refine` each open their store for a poll -- **THEN** The store of `metrics` reads through the snapshot in `listing-metrics`, the store of `intake` through the snapshot in `listing`, and the store of `refine` through the snapshot in `listing-refine` +- **THEN** The store of `metrics` reads through the snapshot in `listing-metrics`, the store of `intake` through the snapshot in `listing`, and the store of `refine` through the snapshot in `listing-refine`, each under the shared tier #### Scenario: A status round with a kept snapshot - **WHEN** The lane `stage_ready` ran one round, and a second round is due - **THEN** The second round sends one listing request, with `since=` +#### Scenario: The newer copy of the two tiers +- **WHEN** The snapshot file of a lane has the watermark 09:00, and the shared tier keeps a fit snapshot of the public repository with the watermark 10:00 +- **THEN** The round sends the listing request with `since=` the watermark 10:00 + ### Requirement: Schema key of the snapshot The snapshot SHALL hold as its schema key the first 16 hex characters of the sha256 of the JSON schema of `IssueRecord`, and not the version of devops-cli.