diff --git a/changelog.d/1361.md b/changelog.d/1361.md new file mode 100644 index 0000000000..df41b991d9 --- /dev/null +++ b/changelog.d/1361.md @@ -0,0 +1,11 @@ +### Fixed +- The roadmap store writes a board field by the card's node id and reads only that card first, so a job-record mark costs about 3 GraphQL points instead of about 215, and filing and placing a critical fix a small constant (about 17 in the tests' fake GitHub, which leaves out the few queries gh makes to resolve an add) instead of about 1,500, whatever the board's size. It no longer sends `gh project field-list` or an `item-edit` that names a card by URL or a field by name, each of which reads the board's first 100 items with every field value, and no longer re-reads the whole board before each write (#1361). +- Intake writes to the card `gh project item-add` returns, so a placement no longer fails with "#N is not on the board after intake added it" while GitHub's board listing has not shown the new card yet (#1361). +- A store reads the board's fields once, and each filter's board listing once, for its life, one command or one Service round, and its own writes keep that listing current: a reprioritize run reads the board once instead of twice, and a Service round reads it once however many changes its triggers look up. Closing an issue drops the listing, because the board's own "Item closed" workflow then sets the card's Status, so a release cut rendered in the same round shows Done (#1361). +- A roadmap job's board write stops with `RoadmapCardChangedError` before any edit when someone changed that field after the job's store read the board, unless the card already holds the value the job writes, so a job never reverts a person's change it did not see; the job fails and the next round plans with the change (#1361). +- A Service round whose new events are all its own reads no board: the store drops them before it attaches job records (#1361). +- A board write still refuses before it starts while fewer than the 250 reserved GraphQL points are left, now read from its card read's `rateLimit` (#1361). + +### Changed +- `RoadmapStore.add_item` returns the Item it added, `Item` and `BoardEntry` carry the card's node id (`card_id`), and `changes_since` takes `except_actor`, an empty one leaving out nothing. The run record card is written by the id `gh project item-create --format json` returns, with no board read after the create (#1361). +- The `--dry-run` request plans list each board write's card read and its `item-edit` by node ids, and the board's fields and each filter's listing once a run; intake's placement lists no board read after its add (#1361). diff --git a/docs/ERRORS.md b/docs/ERRORS.md index f306386d1d..4cb2385fc0 100644 --- a/docs/ERRORS.md +++ b/docs/ERRORS.md @@ -92,6 +92,7 @@ names the class each row describes. One code never maps to two exit statuses. | `PoolLoadError` | `DEVOPS_CLI_ERROR` | `1` | Devops_cli.ai.pool_load | Prometheus could not answer a pool load query. | | `QdrantClientError` | `DEVOPS_CLI_ERROR` | `1` | Devops_cli.ai.rag.qdrant | Raised when an interaction with Qdrant fails. | | `ReviewPoolError` | `REVIEW_POOL_ERROR` | `1` | Ai | Raised when an error occurs during parallel review worker pool execution. | +| `RoadmapCardChangedError` | `ROADMAP_CARD_CHANGED` | `1` | Roadmap | Raised before a job's board write that would revert a change made since it read the card. | | `RoadmapRunError` | `DEVOPS_CLI_ERROR` | `1` | Roadmap | Raised when one or more roadmap jobs fail during execution. | | `RunCancelled` | `RUN_CANCELLED` | `26` | Ai | Raised when an agent run was cancelled by the application or timeout. | | `RunIndexNotConfiguredError` | `DEVOPS_CLI_ERROR` | `1` | Devops_cli.ai.run_store | No shared run index is configured. | diff --git a/docs/agent/tasks/task-1361-board-writes-by-node-id.md b/docs/agent/tasks/task-1361-board-writes-by-node-id.md new file mode 100644 index 0000000000..dc6e23eb51 --- /dev/null +++ b/docs/agent/tasks/task-1361-board-writes-by-node-id.md @@ -0,0 +1,72 @@ +# Task: Board writes go to the card by node id and read only that card (#1361) + +**Issue**: [#1361](https://github.com/dan-petty/devops-cli/issues/1361) +**Status**: Done +**Milestone**: v0.2.29 +**Priority**: priority/p1-high +**Scope**: type/bug, scope/github, priority/p1-high + +## Description + +The roadmap store wrote board fields by name and re-read the whole board around every write. `gh project field-list` and a name-addressed `gh project item-edit` each read the board's first 100 items with every field value (about 101 GraphQL points), and `_require_entry` re-read the whole board, so one `set_field` cost about 320 points and one intake placement about 1,300. The Service spent the machine account's hourly GraphQL budget by itself twice on 2026-10-07/08. Intake also read its card back from the board listing right after `gh project item-add`, which can lag the add by up to two minutes, so three placements failed with "#N is not on the board after intake added it". + +- **Card identity.** `RoadmapStore.add_item` returns the `Item` it added: the card id comes from `gh project item-add --format json` (GitHub answers with the existing card for an issue already on the board), and its fields from one `RoadmapBoardCard` read of that id. `Item` and `BoardEntry` carry `card_id`, from the add or from the listing. Intake's placement writes to `subject.item` or the returned `Item`; it never calls `store.item()`, and the read-back error is gone. +- **Writes by node id.** `set_field`, `set_marks`, `set_card_field` and `set_run_record` write through `card_edit_args` (`--id`, `--project-id`, `--field-id`, and an option's id or `--text` or `--clear`). The board's node id and fields come from the GraphQL fields query (it now selects the board's `id`), read once per store. `_read_board_options`, `_edit_board_field`, `_require_existing_board` and `_require_card` are deleted. `item-add --url` stays: it has no id form. +- **One card read before a write.** `_require_entry` reads the card by node id (`RoadmapBoardCard`: `node(id:) { ... on ProjectV2Item { isArchived ...the page's item fields } }` with `rateLimit`, about one point). The record a write sends joins the record the card holds then (ADR 0002). A card that is gone (GitHub's `NOT_FOUND`, which `gh` reports by exiting 1 with the answer on stdout), archived, or another issue's raises "#N is not on the board" before any write. `require_write_floor` refuses the write while that read reports fewer than the 250-point reserve. +- **A change since the read stops the write.** Before `set_field` writes a board field, and before `set_card_field` writes any, the store compares the field on the card it just read with the value it read: the card's copy in its listings, which its own writes keep current, or the caller's `Item` or `Card` when no listing holds the card. When they differ and the card does not already hold the value being written, it raises `RoadmapCardChangedError` ("#N's Field is X on the board but was Y when this run read it…") before any edit, so a job never reverts a person's change it did not see (ADR 0002); the job fails and the next round plans with a fresh store. The card read takes only the job record into the listings, so a change seen while writing one field still stops a later write of another. Both adapters keep this contract through `store.require_unchanged`. +- **No listing after a write.** The run record card is written by the id `gh project item-create --format json` returns, with nothing read after the create. `remove_card` and `set_card_field` read their card by node id. +- **One listing per filter per store.** The store reads the board listing the first time it needs a filter and keeps it for its life (one command or one Service round). `items`, `item`, `backlog`, `candidates`, `cards`, the job records `changes_since` attaches, the run record lookup and the cross-job checks in `run.py` share it. Its own writes keep it current: each edit updates the card with the value sent, a card it adds joins the unfiltered listing and, when its issue is open, the open items' (`is:open`) listing, and any other filtered listing, which it can't judge, is read again when next needed. A close (`close_issue`, `close_as_duplicate`) drops every listing, because the board's own "Item closed" workflow then sets the card's Status to Done, so a cut rendered in the same round shows Done. Nothing else is cached; the next store reads afresh (ADR 0003). +- **The Service's own events cost no board read.** `changes_since(since, except_actor=...)` drops the actor's changes before it attaches job records; `run.py` passes the session's login. An empty actor leaves out nothing. +- **Request plans.** `StoreRequests` lists each write's card read and id-addressed edit, the fields read and each filter's listing under "the run has not read … since it began or last closed an issue", `add_item`'s `item-add --format json` and card read, no `board_read` after the run record's create, and the card read before `set_card_field` and `remove_card`. Intake's placement drops its `item` step. `--dry-run` still sends no request. + +## Acceptance Criteria + +- [x] `add_item` returns the card it added, with its fields from one node read; both adapters and the protocol change together, and adding an issue already on the board returns its existing card (`test_add_item_adds_the_issue_by_its_url_and_returns_the_card_it_added`, `test_adding_an_issue_already_on_the_board_returns_its_existing_card`, `test_adding_an_item_returns_it_with_its_card_and_adding_it_again_keeps_that_card`). +- [x] `Item` and `BoardEntry` carry the card's node id, from the add or from the listing (`test_two_writes_from_one_read_keep_both_fields_in_the_job_record`). +- [x] `_apply_placement` writes to the card it already has and never calls `store.item()`; the "is not on the board after intake added it" error is deleted. +- [x] Board writes go by node id with field and option ids from the fields query read once per store; no argv the store sends contains `field-list`, and every `item-edit` uses `--id`, `--project-id` and `--field-id` (`test_a_value_write_sends_one_card_read_and_two_id_addressed_edits_and_no_board_read`, `test_no_roadmap_plan_lists_a_board_command_gh_resolves_by_reading_the_board_first`). +- [x] A write reads only the card it writes, joins the record the card holds then, raises "#N is not on the board" for a gone or archived card, and refuses below the reserve (`test_a_write_to_a_card_another_process_archived_raises_before_any_edit`, `test_a_mark_another_process_wrote_after_the_listing_was_read_is_kept`, `test_writing_an_item_that_is_not_on_the_board_raises_without_writing`, `test_a_write_refuses_before_it_starts_while_the_points_left_are_below_the_reserve`). +- [x] No path that writes one card reads the listing after it: the run record card is written by the id `item-create` returns, and `_require_card` reads by node id (`test_set_run_record_creates_its_card_once_then_edits_its_job_record_by_node_id`, `test_remove_card_reads_the_card_then_deletes_it_by_id`). +- [x] One board read per filter per store, kept current by the store's own writes (`test_the_store_reads_the_board_once_and_its_own_writes_keep_that_listing_current`, `test_an_added_card_joins_the_listing_the_store_already_read`, `test_each_read_passes_its_filter_at_the_source`, `test_a_reprioritize_run_on_a_board_of_931_items_charges_its_pages`). +- [x] A job's write of a field someone changed since its store read the card raises `RoadmapCardChangedError` before any edit, in both adapters, for `set_field` and `set_card_field`; a write of the value the card already holds goes ahead, and a revert then a decision on one field from one read both go ahead (`test_a_field_a_person_changed_after_the_listing_was_read_raises_before_any_edit`, `test_a_persons_change_stays_caught_after_the_store_wrote_another_field_of_its_card`, `test_a_write_of_the_value_the_card_holds_now_goes_ahead`, `test_the_stores_own_write_is_the_value_its_next_write_of_that_field_compares`, `test_a_card_field_a_person_changed_after_the_listing_was_read_raises_before_any_edit`, and their in-memory counterparts in `tests/test_roadmap_store_contract.py`). +- [x] A close drops the store's listings, so a render after it in the same store shows the Status the board's workflow set (`test_a_render_after_a_close_in_the_same_store_shows_the_status_the_board_set`, for `close_issue` and `close_as_duplicate`). +- [x] A card intake adds joins the open items' listing it read for its candidates, with no re-read that GitHub's lag could miss it in (`test_an_added_open_card_joins_the_open_items_listing_without_a_read`). +- [x] The Service's own events cost no board read, and an empty actor leaves out nothing (`test_changes_since_drops_an_actors_own_changes_before_it_reads_the_board`, `test_changes_since_leaves_out_the_changes_one_actor_made`, `test_changes_since_with_an_empty_actor_leaves_out_nothing` in both suites). +- [x] The dry-run request plan matches the new requests and sends none (`test_a_board_write_plans_its_card_read_and_an_edit_by_node_ids`, `test_the_run_record_card_a_run_creates_is_written_with_no_read_after_its_create`, `test_intakes_placement_plans_no_board_read_after_its_add`, `test_a_reprioritize_runs_gh_argv_sequence_is_its_plan`, `test_a_render_runs_gh_argv_sequence_is_its_plan`, `test_every_jobs_dry_run_makes_no_request_and_lists_the_requests_a_run_makes`). +- [x] Store tests: one `set_field` on Value sends one card read and two id-addressed edits; `set_field(Release)` one card read, one edit and one REST milestone write; an archived card raises before any edit; another process's mark is kept. +- [x] Intake tests on `GitHubFake` at the `gh` process edge: the observed lag (the listing leaves the new card out of three reads; after `item-add` no board listing query, six card reads; the same test fails on the code before this change with the read-back error), #1336's state (only Effort and Priority, no listing query), and one listing for three placements on a 250-card board (`test_intake_writes_to_the_card_it_added_while_the_board_listing_leaves_it_out`, `test_an_item_on_the_board_with_status_and_value_gets_only_effort_and_priority`, `test_an_intake_of_three_placements_reads_the_board_once`). +- [x] GraphQL point estimates are constants, not proportional to the board: filing and placing a critical fix into the release costs a small constant on boards of 120 and 1,080 cards (about 17 in `GitHubFake`, which charges `item-add` as one mutation though gh first resolves the owner, board and issue with queries of its own), and a job-record mark 3 (`test_a_placement_costs_the_same_few_graphql_points_whatever_the_boards_size`, `test_a_job_record_mark_costs_three_graphql_points_whatever_the_boards_size`). +- [x] Run tests: 50 foreign label changes, none in the current release, send one board read; a poll whose events are all the Service's own sends no GraphQL request (`test_a_round_judging_50_foreign_label_changes_reads_the_board_once`, `test_a_poll_whose_changes_are_all_the_services_own_sends_no_graphql_request`). +- [x] No test reaches the network: fakes sit at the store's `runner` seam; the run tests also fix the session login. Each new test's call phase is under 1 s; the slowest, `test_a_placement_costs_the_same_few_graphql_points_whatever_the_boards_size[1080]`, took 0.07 s (`--durations`, run serially). +- [x] `changelog.d/1361.md` records the fix; `CHANGELOG.md` and `docs/ROADMAP.md` are untouched. +- The worker pause until the GraphQL reset (the reset time in `require_budget`'s and `require_floor`'s details, `ServiceManager` holding every repository's rounds, the `tests/test_server_service.py` cases) and the spend line at the end of each Service round: split out to #1400, as the issue's "One pull request?" question provides. +- Pending a person, after the Service runs a release image with this fix: for the next five issues it places, `gh api graphql -f query='query { repository(owner: "dan-petty", name: "devops-cli") { issue(number: ) { projectItems(first: 5) { nodes { createdAt fieldValueByName(name: "Priority") { ... on ProjectV2ItemFieldSingleSelectValue { updatedAt } } } } } } }'` shows `createdAt` and the Priority's `updatedAt` less than 90 s apart. +- Pending a person: `{namespace="devops", container="service"} |= "changed while they were read"` shows no line inside those five placements, and `sum(count_over_time({namespace="devops", container="service"} |= "GitHubRateLimitError" |= "GraphQL has" [24h]))` is 0 on a day with at least 20 placements. +- Pending a person: #1303, #1336, #1348 and #1352 each have a Priority, or were closed as duplicates. +- Pending a person, over the first day on that image: each `{namespace="devops", container="service"} |= "when this run read it"` line names a field a person or a board workflow changed after that round read the board, and the next round's write of that card succeeds. + +## Decisions and deviations + +- **`field_list_args`, `item_edit_args` and `FieldListingPayload` stay**, unused by the store: `gh project reconcile` reads and writes through them since #892 merged, and the issue leaves that path to #892 and #999. Their docstrings say what they cost and that the store sends neither. +- **The reserve check for a write** is `require_write_floor`, beside `require_floor`: it reads the card read's `rateLimit` and refuses while fewer than the 250 reserved points are left, with a message about the write. `require_budget` prices a read about to happen, so its message would misdescribe a write. +- **The board's node id** comes from the fields query (which now selects it), so `set_card_field` and `set_run_record` no longer read `gh project list` before writing; a board that does not exist fails the fields read. +- **The run record card is still found by its title in the listing**, the store's one listing for the run, which reprioritize has already read for `run_record()`; the write then reads that card by node id. +- **`item(number)` keeps the shared listing**, as the issue proposes: no write path calls it, and after the store's first read it costs no GraphQL point. +- **A card the store adds** joins the unfiltered listing, which selects every card not archived, and the `is:open` listing when its issue is open, so intake's backlog and candidates hold it without a re-read GitHub's lag could leave it out of; a listing that already holds the card keeps its copy, and any other filtered listing is dropped and read again when next needed, because the store can't evaluate a Projects filter. +- **"Changed since it was read" compares the listing copy, not the `item` argument**, so a reprioritize apply that reverts a field and then writes its decision to it, both from one planned `Item`, compares the second write with the first. The caller's value is the baseline only for a card no listing of the store holds. A write of the value the card already holds is not a revert and goes ahead: the board's own "Item added" workflow sets Status New on a card intake adds, and intake writes the same New. The card read before a write takes only the job record into the listings; taking the whole card, as before, would have hidden a person's change to one field behind a write to another. +- **The Release is not compared:** it is the issue's milestone, written over REST, and the card read does not carry it. +- **A close drops every listing** rather than patching the closed card: the Status the board's workflow sets is GitHub's, and only a read shows it. +- **The worker pause and the per-round spend line** are split out to #1400, as the issue's "One pull request?" question allows: the store changes are the fix, and they end the budget exhaustion at its source. +- **An unchanged poll** still reads the board once, about 12 points on board #2. Skipping that read is #1401. + +## Deliverables + +- [x] `src/devops_cli/roadmap/github_store.py`: card ids, the one-card read, writes by node ids, the per-store fields and listings kept current by the store's writes and dropped by a close, the "changed since it was read" check, `add_item` returning its `Item`, the run record card written by the id its create returns, `changes_since(except_actor=)`. +- [x] `src/devops_cli/roadmap/board_read.py`: `RoadmapBoardCard` (`BOARD_CARD_QUERY`, `board_card_args`, `BoardCardPayload`) sharing the page's item selection, and `require_write_floor`. +- [x] `src/devops_cli/roadmap/store.py` and `src/devops_cli/roadmap/memory_store.py`: `Item.card_id`, `BoardEntry.card_id`, `add_item -> Item`, `changes_since(except_actor=)`, `require_unchanged` and each in-memory view's copy of the cards it read, the module contract on what a store keeps. +- [x] `src/devops_cli/exceptions/roadmap.py`, `src/devops_cli/config/constants.py`, `docs/ERRORS.md`: `RoadmapCardChangedError` with `CONST_ERROR_CODE_ROADMAP_CARD_CHANGED`, and its row in the error catalog. +- [x] `src/devops_cli/roadmap/intake.py`, `src/devops_cli/roadmap/run.py`: placement writes to the card it has; the session's own events are dropped in the store. +- [x] `src/devops_cli/roadmap/request_plan.py`, `src/devops_cli/roadmap/intake_requests.py`, `src/devops_cli/lang/en/messages.py`: the plans and their texts. +- [x] Tests: `tests/roadmap_board_fake.py` (`BoardServer` card reads and lag, `GitHubFake` with closes and the board's "Item closed" workflow), `tests/fixtures/roadmap/github-schema-board.graphql`, `tests/test_roadmap_github_store.py`, `tests/test_roadmap_intake.py`, `tests/test_roadmap_run.py`, `tests/test_roadmap_dry_runs.py`, `tests/test_roadmap_store_contract.py`, `tests/test_roadmap_board_read.py`. +- [x] Changelog fragment: `changelog.d/1361.md`. +- The worker pause and the per-round spend line: moved to #1400. diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index b9b850184c..3f0fb050d2 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -1115,6 +1115,7 @@ CONST_ERROR_CODE_TELEMETRY = "TELEMETRY_ERROR" CONST_ERROR_CODE_LOGFIRE = "LOGFIRE_CONFIG_ERROR" CONST_ERROR_CODE_SERVICE_STATUS = "SERVICE_STATUS_ERROR" +CONST_ERROR_CODE_ROADMAP_CARD_CHANGED = "ROADMAP_CARD_CHANGED" CONST_ERROR_CODE_LIBRARY_INGESTION = "LIBRARY_INGESTION_ERROR" CONST_ERROR_CODE_LIBRARY_NOT_FOUND = "LIBRARY_NOT_FOUND_ERROR" CONST_ERROR_CODE_DOCS_INGESTION = "DOCS_INGESTION_ERROR" diff --git a/src/devops_cli/exceptions/__init__.py b/src/devops_cli/exceptions/__init__.py index 3bff47b158..22322e5c2f 100644 --- a/src/devops_cli/exceptions/__init__.py +++ b/src/devops_cli/exceptions/__init__.py @@ -39,7 +39,7 @@ KubernetesError, KubernetesLoggingError, ) -from devops_cli.exceptions.roadmap import RoadmapRunError +from devops_cli.exceptions.roadmap import RoadmapCardChangedError, RoadmapRunError from devops_cli.exceptions.sandbox import ( SandboxError, SandboxNotFoundError, @@ -123,6 +123,7 @@ "KubernetesError", "KubernetesLoggingError", "LogfireConfigurationError", + "RoadmapCardChangedError", "RoadmapRunError", "SSRFBlockedError", "SandboxError", diff --git a/src/devops_cli/exceptions/roadmap.py b/src/devops_cli/exceptions/roadmap.py index e74cb89f91..aa85e4bb3b 100644 --- a/src/devops_cli/exceptions/roadmap.py +++ b/src/devops_cli/exceptions/roadmap.py @@ -5,7 +5,9 @@ from collections.abc import Sequence from typing import Any +from devops_cli.config.constants import CONST_ERROR_CODE_ROADMAP_CARD_CHANGED from devops_cli.exceptions.base import DevOpsCLIError +from devops_cli.exceptions.git import GitHubOperationError class RoadmapRunError(DevOpsCLIError): @@ -24,3 +26,25 @@ def __init__( if failed_jobs and "failed_jobs" not in extra: extra["failed_jobs"] = list(failed_jobs) super().__init__(message, details=extra, **kwargs) + + +class RoadmapCardChangedError(GitHubOperationError): + """Raised before a job's board write that would revert a change made since it read the card. + + The job planned without that change, so writing would revert it (ADR 0002). Nothing is + written; the next run reads the board again and plans with the change. + """ + + def __init__( + self, + message: str, + *, + operation: str = "roadmap.item.set_field", + details: dict[str, Any] | None = None, + ) -> None: + super().__init__( + message, + operation=operation, + error_code=CONST_ERROR_CODE_ROADMAP_CARD_CHANGED, + details=details, + ) diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index a98403eb94..fa5d699bdc 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -1112,6 +1112,16 @@ class RoadmapMessages: "GraphQL has {remaining} points left until {reset}, below the {floor} kept in reserve, " "so the read of {what} stopped before page {page}. Run it again after {reset}." ) + graphql_budget_write_floor: str = ( + "GraphQL has {remaining} points left until {reset}, below the {floor} kept in reserve, " + "so the run stopped before writing {what}. Run it again after {reset}." + ) + card_changed: str = ( + "{card}'s {field} is {now} on the board but was {read} when this run read it, so " + "someone changed it since and the run stopped before writing it. Nothing was written; " + "the next run reads the board again and plans with that change." + ) + card_value_unset: str = "unset" board_count_changed: str = ( "The {what} changed while they were read ({counts}), and again on a second read, so " "the read is incomplete. Run it again once the board is still." @@ -1366,8 +1376,12 @@ class RoadmapMessages: ), "board_first": "the first page of board {board}'s items{matching}", "board_page": "the next page of board {board}'s items{matching}", - "fields": "board {board}'s fields, with their options", - "field_options": "board {board}'s field options", + "fields": "board {board}'s node id and fields, with their options", + "card": ( + "the card of {subject}: its fields, its job record and GraphQL's points left; a " + "write stops here when the points are below the reserve, or when someone changed " + "the field it writes since the run read it" + ), "workflows": "board {board}'s workflows", "boards": "{owner}'s boards, to find board {board}", "default_branch": "the default branch and its head", @@ -1431,6 +1445,12 @@ class RoadmapMessages: "posted": "the change posts a comment", "record": "the run records its release or size", "no_card": "the board has no run record card yet", + "run_card": "the board has the run record card", + "board_unread": ( + "the run has not read these items of the board since it began or last closed an " + "issue" + ), + "fields_unread": "the run has not read the board's fields yet", "closing": "a shipped release's milestone is still open", "release_named": "the value is a Release", "board": "the configured board exists", @@ -1703,20 +1723,20 @@ class RoadmapMessages: "label {subject} with its type/* label when it has none, and budget/borrowed " "when it borrows" ), - "add": "read {subject}, then add it to board {board}", - "item": "board {board} and {subject}, to find its item", + "add": "read {subject}, add it to board {board}, then read the card the add names", "release": ( - "set the milestone of {subject} to : the board's fields and " - "items, every milestone, the job record (GraphQL), then the milestone (REST)" + "set the milestone of {subject} to : the board's fields once a " + "run, every milestone, its card, the job record (GraphQL), then the milestone " + "(REST)" ), "field": ( - "set {field} on {subject}: the board's fields and items, the job record, then " - "the field" + "set {field} on {subject}: the board's fields once a run, its card, the job " + "record, then the field" ), "comment": "the reason comment on {subject}", "priority": ( - "set Priority on {subject}: the board's fields and " - "items, the job record, then the field" + "set Priority on {subject}: the board's fields once a " + "run, its card, the job record, then the field" ), "duplicate_read": "{subject} and ", "duplicate_comment": "the duplicate comment on {subject}", diff --git a/src/devops_cli/roadmap/board_read.py b/src/devops_cli/roadmap/board_read.py index 28c44fc6ad..01f79ce9ce 100644 --- a/src/devops_cli/roadmap/board_read.py +++ b/src/devops_cli/roadmap/board_read.py @@ -12,7 +12,12 @@ Before the pages, one small query (`RoadmapBoardBudget`) reads the points left and the filter's total; a read that would leave fewer than `DEFAULT_GH_GRAPHQL_BUDGET_FLOOR` points refuses there, having spent nothing on pages, and a read stops before any page while fewer than the floor are -left. The documents are fixed templates, validated against GitHub's public schema in a test. +left. + +A write reads only the card it writes (#1361): `RoadmapBoardCard` reads one item by its node id, +with the same item fields a page holds and `rateLimit`, for about one point whatever the board's +size, and a write refuses before it starts while fewer than the floor are left. The documents are +fixed templates, validated against GitHub's public schema in a test. This module only builds `gh` arguments and reads payloads; the store runs them, so a request plan can list the same argv the store sends. @@ -36,6 +41,7 @@ BOARD_ITEMS_OPERATION = "RoadmapBoardItems" BOARD_BUDGET_OPERATION = "RoadmapBoardBudget" +BOARD_CARD_OPERATION = "RoadmapBoardCard" GRAPHQL_BUDGET_OPERATION = "RoadmapGraphQLBudget" _RATE_LIMIT = "rateLimit { cost limit remaining used resetAt }" @@ -46,6 +52,16 @@ ) _FIELD_NAME = "field { ... on ProjectV2FieldCommon { name } }" _REPOSITORY_CONTENT = "number title url repository { nameWithOwner }" +# The item fields the store keeps, the same in a page and in a one-card read. +_ITEM_SELECTION = ( + "id content { __typename ... on DraftIssue { title } " + f"... on Issue {{ {_REPOSITORY_CONTENT} }} " + f"... on PullRequest {{ {_REPOSITORY_CONTENT} }} }} " + "fieldValues(first: $fieldValues) { nodes { " + f"... on ProjectV2ItemFieldSingleSelectValue {{ name {_FIELD_NAME} }} " + f"... on ProjectV2ItemFieldTextValue {{ text {_FIELD_NAME} }} " + f"... on ProjectV2ItemFieldDateValue {{ date {_FIELD_NAME} }} }} }}" +) BOARD_ITEMS_QUERY = ( f"query {BOARD_ITEMS_OPERATION}($owner: String!, $number: Int!, $filter: String!, " @@ -53,19 +69,18 @@ f"{_RATE_LIMIT} " + _OWNED_BOARD.format( selection=_ITEMS.format(first="$first", after="after: $after, ") - + " { totalCount pageInfo { hasNextPage endCursor } nodes { id " - "content { __typename ... on DraftIssue { title } " - f"... on Issue {{ {_REPOSITORY_CONTENT} }} " - f"... on PullRequest {{ {_REPOSITORY_CONTENT} }} }} " - "fieldValues(first: $fieldValues) { nodes { " - f"... on ProjectV2ItemFieldSingleSelectValue {{ name {_FIELD_NAME} }} " - f"... on ProjectV2ItemFieldTextValue {{ text {_FIELD_NAME} }} " - f"... on ProjectV2ItemFieldDateValue {{ date {_FIELD_NAME} }} }} }} }} }}" + + f" {{ totalCount pageInfo {{ hasNextPage endCursor }} nodes {{ {_ITEM_SELECTION} }} }}" ) + " }" ) """One page of the board's items that `$filter` selects, archived ones left out.""" +BOARD_CARD_QUERY = ( + f"query {BOARD_CARD_OPERATION}($id: ID!, $fieldValues: Int!) {{ {_RATE_LIMIT} " + f"node(id: $id) {{ ... on ProjectV2Item {{ isArchived {_ITEM_SELECTION} }} }} }}" +) +"""One board item by its node id, archived or not, with the fields a page holds.""" + BOARD_BUDGET_QUERY = ( f"query {BOARD_BUDGET_OPERATION}($owner: String!, $number: Int!, $filter: String!) {{ " f"{_RATE_LIMIT} " @@ -121,6 +136,15 @@ def board_budget_args(owner: str, number: int | str, board_filter: str) -> list[ ) +def board_card_args(card_id: str) -> list[str]: + """The `gh` arguments of the read of one board item by its node id.""" + return _graphql_args( + BOARD_CARD_QUERY, + ("id", card_id), + typed=("-F", f"fieldValues={DEFAULT_GH_PROJECT_FIELD_LIMIT}"), + ) + + def graphql_budget_args() -> list[str]: """The `gh` arguments of the query that reads the GraphQL points left.""" return _graphql_args(GRAPHQL_BUDGET_QUERY) @@ -211,6 +235,35 @@ class GraphQLBudgetPayload(BaseModel): rate_limit: GraphQLBudget = Field(validation_alias=AliasPath("data", "rateLimit")) +class _GraphQLError(BaseModel): + type: str | None = None + + +class BoardCardPayload(BaseModel): + """The answer to `RoadmapBoardCard`. A node id that resolves to nothing comes back as a null + node with a `NOT_FOUND` error, which `gh` reports by exiting 1 with the answer on stdout.""" + + rate_limit: GraphQLBudget = Field(validation_alias=AliasPath("data", "rateLimit")) + node: dict[str, Any] | None = Field(default=None, validation_alias=AliasPath("data", "node")) + errors: list[_GraphQLError] = Field(default_factory=list) + + def is_gone(self) -> bool: + """Whether GitHub says the node does not exist, and says nothing else went wrong.""" + return ( + self.node is None + and bool(self.errors) + and all(error.type == "NOT_FOUND" for error in self.errors) + ) + + def listed(self) -> dict[str, Any] | None: + """The item shaped as `gh project item-list` lists it, or None when it is archived, gone + or not a board item.""" + node = self.node or {} + if "id" not in node or node.get("isArchived"): + return None + return listing_item(node) + + def listing_item(node: dict[str, Any]) -> dict[str, Any]: """A board item node in the shape `gh project item-list` gives it: content keyed `type`, `repository` as `owner/name`, and each field's value under its name, first letter @@ -258,6 +311,22 @@ def require_budget(budget: GraphQLBudget, cost: int, what: str) -> None: ) +def require_write_floor(budget: GraphQLBudget, what: str) -> None: + """Refuse a write, before it starts, while fewer points than the floor are left.""" + if budget.remaining < DEFAULT_GH_GRAPHQL_BUDGET_FLOOR: + raise GitHubRateLimitError( + MESSAGES.roadmap.graphql_budget_write_floor.format( + remaining=budget.remaining, + reset=utc_clock(budget.reset_at), + floor=DEFAULT_GH_GRAPHQL_BUDGET_FLOOR, + what=what, + ), + subcommand="graphql", + operation="roadmap.write", + details={"remaining": budget.remaining}, + ) + + def require_floor(budget: GraphQLBudget, what: str, page: int) -> None: """Stop a read before page `page` while fewer points than the floor are left.""" if budget.remaining < DEFAULT_GH_GRAPHQL_BUDGET_FLOOR: @@ -283,16 +352,20 @@ def utc_clock(moment: datetime) -> str: __all__ = [ "BOARD_BUDGET_OPERATION", "BOARD_BUDGET_QUERY", + "BOARD_CARD_OPERATION", + "BOARD_CARD_QUERY", "BOARD_ITEMS_OPERATION", "BOARD_ITEMS_QUERY", "GRAPHQL_BUDGET_OPERATION", "GRAPHQL_BUDGET_QUERY", "BoardBudgetPayload", + "BoardCardPayload", "BoardItemsPage", "GraphQLBudget", "GraphQLBudgetPayload", "GraphQLSpend", "board_budget_args", + "board_card_args", "board_items_args", "graphql_budget_args", "item_list_key", @@ -300,6 +373,7 @@ def utc_clock(moment: datetime) -> str: "read_cost", "require_budget", "require_floor", + "require_write_floor", "spend_between", "utc_clock", ] diff --git a/src/devops_cli/roadmap/github_store.py b/src/devops_cli/roadmap/github_store.py index 6e527d79fe..124224796e 100644 --- a/src/devops_cli/roadmap/github_store.py +++ b/src/devops_cli/roadmap/github_store.py @@ -1,26 +1,41 @@ """The GitHub roadmap store: Releases, Items and board fields read and written through `gh`. -Every command goes through an injected runner that defaults to `run_gh`, and no read is -cached. REST listings are read a full page at a time until a page is short, and each page must -be a JSON list: `run_gh`'s own paging (`api --paginate`) ends a listing at a page that is empty -or not JSON as if it were the last. The board comes from the store's own paged GraphQL query -(`board_read`): each read passes its job's Projects filter at the source, leaves archived items -out, checks the budget first and charges each page's reported points, and is checked against the -total for the same filter, so a short read is caught; a count that changes during the read is -read again once before the read fails. Issue events are read a page at a time, newest -first, so the read stops at the first event older than it needs. - -The board's own shape (its fields with their option ids, colors and descriptions, and its -workflows) comes from GraphQL, because `gh project field-list` gives no option colors or -descriptions. So do the default branch, pull requests with their last commit, and when an -Item's Status last changed, which is the Status value's `updatedAt`: the board's timelines hold -no status-change events (#768). A GraphQL connection is read in one request of up to its limit, -and one longer than that raises. New fields, and the options of a board just created, are -written with a GraphQL request on stdin. GitHub's option input takes no id, so the adapter never -sends an option list to a board that already has cards. A card is edited by its node ids, which -reach draft issues and other repositories' cards too. Issue events carry the Item's job record -from the board as it is when they are read. The run record card is the board's draft issue -titled `CONST_ROADMAP_RUN_RECORD_TITLE`, found by that title in the board listing. +Every command goes through an injected runner that defaults to `run_gh`. REST listings are read +a full page at a time until a page is short, and each page must be a JSON list: `run_gh`'s own +paging (`api --paginate`) ends a listing at a page that is empty or not JSON as if it were the +last. The board comes from the store's own paged GraphQL query (`board_read`): each read passes +a Projects filter at the source, leaves archived items out, checks the budget first and charges +each page's reported points, and is checked against the total for the same filter, so a short +read is caught; a count that changes during the read is read again once before the read fails. +Issue events are read a page at a time, newest first, so the read stops at the first event older +than it needs. + +The store reads the board listing once for each filter, and the board's fields once, and keeps +both for its life, one command or one Service round (#1361): every reader of a filter shares its +listing, and the store's own writes keep it current with the values they sent and the cards +they add. A close drops the listings, because the board's own workflow then changes the closed +issue's card. A write reads only the card it writes, by node id (`RoadmapBoardCard`, about one +point), so the job record it writes joins the one the card holds then, a card gone or archived +raises before any write, and the points that read reports below the reserve refuse the write. +A field someone changed since the store read the card raises `RoadmapCardChangedError` before +any write, unless the card already holds the value the write sends: the job planned without +that change, and ADR 0002 forbids reverting it, so the job fails and the next store plans again. +Every board write is `gh project item-edit` by node ids (`--id`, `--project-id`, `--field-id`, +and an option's id), which sends only the mutation; given a card's URL or a field's name, gh +first reads the board's first 100 items with all their field values, about 101 points. +`item-add` and `item-create` return the card they make (`--format json`), which the store writes +to without looking for it in a listing that can lag the add by minutes. + +The board's own shape (its node id, its fields with their option ids, colors and descriptions, +and its workflows) comes from GraphQL. So do the default branch, pull requests with their last +commit, and when an Item's Status last changed, which is the Status value's `updatedAt`: the +board's timelines hold no status-change events (#768). A GraphQL connection is read in one +request of up to its limit, and one longer than that raises. New fields, and the options of a +board just created, are written with a GraphQL request on stdin. GitHub's option input takes no +id, so the adapter never sends an option list to a board that already has cards. Issue events +carry the Item's job record from the board listing, and those of the actor a caller leaves out +read none. The run record card is the board's draft issue titled +`CONST_ROADMAP_RUN_RECORD_TITLE`, found by that title in the board listing. """ from __future__ import annotations @@ -69,17 +84,20 @@ from devops_cli.lang import MESSAGES from devops_cli.roadmap.board_read import ( BoardBudgetPayload, + BoardCardPayload, BoardItemsPage, GraphQLBudget, GraphQLBudgetPayload, GraphQLSpend, board_budget_args, + board_card_args, board_items_args, graphql_budget_args, item_list_key, read_cost, require_budget, require_floor, + require_write_floor, spend_between, ) from devops_cli.roadmap.store import ( @@ -126,6 +144,7 @@ require_new_release, require_option, require_release, + require_unchanged, select_candidates, with_marks, ) @@ -470,20 +489,20 @@ def is_run_record(self) -> bool: def values(self) -> dict[str, Any]: """The card's board fields and job record, keyed as `BoardEntry` and `Card` hold them.""" - extra = self.model_extra or {} - fields = { - f.name.lower(): _text_value(extra.get(item_list_key(f.value))) for f in BOARD_FIELDS - } + fields = {f.name.lower(): self.field_value(f.value) for f in BOARD_FIELDS} return fields | {"job_record": decode_job_record(self.job_record_text(), card=self.name())} + def field_value(self, field_name: str) -> str | None: + """The value the card holds for the board field `field_name`, None when it has none.""" + return _text_value((self.model_extra or {}).get(item_list_key(field_name))) + def name(self) -> str: """The card as an error names it: its issue's number, or its node id.""" return f"#{self.content_number}" if self.content_number else f"card {self.id}" def job_record_text(self) -> str | None: """The job record as the board's text field holds it.""" - extra = self.model_extra or {} - return _text_value(extra.get(item_list_key(CONST_GH_PROJECT_JOB_RECORD_FIELD))) + return self.field_value(CONST_GH_PROJECT_JOB_RECORD_FIELD) def recorded( self, @@ -499,8 +518,14 @@ def recorded( return encode_job_record(kept, over=held, card=self.name()) def entry(self) -> BoardEntry: - """The board's fields and job record for this issue.""" - return BoardEntry.model_validate(self.values() | {"number": self.content_number}) + """The board's fields and job record for this issue, with its card's node id.""" + return BoardEntry.model_validate( + self.values() | {"number": self.content_number, "card_id": self.id} + ) + + def written(self, field_name: str, value: str | None) -> _BoardItemPayload: + """The card as it is once the store has written `value` to the field `field_name`.""" + return self.model_copy(update={item_list_key(field_name): value}) def card(self) -> Card: """The card, whatever it holds.""" @@ -516,13 +541,20 @@ def card(self) -> Card: ) +class _AddedCardPayload(BaseModel): + """What `gh project item-add` or `item-create` prints with `--format json`: the card it made.""" + + id: str + + class _BoardFieldPayload(BaseModel): name: str options: list[_NamedPayload] = Field(default_factory=list) class FieldListingPayload(BaseModel): - """The reply to `field_list_args`: every board field, with its options by name.""" + """The reply to `field_list_args`: every board field, with its options by name. Project + reconcile reads it (#892); the store reads its fields through GraphQL instead.""" fields: list[_BoardFieldPayload] total_count: int = Field(alias="totalCount") @@ -577,11 +609,29 @@ class _FieldConnectionPayload(BaseModel): class _BoardFieldsPayload(BaseModel): + board_id: str = Field(validation_alias=AliasPath("data", "repositoryOwner", "projectV2", "id")) fields: _FieldConnectionPayload = Field( validation_alias=AliasPath("data", "repositoryOwner", "projectV2", "fields") ) +class _BoardSchema(BaseModel): + """The board's node id and its fields, which every write addresses by id.""" + + model_config = ConfigDict(frozen=True) + + board_id: str + fields: tuple[BoardField, ...] + + def options(self) -> dict[str, tuple[str, ...]]: + """Each field's option names by field name.""" + return field_options(self.fields) + + def field(self, name: str, operation: str) -> BoardField: + """The field named `name`, raising when the board has none.""" + return require_field(self.fields, name, operation) + + class _WorkflowConnectionPayload(BaseModel): nodes: list[Workflow] total_count: int = Field(alias="totalCount") @@ -608,7 +658,9 @@ class _UpdatedFieldPayload(BaseModel): _BOARD_BUDGET = TypeAdapter(BoardBudgetPayload) _GRAPHQL_BUDGET = TypeAdapter(GraphQLBudgetPayload) _BOARD_ITEMS = TypeAdapter(list[_BoardItemPayload]) -_FIELDS = TypeAdapter(FieldListingPayload) +_BOARD_ITEM = TypeAdapter(_BoardItemPayload) +_BOARD_CARD = TypeAdapter(BoardCardPayload) +_ADDED_CARD = TypeAdapter(_AddedCardPayload) _JOB_RECORD = TypeAdapter(JobRecord) # The job record keys this version reads; the others are a newer version's, kept as they are. _JOB_RECORD_KEYS = frozenset(key.value for key in (*ItemField, *JobMark, *RefineRecordKey)) @@ -644,7 +696,7 @@ class _UpdatedFieldPayload(BaseModel): "... on ProjectV2SingleSelectField { options { id name color description } }" ) _FIELDS_QUERY = _OWNED_BOARD.format( - selection=f"fields(first: $first) {{ totalCount nodes {{ {_FIELD_SELECTION} }} }}" + selection=f"id fields(first: $first) {{ totalCount nodes {{ {_FIELD_SELECTION} }} }}" ) _WORKFLOWS_QUERY = _OWNED_BOARD.format( selection="workflows(first: $first) { totalCount nodes { number name enabled } }" @@ -883,7 +935,8 @@ def board_query_args(query: str, owner: str, number: Number, first: int) -> list def board_fields_args(owner: str, number: Number) -> list[str]: - """The GraphQL read of board `number`'s fields, with each option's id, color and description.""" + """The GraphQL read of board `number`'s node id and fields, with each option's id, color and + description; it reads no item, so it costs about one point.""" return board_query_args(_FIELDS_QUERY, owner, number, DEFAULT_GH_PROJECT_FIELD_LIMIT) @@ -893,7 +946,9 @@ def board_workflows_args(owner: str, number: Number) -> list[str]: def field_list_args(owner: str, number: Number) -> list[str]: - """`gh project field-list`: every board field's options by name.""" + """`gh project field-list`: every board field's options by name. gh also reads the board's + first 100 items with every field value (about 101 points), so the store never sends it; + project reconcile does (#892).""" limit = str(DEFAULT_GH_PROJECT_FIELD_LIMIT) return [ "project", @@ -927,13 +982,17 @@ def field_delete_args(field_id: str) -> list[str]: def item_add_args(owner: str, number: Number, url: str) -> list[str]: - return ["project", "item-add", str(number), "--owner", owner, "--url", url] + """`gh project item-add` of the issue at `url`, printing the card it adds, or the card the + issue already has.""" + return ["project", "item-add", str(number), "--owner", owner, "--url", url, "--format", "json"] def item_edit_args( owner: str, number: Number, url: str, field_name: str, change: Sequence[str] ) -> list[str]: - """`gh project item-edit` on the issue at `url`, by the field's name.""" + """`gh project item-edit` on the issue at `url`, by the field's name. gh resolves both names + by reading the board's first 100 items with every field value (about 101 points), so the + store edits by node ids (`card_edit_args`); project reconcile sends this (#892).""" return [ "project", "item-edit", @@ -951,7 +1010,7 @@ def item_edit_args( def card_edit_args( card_id: str, project_id: str, field_id: str, change: Sequence[str] ) -> list[str]: - """`gh project item-edit` on any card, by node ids.""" + """`gh project item-edit` on any card, by node ids: gh sends only the mutation.""" return [ "project", "item-edit", @@ -966,7 +1025,7 @@ def card_edit_args( def run_record_card_args(owner: str, number: Number) -> list[str]: - """`gh project item-create`: the run record card, a draft issue.""" + """`gh project item-create`: the run record card, a draft issue, printing the card.""" return [ "project", "item-create", @@ -977,6 +1036,8 @@ def run_record_card_args(owner: str, number: Number) -> list[str]: CONST_ROADMAP_RUN_RECORD_TITLE, "--body", CONST_ROADMAP_RUN_RECORD_BODY, + "--format", + "json", ] @@ -1181,7 +1242,9 @@ def _releases_among(milestones: list[_MilestonePayload]) -> Iterator[Release]: class GitHubRoadmapStore(RoadmapStore): """The roadmap on GitHub, read and written as whoever `gh` is logged in as. - Without a board, Release operations work, and Item reads and writes raise. + Without a board, Release operations work, and Item reads and writes raise. One store lives + for one command or one Service round: it keeps the board's fields, and the listing of each + filter it read, for its life. """ def __init__( @@ -1203,6 +1266,9 @@ def __init__( (board_owner, board_number) if board_owner and board_number else None ) self._runner = runner + # The board's node id and fields, and its listing by filter, read once when first needed. + self._schema: _BoardSchema | None = None + self._listings: dict[str, list[_BoardItemPayload]] = {} # ── Releases ── @@ -1293,14 +1359,22 @@ def candidates(self) -> list[Candidate]: board = self._read_board(CONST_ROADMAP_OPEN_ITEMS_FILTER) return select_candidates(self._read_issues("state=open"), board) - def changes_since(self, since: datetime) -> list[Change]: - """The Item changes made at or after `since`, oldest first, read newest first.""" + def changes_since(self, since: datetime, *, except_actor: str | None = None) -> list[Change]: + """The Item changes made at or after `since`, oldest first, read newest first; those + `except_actor` made are left out before any job record is read; an empty actor leaves out + nothing.""" cutoff = as_utc(since) + skipped = except_actor or None changes: list[Change] = [] for page in range(1, DEFAULT_GH_MAX_PAGINATED_PAGES + 1): events = self._read(issue_events_page_args(self._repo, page), _EVENTS, "issue events") recent = list(takewhile(lambda event: event.created_at >= cutoff, events)) - changes.extend(change for event in recent if (change := event.change()) is not None) + changes.extend( + change + for event in recent + if (change := event.change()) is not None + and (skipped is None or change.actor != skipped) + ) if len(recent) < len(events) or len(events) < DEFAULT_GH_REST_PER_PAGE: return self._with_job_records(changes[::-1]) raise GitHubOperationError( @@ -1310,8 +1384,11 @@ def changes_since(self, since: datetime) -> list[Change]: details={"repo": self._repo[:256]}, ) - def add_item(self, number: int) -> None: - """Put issue `number` on the board, raising if it is not an issue of this repository.""" + def add_item(self, number: int) -> Item: + """Put issue `number` on the board and return its Item, raising if it is not an issue + of this repository. The card is the one `item-add` names, the issue's own when it is on + the board already, and its fields come from one read of that card, never from the board + listing, which can show a new card minutes late.""" owner, board_number = self._require_board() issue = self._read_issue(number) if issue.pull_request is not None: @@ -1320,9 +1397,20 @@ def add_item(self, number: int) -> None: operation="roadmap.item.add", details={"repo": self._repo[:256], "number": number}, ) - self._write( + written = self._write( item_add_args(owner, board_number, issue.html_url), f"add #{number} to the board" ) + added = self._validate(written, _ADDED_CARD, f"card of #{number} after it was added") + card, _ = self._read_card(added.id, f"#{number}") + if card is None or card.content_number != number: + raise GitHubOperationError( + f"Board #{board_number} does not hold card {added.id} that #{number} was just " + "added as.", + operation="roadmap.item.add", + details={"repo": self._repo[:256], "number": number, "card": added.id[:256]}, + ) + self._added(card, is_open=issue.state is GitHubState.OPEN) + return join_items([issue.record()], {number: card.entry()})[0] def set_field( self, @@ -1336,26 +1424,29 @@ def set_field( GitHub takes the two as separate calls, and the record goes first: a run that stops between them leaves the field as it was and the record naming the job's value, never - a field the job changed with no record of it. The value joins the job record the board - holds now, not the one `item` was read with, so two writes from one read both stay - recorded. + a field the job changed with no record of it. The value joins the job record the card + holds now, read by its node id just before the write, not the one `item` was read with, + so two writes from one read both stay recorded. A board field someone changed since the + store read the card raises before any write, unless the card already holds `value`, so + a job never reverts a change it did not see (ADR 0002). """ - options, entry = self._require_entry(item, "roadmap.item.set_field") + operation = "roadmap.item.set_field" + options = self._read_schema().options() + require_job_record_field(options) if field is ItemField.RELEASE: target = self._release_for(value) recorded = target.title if target else None else: require_option(options, field, value) recorded = value - changes = with_marks({field: recorded}, marks or {}) - self._edit_board_field( - item, CONST_GH_PROJECT_JOB_RECORD_FIELD, ["--text", entry.recorded(changes)] - ) + written = None if field is ItemField.RELEASE else field + card = self._require_entry(item, operation, written, value) + text = card.recorded(with_marks({field: recorded}, marks or {})) + card = self._edit_card(card, CONST_GH_PROJECT_JOB_RECORD_FIELD, text, operation) if field is ItemField.RELEASE: self._place_in_release(item, target) else: - change = ["--value", value] if value is not None else ["--clear"] - self._edit_board_field(item, field.value, change) + self._edit_card(card, field.value, value, operation) def set_marks( self, @@ -1365,14 +1456,16 @@ def set_marks( recorded: Mapping[ItemField, str | None] | None = None, forgotten: Collection[ItemField] = (), ) -> None: - """Set or clear a job's marks in the Item's job record, as held on the board now, and + """Set or clear a job's marks in the Item's job record, as its card holds it now, and record or forget a value for a field, in one write.""" - _, entry = self._require_entry(item, "roadmap.item.set_marks") + operation = "roadmap.item.set_marks" + require_job_record_field(self._read_schema().options()) + card = self._require_entry(item, operation) changes: JobRecord = {} for item_field, value in (recorded or {}).items(): changes[item_field] = value - text = entry.recorded(with_marks(changes, marks), forgotten) - self._edit_board_field(item, CONST_GH_PROJECT_JOB_RECORD_FIELD, ["--text", text]) + text = card.recorded(with_marks(changes, marks), forgotten) + self._edit_card(card, CONST_GH_PROJECT_JOB_RECORD_FIELD, text, operation) def run_record(self) -> JobRecord: """The run record card's job record, empty while the board has no such card.""" @@ -1380,17 +1473,18 @@ def run_record(self) -> JobRecord: return card.card().job_record if card else {} def set_run_record(self, marks: Mapping[Any, str | None]) -> None: - """Set or clear marks in the run record card's job record, creating the card first when - the board has none. The card is found again after it is created, by its title.""" - board = self._require_existing_board() - fields = self.board_fields() - require_job_record_field(field_options(fields)) - record = require_field(fields, CONST_GH_PROJECT_JOB_RECORD_FIELD, "roadmap.run_record") - card = self._run_record_card() or self._create_run_record_card() - self._write( - card_edit_args(card.id, board.id, record.id, ["--text", card.recorded(marks)]), - "set the run record", + """Set or clear marks in the run record card's job record, as the card holds it now, + creating the card first when the board has none.""" + operation = "roadmap.run_record" + require_job_record_field(self._read_schema().options()) + listed = self._run_record_card() + card = ( + self._require_card_node(listed.id, f"Run record card {listed.id}", operation) + if listed + else self._create_run_record_card() ) + text = card.recorded(marks) + self._edit_card(card, CONST_GH_PROJECT_JOB_RECORD_FIELD, text, operation) def release_changes(self, number: int) -> list[Change]: """Every time issue `number` joined or left a Release, from its own events.""" @@ -1422,7 +1516,9 @@ def create_issue(self, title: str, body: str, *, labels: Sequence[str] = ()) -> return self._validate(written, _ISSUE, "issue after it was opened").record() def close_issue(self, number: int, reason: CloseReason, comment: str) -> None: - """Comment on issue `number`, then close it for `reason`.""" + """Comment on issue `number`, then close it for `reason`. The board's own workflow then + changes the issue's card, so the store drops the listings it read and reads the board + again when next needed.""" if self._read_issue(number).pull_request is not None: raise GitHubOperationError( f"#{number} in {self._repo} is a pull request, not an issue.", @@ -1431,6 +1527,7 @@ def close_issue(self, number: int, reason: CloseReason, comment: str) -> None: ) self.comment(number, comment) self._write(close_issue_args(self._repo, number, reason), f"close #{number}") + self._listings = {} def read_issue_body(self, number: int) -> str: """The body of issue `number`, raising if it is not an issue of this repository.""" @@ -1469,7 +1566,8 @@ def comment(self, number: int, body: str) -> None: def close_as_duplicate(self, number: int, original: int, comment: str | None) -> None: """Comment on issue `number` unless `comment` is None, then close it as a duplicate of `original` through GraphQL, which alone sets the original (`duplicateIssueId`). Both are - read first, so a pull request on either side raises before any write.""" + read first, so a pull request on either side raises before any write. The board's own + workflow then changes the issue's card, so the store drops the listings it read.""" node_ids = [self._require_issue_node(n, "roadmap.issue.close") for n in (number, original)] if comment is not None: self.comment(number, comment) @@ -1477,6 +1575,7 @@ def close_as_duplicate(self, number: int, original: int, comment: str | None) -> close_as_duplicate_request(node_ids[0], node_ids[1]), f"close #{number} as a duplicate of #{original}", ) + self._listings = {} def closures(self, number: int) -> list[Closure]: """Every close and reopen of issue `number` from its timeline, oldest first.""" @@ -1561,7 +1660,8 @@ def create_board(self, title: str, fields: Sequence[FieldSpec]) -> Board: project_link_args(owner, created.number, self._repo), f"link board #{created.number}" ) current = { - board_field.name: board_field for board_field in self._read_fields(created.number) + board_field.name: board_field + for board_field in self._read_fields(created.number).fields } for spec in fields: self._create_or_align_field(created, current.get(spec.name), spec) @@ -1569,46 +1669,50 @@ def create_board(self, title: str, fields: Sequence[FieldSpec]) -> Board: def board_fields(self) -> list[BoardField]: """Every field on the board, with each option's id, color and description.""" - return self._read_fields(self._require_board()[1]) + return list(self._read_schema().fields) def delete_field(self, name: str) -> None: """Delete the board field `name`, raising if the board has none.""" - deleted = require_field(self.board_fields(), name, "roadmap.board.delete_field") + schema = self._read_schema() + deleted = schema.field(name, "roadmap.board.delete_field") self._write(field_delete_args(deleted.id), f"delete the {name} field") + kept = tuple(board_field for board_field in schema.fields if board_field.id != deleted.id) + self._schema = schema.model_copy(update={"fields": kept}) def cards(self) -> list[Card]: """Everything on the board, whatever it holds and whichever repository it belongs to.""" return [board_item.card() for board_item in self._read_board_listing()] def set_card_field(self, card: Card, field: ItemField, value: str | None) -> None: - """Set or clear a board field on any card by its node ids, then record it.""" + """Set or clear a board field on any card by its node ids, then record it; a field + someone changed since the store read the card raises before any write, unless the card + already holds `value`.""" + operation = "roadmap.card.set_field" require_board_field(field) - board = self._require_existing_board() - fields = self.board_fields() - require_job_record_field(field_options(fields)) - require_option(field_options(fields), field, value) - current = self._require_card(card, "roadmap.card.set_field") - target = require_field(fields, field.value, "roadmap.card.set_field") - option_id = next((option.id for option in target.options if option.name == value), None) - change = ["--single-select-option-id", option_id] if option_id else ["--clear"] - record = require_field(fields, CONST_GH_PROJECT_JOB_RECORD_FIELD, "roadmap.card.set_field") - edits = ( - (target, change), - (record, ["--text", current.recorded({field: value})]), + options = self._read_schema().options() + require_job_record_field(options) + require_option(options, field, value) + current = self._require_card_node( + card.id, + f"Card {card.id}", + operation, + field=field, + value=value, + held=card.field_value(field), ) - for board_field, flags in edits: - self._write( - card_edit_args(card.id, board.id, board_field.id, flags), - f"set {board_field.name} on card {card.id}", - ) + current = self._edit_card(current, field.value, value, operation) + text = current.recorded({field: value}) + self._edit_card(current, CONST_GH_PROJECT_JOB_RECORD_FIELD, text, operation) def remove_card(self, card: Card) -> None: """Take `card` off the board, raising if it is not on it.""" owner, number = self._require_board() - self._require_card(card, "roadmap.card.remove") + self._require_card_node(card.id, f"Card {card.id}", "roadmap.card.remove") self._write( item_delete_args(owner, number, card.id), f"remove card {card.id} from board #{number}" ) + for listing in self._listings.values(): + listing[:] = [listed for listed in listing if listed.id != card.id] def workflows(self) -> list[Workflow]: """The board's built-in workflows.""" @@ -1736,37 +1840,145 @@ def _with_job_records(self, changes: list[Change]) -> list[Change]: ] def _run_record_card(self) -> _BoardItemPayload | None: - """The run record card as the board holds it now, or None.""" + """The run record card as the board listing holds it, or None.""" listing = self._read_board_listing() return next((item for item in listing if item.is_run_record()), None) def _create_run_record_card(self) -> _BoardItemPayload: - """Put the run record card on the board, and read it back.""" + """Put the run record card on the board: the card `item-create` names, with no field + set, read nothing after the create.""" owner, number = self._require_board() - self._write(run_record_card_args(owner, number), "create the run record card") - created = self._run_record_card() - if created is None: - raise GitHubOperationError( - f"Board #{number} does not list the run record card just created.", - operation="roadmap.run_record", - details={"repo": self._repo[:256], "board": number}, - ) - return created + written = self._write(run_record_card_args(owner, number), "create the run record card") + created = self._validate(written, _ADDED_CARD, "run record card after it was created") + content = {"type": CardKind.DRAFT_ISSUE.value, "title": CONST_ROADMAP_RUN_RECORD_TITLE} + card = _BOARD_ITEM.validate_python({"id": created.id, "content": content}) + self._added(card, is_open=False) + return card def _require_entry( - self, item: Item, operation: str - ) -> tuple[dict[str, tuple[str, ...]], _BoardItemPayload]: - """The board's options and the Item's card, raising before any write when either is missing.""" - options = self._read_board_options() - require_job_record_field(options) - entry = self._read_board_items().get(item.number) - if entry is None: - raise GitHubOperationError( - f"#{item.number} is not on the board.", - operation=operation, - details={"repo": self._repo[:256], "number": item.number}, - ) - return options, entry + self, item: Item, operation: str, field: ItemField | None = None, value: str | None = None + ) -> _BoardItemPayload: + """The Item's card as it is now, read by its node id, raising before any write when the + Item has none, or it is gone, archived or another issue's, when the points left are + below the reserve, or when someone changed `field` since the store read the card.""" + return self._require_card_node( + item.card_id, + f"#{item.number}", + operation, + number=item.number, + field=field, + value=value, + held=None if field is None else item.field_value(field), + ) + + def _require_card_node( + self, + card_id: str | None, + name: str, + operation: str, + *, + number: int | None = None, + field: ItemField | None = None, + value: str | None = None, + held: str | None = None, + ) -> _BoardItemPayload: + """The card `card_id` as it is now, from one read by its node id, raising before any + write when it is gone or archived, or not issue `number`'s when one is given, when that + read leaves fewer points than the reserve, or when writing `value` to `field` would + revert a change made since the store read the card: the value read is the card's in the + store's listings, which its own writes keep current, or `held`, the caller's, when no + listing holds the card. The listings take the card's job record as it is now, and keep + its fields as the store read them.""" + if not card_id: + raise self._not_on_board(name, operation) + card, budget = self._read_card(card_id, name) + if card is None: + raise self._not_on_board(name, operation) + require_write_floor(budget, name) + if number is not None and not ( + card.is_issue_of(self._repo) and card.content_number == number + ): + raise self._not_on_board(name, operation) + if field is not None: + read = {listed.field_value(field.value) for listed in self._listed(card.id)} + now = card.field_value(field.value) + require_unchanged(card.name(), field, read or {held}, now, value, operation) + self._remember(card.id, CONST_GH_PROJECT_JOB_RECORD_FIELD, card.job_record_text()) + return card + + def _read_card(self, card_id: str, name: str) -> tuple[_BoardItemPayload | None, GraphQLBudget]: + """Card `card_id` from one GraphQL read by its node id, None when GitHub holds no such + card or it is archived, and the budget the read reported; any other failure raises.""" + what = f"the card of {name}" + proc = self._run(board_card_args(card_id)) + if proc.returncode == 0: + read = self._validate(proc.stdout or "", _BOARD_CARD, what) + else: + read = self._gone_card(proc, what) + self._note_budget(read.rate_limit) + listed = read.listed() + card = None if listed is None else self._validate(json.dumps(listed), _BOARD_ITEM, what) + return card, read.rate_limit + + def _gone_card(self, proc: subprocess.CompletedProcess[str], what: str) -> BoardCardPayload: + """A failed card read's answer when GitHub says only that the node does not exist, which + `gh` reports by exiting 1 with the answer on stdout; any other failure raises.""" + try: + read = _BOARD_CARD.validate_json(proc.stdout or "") + except MalformedPayloadError: + raise self._failure(proc, f"read {what}", "roadmap.read") from None + if not read.is_gone(): + raise self._failure(proc, f"read {what}", "roadmap.read") + return read + + def _not_on_board(self, name: str, operation: str) -> GitHubOperationError: + return GitHubOperationError( + f"{name} is not on the board.", + operation=operation, + details={"repo": self._repo[:256], "card": name[:256]}, + ) + + def _edit_card( + self, card: _BoardItemPayload, field_name: str, value: str | None, operation: str + ) -> _BoardItemPayload: + """Write `value` to the board field `field_name` on `card` by node ids: text for the job + record, an option's id for a single-select field, a clear for None. The listings the + store holds take the value it sent.""" + schema = self._read_schema() + board_field = schema.field(field_name, operation) + self._write( + card_edit_args(card.id, schema.board_id, board_field.id, _change(board_field, value)), + f"set {field_name} on {card.name()}", + ) + self._remember(card.id, field_name, value) + return card.written(field_name, value) + + def _listed(self, card_id: str) -> list[_BoardItemPayload]: + """Card `card_id` in each listing the store holds it in, as the store read it.""" + return [ + listed for items in self._listings.values() for listed in items if listed.id == card_id + ] + + def _remember(self, card_id: str, field_name: str, value: str | None) -> None: + """Hold `value` as card `card_id`'s field `field_name` in every listing the store holds + the card in; its other fields stay as the store read them.""" + for listing in self._listings.values(): + listing[:] = [ + listed.written(field_name, value) if listed.id == card_id else listed + for listed in listing + ] + + def _added(self, card: _BoardItemPayload, *, is_open: bool) -> None: + """Hold a card the store added in each listing that selects it: the unfiltered one, + which selects every card not archived, and the open items' when its issue is open; a + listing that already holds the card keeps it as the store read it. Any other listing, + whose filter the store can't judge, is read again when next needed.""" + kept = {"", CONST_ROADMAP_OPEN_ITEMS_FILTER} if is_open else {""} + self._listings = { + query: listing if any(listed.id == card.id for listed in listing) else [*listing, card] + for query, listing in self._listings.items() + if query in kept + } def _release_for(self, version: str | None) -> Release | None: """The Release of `version` an issue is placed in, None for the backlog; raising when @@ -1782,13 +1994,6 @@ def _place_in_release(self, item: Item, target: Release | None) -> None: f"set the Release of #{item.number}", ) - def _edit_board_field(self, item: Item, field_name: str, change: list[str]) -> None: - owner, board_number = self._require_board() - self._write( - item_edit_args(owner, board_number, item.url, field_name, change), - f"set {field_name} on #{item.number}", - ) - def _write_milestone( self, method: str, number: int | None, fields: dict[str, str | date], action: str ) -> Release: @@ -1815,10 +2020,17 @@ def _require_board(self) -> tuple[str, int]: def _read_board_listing(self, board_filter: str | None = None) -> list[_BoardItemPayload]: """The board's items that `board_filter`, or the job's filter, selects, archived ones - left out, refusing before any page when the budget can't cover the read and raising on a - short read. A count that changes during the read is read again once.""" - owner, number = self._require_board() + left out: read the first time the store needs that filter, and kept for its life.""" query = self._board_filter if board_filter is None else board_filter + if query not in self._listings: + self._listings[query] = self._fetch_board_listing(query) + return self._listings[query] + + def _fetch_board_listing(self, query: str) -> list[_BoardItemPayload]: + """One read of the items `query` selects, refusing before any page when the budget can't + cover the read and raising on a short read. A count that changes during the read is read + again once.""" + owner, number = self._require_board() texts = MESSAGES.roadmap what = ( texts.board_items_filtered.format(number=number, query=query) @@ -1904,29 +2116,6 @@ def _read_board_items(self, board_filter: str | None = None) -> dict[int, _Board if item.is_issue_of(self._repo) and item.content_number is not None } - def _require_existing_board(self) -> Board: - found = self.board() - if found is None: - owner, number = self._require_board() - raise GitHubOperationError( - f"{owner} has no board #{number}.", - operation="roadmap.board", - details={"owner": owner[:256], "number": number}, - ) - return found - - def _require_card(self, card: Card, operation: str) -> _BoardItemPayload: - """The card as the board holds it now, raising when it is no longer on the board.""" - listing = self._read_board_listing() - found = next((current for current in listing if current.id == card.id), None) - if found is None: - raise GitHubOperationError( - f"Card {card.id} is not on the board.", - operation=operation, - details={"repo": self._repo[:256], "card": card.id[:256]}, - ) - return found - def _pull_requests( self, connection: _PullRequestConnectionPayload, what: str ) -> list[PullRequest]: @@ -1962,8 +2151,15 @@ def _require_issue_node(self, number: int, operation: str) -> str: ) return issue.node_id - def _read_fields(self, number: int) -> list[BoardField]: - """Board `number`'s fields through GraphQL, which alone gives option colors and descriptions.""" + def _read_schema(self) -> _BoardSchema: + """The configured board's node id and fields, read the first time a store needs them.""" + if self._schema is None: + self._schema = self._read_fields(self._require_board()[1]) + return self._schema + + def _read_fields(self, number: int) -> _BoardSchema: + """Board `number`'s node id and fields through GraphQL, which alone gives option colors + and descriptions.""" owner, _ = self._require_board() payload = self._read( board_fields_args(owner, number), @@ -1972,7 +2168,9 @@ def _read_fields(self, number: int) -> list[BoardField]: ) connection = payload.fields self._require_whole(len(connection.nodes), connection.total_count, "board fields") - return [node.field() for node in connection.nodes] + return _BoardSchema( + board_id=payload.board_id, fields=tuple(node.field() for node in connection.nodes) + ) def _create_or_align_field( self, board: Board, current: BoardField | None, spec: FieldSpec @@ -2001,17 +2199,6 @@ def _graphql(self, request: str, action: str) -> str: raise self._failure(proc, action, "roadmap.write") return proc.stdout or "" - def _read_board_options(self) -> dict[str, tuple[str, ...]]: - """Every board field's options by field name; fields that aren't single-select have none.""" - owner, number = self._require_board() - listing = self._read( - field_list_args(owner, number), - _FIELDS, - f"board #{number} fields", - ) - self._require_whole(len(listing.fields), listing.total_count, f"board #{number} fields") - return listing.options() - def _read_issue(self, number: int) -> _IssuePayload: return self._read(issue_args(self._repo, number), _ISSUE, f"issue #{number}") @@ -2085,6 +2272,23 @@ def _failure( ) +def _change(board_field: BoardField, value: str | None) -> list[str]: + """The `item-edit` flags that write `value` to `board_field`: its text for a text field, + the option's id for a single-select one, and a clear for None.""" + if value is None: + return ["--clear"] + if not board_field.single_select: + return ["--text", value] + found = next((o.id for o in board_field.options if o.name == value and o.id), None) + if found is None: + raise GitHubOperationError( + f"The board's {board_field.name} field has no option {value[:64]!r} to write.", + operation="roadmap.write", + details={"field": board_field.name[:256], "value": value[:256]}, + ) + return ["--single-select-option-id", found] + + def _counts(totals: Sequence[int], listing: Sequence[object]) -> str: """The totals a read saw, then what it received.""" return ", ".join(str(total) for total in totals) + f"; received {len(listing)}" diff --git a/src/devops_cli/roadmap/intake.py b/src/devops_cli/roadmap/intake.py index 109d41a5ea..2f1a9d23a2 100644 --- a/src/devops_cli/roadmap/intake.py +++ b/src/devops_cli/roadmap/intake.py @@ -37,7 +37,9 @@ candidate only), add a `type/*` label when it has none, put it on the board, set the milestone when the placement changes it, set the empty ones of Status (New), Value and Effort, leave one reason comment carrying `CONST_ROADMAP_INTAKE_REASON_MARKER` unless one is there, then set -Priority. A duplicate close comments with `CONST_ROADMAP_INTAKE_DUPLICATE_MARKER` unless that +Priority. Each field write goes to the card the item has, or the card the add returned: no +placement looks for its card in the board listing, which can show a new card minutes after the +add (#1361). A duplicate close comments with `CONST_ROADMAP_INTAKE_DUPLICATE_MARKER` unless that comment is there, then closes. A run that stops part-way leaves an open issue off the board, an item with no Priority, or an open duplicate, and the next run finishes it. Intake writes to no issue but the candidate. @@ -102,7 +104,6 @@ ) from devops_cli.dry_run.requests import PlannedRequest, render_request_plan from devops_cli.exceptions.config import ConfigurationError -from devops_cli.exceptions.git import GitHubOperationError from devops_cli.exceptions.security import SecurityError from devops_cli.github.labels import LabelSpec from devops_cli.lang import MESSAGES @@ -1159,15 +1160,7 @@ def _apply_placement(store: RoadmapStore, decision: IntakeDecision) -> int | Non assert number is not None and decision.priority is not None for label in decision.labels: store.label_issue(number, label) - if subject.item is None: - store.add_item(number) - item = store.item(number) - if item is None: - raise GitHubOperationError( - f"#{number} is not on the board after intake added it.", - operation="roadmap.intake", - details={"number": number}, - ) + item = subject.item or store.add_item(number) if decision.moves and decision.placement is not None: store.set_field(item, ItemField.RELEASE, decision.placement.release) for board_field, value in decision.fields: diff --git a/src/devops_cli/roadmap/intake_requests.py b/src/devops_cli/roadmap/intake_requests.py index 6ca9a97965..3eee28e47c 100644 --- a/src/devops_cli/roadmap/intake_requests.py +++ b/src/devops_cli/roadmap/intake_requests.py @@ -6,10 +6,11 @@ call and the model calls. `method` names the transport and whether it reads or writes, and `target` what it reads or writes. Every `gh` command shows its exact argv and stdin, built by the store's own argument builders (`roadmap/request_plan.py`, #1125), one line per command, so a -board write shows the board reads it makes first. A value that needs a read is a placeholder in -angle brackets, a request that runs only when an earlier one returns something names that in -`condition`, and a listing read a page at a time, or a request made for each candidate, says so -in `repeat`. The reads end with the GraphQL budget read the run's spend line comes from. +board write shows the read of its one card it makes first (#1361). A value that needs a read is +a placeholder in angle brackets, a request that runs only when an earlier one returns something +names that in `condition`, and a listing read a page at a time, or a request made for each +candidate, says so in `repeat`. The reads end with the GraphQL budget read the run's spend line +comes from. A `--plan` run makes the reads and the model calls, writes nothing, and reports what it spent: each `gh` command by the rate-limit resource it spends, as `run_gh` classifies it, and each @@ -192,7 +193,6 @@ def _placement(self, subject: str, repeat: str) -> list[PlannedRequest]: steps: list[tuple[str, list[PlannedRequest], dict[str, str]]] = [ ("label", store.label_issue(subject), {}), ("add", store.add_item(subject), {}), - ("item", store.item(subject), {}), ("release", store.set_field(subject, "Release"), {}), *( ("field", store.set_field(subject, name), {"field": shown}) diff --git a/src/devops_cli/roadmap/memory_store.py b/src/devops_cli/roadmap/memory_store.py index 123f486f7e..1c446b083f 100644 --- a/src/devops_cli/roadmap/memory_store.py +++ b/src/devops_cli/roadmap/memory_store.py @@ -12,6 +12,10 @@ write the store makes as a job, not as a person, is kept in `job_writes`, so a test can check what a job wrote and that a preview wrote nothing. The only draft issue the board holds is the run record card, once a job has written the run record. + +Each view holds every card as it last read it, with its own writes: a job's write of a field a +person changed since raises before it changes anything, as the GitHub adapter's does against +its listing (#1361). Reads here are live, so a view's next read sees the person's change. """ from __future__ import annotations @@ -81,6 +85,7 @@ require_new_release, require_option, require_release, + require_unchanged, select_candidates, with_marks, ) @@ -94,8 +99,9 @@ def _at_or_after(moment: datetime | None, since: datetime) -> bool: return moment is not None and moment >= as_utc(since) -def _card_id(number: int) -> str: - return f"card-{number}" +def _entry(number: int) -> BoardEntry: + """A new card for issue `number`, with no field set.""" + return BoardEntry(number=number, card_id=f"card-{number}") # The run record card's id: the only draft issue the in-memory board holds. @@ -178,6 +184,8 @@ def __init__( self._roadmap = _Roadmap(repo=repo, clock=clock, board=None, is_private=is_private) self._actor = actor self._writes_job_record = True + # Each card as this view last read or wrote it, by issue number. + self._read: dict[int, BoardEntry] = {} if board_exists: self._roadmap.board = self._new_board("Roadmap") specs = [ @@ -238,7 +246,7 @@ def seed_issue( closed_at=now if state is GitHubState.CLOSED else None, ) if on_board: - self._roadmap.cards[number] = BoardEntry(number=number) + self._roadmap.cards[number] = _entry(number) return number def seed_field(self, spec: FieldSpec) -> BoardField: @@ -571,7 +579,8 @@ def item(self, number: int) -> Item | None: """The Item numbered `number`, or None when that issue is not on the board.""" self._require_board() issue = self._roadmap.issues.get(number) - return next(iter(join_items([issue], self._roadmap.cards)), None) if issue else None + found = self._seen(join_items([issue], self._roadmap.cards)) if issue else [] + return next(iter(found), None) def items(self, *, release: str | None = None) -> list[Item]: """Every Item, open and closed, or only those in the Release of `release`.""" @@ -580,7 +589,7 @@ def items(self, *, release: str | None = None) -> list[Item]: if release is not None: version = parse_release_version(release) issues = [issue for issue in issues if in_release(issue.release, version)] - return join_items(issues, self._roadmap.cards) + return self._seen(join_items(issues, self._roadmap.cards)) def backlog(self) -> list[Item]: """The open Items in no Release.""" @@ -593,15 +602,22 @@ def candidates(self) -> list[Candidate]: self._require_board() return select_candidates(self._roadmap.issues.values(), self._roadmap.cards) - def changes_since(self, since: datetime) -> list[Change]: - """The changes made at or after `since`, oldest first, each as a poll reads it now.""" + def changes_since(self, since: datetime, *, except_actor: str | None = None) -> list[Change]: + """The changes made at or after `since`, oldest first, each as a poll reads it now, + leaving out those `except_actor` made; an empty actor leaves out nothing.""" cutoff = as_utc(since) - return [self._as_read(change) for change in self._roadmap.changes if change.at >= cutoff] + skipped = except_actor or None + return [ + self._as_read(change) + for change in self._roadmap.changes + if change.at >= cutoff and (skipped is None or change.actor != skipped) + ] # ── Item writes ── - def add_item(self, number: int) -> None: - """Put issue `number` on the board, raising if it is not an issue of this repository.""" + def add_item(self, number: int) -> Item: + """Put issue `number` on the board and return its Item, raising if it is not an issue + of this repository; an issue already on the board keeps its card.""" self._require_board() issue = self._roadmap.issues.get(number) if issue is None or issue.pull_request: @@ -610,8 +626,9 @@ def add_item(self, number: int) -> None: operation="roadmap.item.add", details={"number": number}, ) - self._roadmap.cards.setdefault(number, BoardEntry(number=number)) + self._read.setdefault(number, self._roadmap.cards.setdefault(number, _entry(number))) self._log("add_item", number) + return join_items([issue], self._roadmap.cards)[0] def set_field( self, @@ -624,9 +641,12 @@ def set_field( """Set or clear one of the Item's fields; the store's own writes also record the value, and `marks` with it, in one step, so no write stops between the two. - `job_writes` keeps the field's entry, then one entry for each mark. + `job_writes` keeps the field's entry, then one entry for each mark. A job's write of a + board field a person changed since this view read the card raises, unless the card + already holds `value`. """ - entry = self._require_entry(item, "roadmap.item.set_field") + written = None if field is ItemField.RELEASE else field + entry = self._require_entry(item, "roadmap.item.set_field", written, value) if field is ItemField.RELEASE: recorded = self._place_in_release(item.number, value) else: @@ -640,6 +660,7 @@ def set_field( entry = self._recorded(entry, mark, marked) self._log("set_mark", item.number, mark.value, marked) self._roadmap.cards[item.number] = entry + self._remember(entry, written) def set_marks( self, @@ -666,6 +687,7 @@ def set_marks( entry = self._recorded(entry, mark, value) self._log("set_mark", item.number, mark.value, value) self._roadmap.cards[item.number] = entry + self._remember(entry) def run_record(self) -> JobRecord: """The run record card's job record, empty while the board has no such card.""" @@ -805,6 +827,7 @@ def cards(self) -> list[Card]: """Every card: this repository's issues and pull requests on the board, then the run record card when there is one.""" self._require_board() + self._read.update(self._roadmap.cards) cards = [self._card(entry) for _, entry in sorted(self._roadmap.cards.items())] if self._roadmap.run_record is not None: cards.append( @@ -817,14 +840,20 @@ def cards(self) -> list[Card]: return cards def set_card_field(self, card: Card, field: ItemField, value: str | None) -> None: - """Set or clear a board field on any card; the store's own writes also record it.""" + """Set or clear a board field on any card; the store's own writes also record it, and + raise for a field a person changed since this view read the card, unless the card + already holds `value`.""" + operation = "roadmap.card.set_field" require_board_field(field) - number = self._card_number(card, "roadmap.card.set_field") + number = self._card_number(card, operation) if self._writes_job_record: require_job_record_field(self._roadmap.board_fields) require_option(field_options(self._roadmap.board_fields.values()), field, value) - entry = self._roadmap.cards[number].model_copy(update={field.name.lower(): value}) + current = self._roadmap.cards[number] + self._require_unchanged(current, field, value, card.field_value(field), operation) + entry = current.model_copy(update={field.name.lower(): value}) self._roadmap.cards[number] = self._recorded(entry, field, value) + self._remember(self._roadmap.cards[number], field) self._field_changed(number, field, value) self._log("set_card_field", number, field.value, value) @@ -836,6 +865,7 @@ def remove_card(self, card: Card) -> None: return number = self._card_number(card, "roadmap.card.remove") del self._roadmap.cards[number] + self._read.pop(number, None) self._log("remove_card", number) def workflows(self) -> list[Workflow]: @@ -899,11 +929,15 @@ def _require_issue(self, number: int, operation: str) -> IssueRecord: ) return issue - def _require_entry(self, item: Item, operation: str) -> BoardEntry: - """The Item's board entry, refusing an Item off the board or a board with no record field.""" + def _require_entry( + self, item: Item, operation: str, field: ItemField | None = None, value: str | None = None + ) -> BoardEntry: + """The Item's board entry, refusing an Item off the board, one whose card id is not its + card's, a board with no record field, and a job's write of `value` to `field` when a + person changed it since this view read the card.""" self._require_board() entry = self._roadmap.cards.get(item.number) - if entry is None: + if entry is None or entry.card_id != item.card_id: raise GitHubOperationError( f"#{item.number} is not on the board.", operation=operation, @@ -911,8 +945,40 @@ def _require_entry(self, item: Item, operation: str) -> BoardEntry: ) if self._writes_job_record: require_job_record_field(self._roadmap.board_fields) + if field is not None: + self._require_unchanged(entry, field, value, item.field_value(field), operation) return entry + def _require_unchanged( + self, entry: BoardEntry, field: ItemField, value: str | None, held: str | None, op: str + ) -> None: + """A job's write of `value` to `field` raises when the card holds another value than + this view read: its own copy, kept current by its writes, or `held`, the caller's, when + it has none. A person's view checks nothing, as a person on GitHub sees the board.""" + if not self._writes_job_record: + return + attribute = field.name.lower() + read = self._read.get(entry.number) + before = held if read is None else getattr(read, attribute) + now = getattr(entry, attribute) + require_unchanged(f"#{entry.number}", field, {before}, now, value, op) + + def _seen(self, items: list[Item]) -> list[Item]: + """`items`, each card held as this view read it.""" + self._read.update((item.number, self._roadmap.cards[item.number]) for item in items) + return items + + def _remember(self, entry: BoardEntry, field: ItemField | None = None) -> None: + """Hold this view's own write: its copy of the card takes the job record and `field`'s + value `entry` holds, and keeps its other fields as the view read them.""" + read = self._read.get(entry.number) + if read is None: + return + kept: dict[str, Any] = {"job_record": entry.job_record} + if field is not None: + kept[field.name.lower()] = getattr(entry, field.name.lower()) + self._read[entry.number] = read.model_copy(update=kept) + def _log( self, operation: str, @@ -930,7 +996,7 @@ def _as_read(self, change: Change) -> Change: issue = self._roadmap.issues.get(change.number) if change.kind in RELEASE_CHANGE_KINDS or issue is None: return change - entry = self._roadmap.cards.get(change.number, BoardEntry(number=change.number)) + entry = self._roadmap.cards.get(change.number, _entry(change.number)) values = entry.model_dump() | {"release": issue.release} moved = change.field is ItemField.RELEASE return change.model_copy( @@ -1007,16 +1073,16 @@ def _card(self, entry: BoardEntry) -> Card: issue = self._roadmap.issues[entry.number] kind = CardKind.PULL_REQUEST if issue.pull_request else CardKind.ISSUE return Card( - id=_card_id(entry.number), + id=entry.card_id, kind=kind, url=issue.url, repository=self._roadmap.repo, - **entry.model_dump(), + **entry.model_dump(exclude={"card_id"}), ) def _card_number(self, card: Card, operation: str) -> int: self._require_board() - number = next((n for n in self._roadmap.cards if _card_id(n) == card.id), None) + number = next((n for n, e in self._roadmap.cards.items() if e.card_id == card.id), None) if number is None: raise GitHubOperationError( f"Card {card.id} is not on the board.", diff --git a/src/devops_cli/roadmap/request_plan.py b/src/devops_cli/roadmap/request_plan.py index 4737ab9ba1..d99c4a921e 100644 --- a/src/devops_cli/roadmap/request_plan.py +++ b/src/devops_cli/roadmap/request_plan.py @@ -9,8 +9,10 @@ `StoreRequests` gives the requests of each store operation; `render_requests`, `reprioritize_requests` and `migrate_requests` put a job's operations in the order the job makes -them. Every run of a job that reads the board ends with one GraphQL budget read, for its spend -line, after any write. +them. A store reads the board's fields, and the listing of each filter, once (#1361), so an +operation that needs them lists their read under the condition that the run has not made it yet. +A board write lists the read of its one card and the edit by node ids. Every run of a job that +reads the board ends with one GraphQL budget read, for its spend line, after any write. """ from __future__ import annotations @@ -35,6 +37,7 @@ from devops_cli.roadmap import github_store as gh from devops_cli.roadmap.board_read import ( board_budget_args, + board_card_args, board_items_args, graphql_budget_args, ) @@ -169,15 +172,20 @@ def board_read(self, board_filter: str | None = None) -> Requests: ), ] + def kept_board(self, board_filter: str | None = None) -> Requests: + """The board read a store makes the first time it needs this filter's listing.""" + unread = MESSAGES.roadmap.plan_conditions["board_unread"] + return within(self.board_read(board_filter), unread) + def items(self, release: str | None = None) -> Requests: if release is None: - return [*self.board_read(), *self._issues("state=all")] + return [*self.kept_board(), *self._issues("state=all")] query = f"milestone={_p('milestone')}&state=all" - return [*self.board_read(), *self.releases(), *self._issues(query)] + return [*self.kept_board(), *self.releases(), *self._issues(query)] def backlog(self) -> Requests: return [ - *self.board_read(CONST_ROADMAP_OPEN_ITEMS_FILTER), + *self.kept_board(CONST_ROADMAP_OPEN_ITEMS_FILTER), *self._issues("milestone=none&state=open"), ] @@ -187,8 +195,13 @@ def issues(self) -> Requests: def board_fields(self, board: str | None = None) -> Requests: return [self.gh(gh.board_fields_args(self.owner, board or self.number), "fields")] - def field_options(self) -> Requests: - return [self.gh(gh.field_list_args(self.owner, self.number), "field_options")] + def kept_fields(self) -> Requests: + """The fields read a store makes the first time it needs the board's fields.""" + return within(self.board_fields(), MESSAGES.roadmap.plan_conditions["fields_unread"]) + + def card(self, subject: str) -> Requests: + """One card by its node id: its fields, its job record and the GraphQL points left.""" + return [self.gh(board_card_args(_p("card_id")), "card", subject=subject)] def workflows(self) -> Requests: return [self.gh(gh.board_workflows_args(self.owner, self.number), "workflows")] @@ -251,9 +264,6 @@ def branch(self) -> Requests: def issue(self, subject: str) -> Requests: return [self.gh(gh.issue_args(self.repo, _number(subject)), "issue", subject=subject)] - def item(self, subject: str) -> Requests: - return [*self.board_read(), *self.issue(subject)] - def count_issues(self, query: IssueQuery, *, text: str | None = None) -> Requests: args = gh.issue_count_args(self.repo, query) shown = text or gh.issue_search_text(self.repo, query) @@ -276,7 +286,7 @@ def evidence(self, subject: str) -> Requests: return [self.gh(args, key, subject=subject, repeat=repeat) for args, key in kinds] def run_record(self) -> Requests: - return self.board_read() + return self.kept_board() def budget(self) -> Requests: """The run's last request: the GraphQL budget its spend line reports.""" @@ -305,7 +315,8 @@ def create_branch(self) -> Requests: def _edit( self, subject: str, field_name: str, change: Sequence[str], key: str ) -> PlannedRequest: - args = gh.item_edit_args(self.owner, self.number, _p("url"), field_name, change) + """An `item-edit` of one card by node ids, which sends only the mutation.""" + args = gh.card_edit_args(_p("card_id"), _p("board_id"), _p("field_id"), change) return self.gh(args, key, subject=subject, field=field_name) def _record(self, subject: str) -> PlannedRequest: @@ -313,27 +324,29 @@ def _record(self, subject: str) -> PlannedRequest: return self._edit(subject, record, ["--text", _p("record")], "record") def set_marks(self, subject: str) -> Requests: - """The board's options and items, then the job record.""" - return [*self.field_options(), *self.board_read(), self._record(subject)] + """The board's fields once a run, the card, then the job record.""" + return [*self.kept_fields(), *self.card(subject), self._record(subject)] def set_field(self, subject: str, field_name: str | None = None) -> Requests: - """The board's options and items, every milestone for a Release value, the job record, - then the field: the milestone for the Release, through REST. `field_name` None stands - for either.""" + """The board's fields once a run, every milestone for a Release value, the card, the + job record, then the field: the milestone for the Release, through REST. `field_name` + None stands for either.""" cond = MESSAGES.roadmap.plan_conditions release, other = cond["release_field"], cond["other_field"] listing = within(self.releases(), cond["release_named"]) milestone = gh.issue_milestone_args(self.repo, _number(subject), _p("milestone")) patch = self.gh(milestone, "milestone", subject=subject) - edit = self._edit(subject, field_name or _p("field"), ["--value", _p("value")], "set_field") - head = [*self.field_options(), *self.board_read()] + change = ["--single-select-option-id", _p("option_id")] + edit = self._edit(subject, field_name or _p("field"), change, "set_field") + head, card = self.kept_fields(), self.card(subject) if field_name == "Release": - return [*head, *listing, self._record(subject), patch] + return [*head, *listing, *card, self._record(subject), patch] if field_name is not None: - return [*head, self._record(subject), edit] + return [*head, *card, self._record(subject), edit] return [ *head, *within(listing, release), + *card, self._record(subject), *within([patch], release), *within([edit], other), @@ -348,8 +361,13 @@ def label_issue(self, subject: str) -> Requests: return [self.gh(args, "label", subject=subject)] def add_item(self, subject: str) -> Requests: + """The issue, the add, which names the card, then that card.""" args = gh.item_add_args(self.owner, self.number, _p("url")) - return [*self.issue(subject), self.gh(args, "add_item", subject=subject)] + return [ + *self.issue(subject), + self.gh(args, "add_item", subject=subject), + *self.card(subject), + ] def create_issue(self, subject: str, labels: Sequence[str] = ()) -> Requests: args = gh.create_issue_args(self.repo, _p("title"), _p("body"), labels) @@ -370,28 +388,27 @@ def close_as_duplicate(self, subject: str) -> Requests: ] def set_run_record(self) -> Requests: - """The board, its fields and items, the card created when there is none, then the job - record.""" + """The board's fields and items once a run, the card, or the card created when there is + none, which nothing reads after, then the job record.""" texts = MESSAGES.roadmap + cond, run_record = texts.plan_conditions, texts.plan_targets["run_record"] create = self.gh(gh.run_record_card_args(self.owner, self.number), "create_card") edit = gh.card_edit_args( _p("card_id"), _p("board_id"), _p("field_id"), ["--text", _p("record")] ) return [ - *self.find_board(), - *self.board_fields(), - *self.board_read(), - *within([create, *self.board_read()], texts.plan_conditions["no_card"]), + *self.kept_fields(), + *self.kept_board(), + *within(self.card(run_record), cond["run_card"]), + *within([create], cond["no_card"]), self.gh( - edit, - "card_field", - subject=texts.plan_targets["run_record"], - field=CONST_GH_PROJECT_JOB_RECORD_FIELD, + edit, "card_field", subject=run_record, field=CONST_GH_PROJECT_JOB_RECORD_FIELD ), ] def set_card_field(self) -> Requests: - """The board, its fields and items, then the field and the job record by node ids.""" + """The board's fields once a run, the card, then the field and the job record by node + ids.""" card, field_name = _p("card"), _p("field") change = ["--single-select-option-id", _p("option_id")] field_edit = gh.card_edit_args(_p("card_id"), _p("board_id"), _p("field_id"), change) @@ -399,9 +416,8 @@ def set_card_field(self) -> Requests: _p("card_id"), _p("board_id"), _p("field_id"), ["--text", _p("record")] ) return [ - *self.find_board(), - *self.board_fields(), - *self.board_read(), + *self.kept_fields(), + *self.card(card), self.gh(field_edit, "card_field", subject=card, field=field_name), self.gh( record_edit, "card_field", subject=card, field=CONST_GH_PROJECT_JOB_RECORD_FIELD @@ -409,8 +425,10 @@ def set_card_field(self) -> Requests: ] def remove_card(self) -> Requests: + """The card, then its removal.""" args = gh.item_delete_args(self.owner, self.number, _p("card_id")) - return [*self.board_read(), self.gh(args, "remove_card", subject=_p("card"))] + card = _p("card") + return [*self.card(card), self.gh(args, "remove_card", subject=card)] def delete_field(self) -> Requests: args = gh.field_delete_args(_p("field_id")) diff --git a/src/devops_cli/roadmap/run.py b/src/devops_cli/roadmap/run.py index 824a74b05e..fac7ee11fc 100644 --- a/src/devops_cli/roadmap/run.py +++ b/src/devops_cli/roadmap/run.py @@ -679,14 +679,13 @@ def _fetch_filtered_changes( store: RoadmapStore, current_time: datetime, ) -> list[Change]: - """Fetch recent store changes excluding writes authored by the current session.""" + """Fetch recent store changes excluding writes authored by the current session, which the + store leaves out before it reads any job record (#1361).""" has_poll = any(src == "poll" for (src, _evt, _act) in active_batch) if not has_poll and not any(r.change_predicate is not None for r in rows): return [] cutoff = _oldest_cutoff(rows, schedule, current_time) - raw_changes = store.changes_since(cutoff) - ignored = _current_actor(store) - return [c for c in raw_changes if not (c.actor and ignored and c.actor == ignored)] + return store.changes_since(cutoff, except_actor=_current_actor(store)) def _simulate_dry_run( diff --git a/src/devops_cli/roadmap/store.py b/src/devops_cli/roadmap/store.py index 7d7bb5e87e..cfefe5fa92 100644 --- a/src/devops_cli/roadmap/store.py +++ b/src/devops_cli/roadmap/store.py @@ -3,9 +3,18 @@ An Item is an issue of this repository that is on the board. A Release is a milestone whose title parses as a version. A Candidate is an open issue of this repository that is not on the board yet. A Card is anything on the board: an Item, a pull request, a draft issue or another -repository's issue. Both adapters keep the same promises: reads page through every result, a -read that can't complete raises instead of returning an empty or partial result, and no read is -cached. +repository's issue. Both adapters keep the same promises: reads page through every result, and a +read that can't complete raises instead of returning an empty or partial result. + +A store lives for one command or one Service round (#1361). It reads the board's fields once, +and the board listing once for each Projects filter, when first needed, and its own writes keep +that listing current with the values they sent and the cards they add; a close drops it, as the +board's own workflow changes a closed issue's card, and a change someone else makes meanwhile is +seen by the next store (ADR 0003). A write never trusts the listing: it reads the one card it +writes, by the card's node id, so it joins the job record the card holds then, and a job's write +of a field someone changed since the store read it raises `RoadmapCardChangedError` before it +changes anything, unless the card already holds the value it writes, so a job never reverts a +change it did not see (ADR 0002). Every Item and Card field write also records the value it set in the card's job record, so a job can tell a person's change from its own by comparing a field with its record (ADR 0002). @@ -28,7 +37,9 @@ from devops_cli.config.constants import CONST_GH_PROJECT_JOB_RECORD_FIELD from devops_cli.config.defaults import DEFAULT_GH_PROJECT_OPTION_COLOR, DEFAULT_RELEASE_LABEL from devops_cli.exceptions.git import GitHubOperationError +from devops_cli.exceptions.roadmap import RoadmapCardChangedError from devops_cli.exceptions.validation import InvalidVersionError +from devops_cli.lang import MESSAGES if TYPE_CHECKING: from devops_cli.roadmap.board_read import GraphQLSpend @@ -240,7 +251,9 @@ class Item(BaseModel): State, labels and Release come from the issue; Status, Priority, Value and Effort from the board. The job record holds the last value the store set for each field; a field missing - from it was never set by a job. + from it was never set by a job. `card_id` is the node id of the Item's card, which every + Item a store reads or adds carries and a store writes it by; an Item built as a probe has + none, and a write to it raises. """ model_config = ConfigDict(frozen=True) @@ -248,6 +261,7 @@ class Item(BaseModel): number: int title: str url: str + card_id: str | None = None state: GitHubState = GitHubState.OPEN state_reason: str | None = None labels: tuple[str, ...] = () @@ -347,11 +361,13 @@ class Evidence(BaseModel): class BoardEntry(BaseModel): - """What the board holds for one issue of this repository: its fields and job record.""" + """What the board holds for one issue of this repository: its card's node id, its fields + and its job record.""" model_config = ConfigDict(frozen=True) number: int + card_id: str status: str | None = None priority: str | None = None value: str | None = None @@ -604,6 +620,40 @@ def require_option( ) +def require_unchanged( + card: str, + field: ItemField, + read: Collection[str | None], + now: str | None, + value: str | None, + operation: str, +) -> None: + """Refuse a job's write of `value` to `field` on `card` when the card holds `now` but the + store read another value (`read` holds each value it read, its own writes included): the + job planned without that change, so the write would revert it (ADR 0002). Writing the value + the card holds now reverts nothing, such as the Status the board sets on a card just added. + """ + if set(read) == {now} or value == now: + return + texts = MESSAGES.roadmap + before = min(set(read) - {now}, key=str) + raise RoadmapCardChangedError( + texts.card_changed.format( + card=card, + field=field.value, + now=now or texts.card_value_unset, + read=before or texts.card_value_unset, + ), + operation=operation, + details={ + "card": card[:256], + "field": field.value, + "read": before and before[:256], + "now": now and now[:256], + }, + ) + + def field_options(fields: Iterable[BoardField]) -> dict[str, tuple[str, ...]]: """Each board field's option names by field name; a field that isn't single-select has none.""" return {field.name: tuple(option.name for option in field.options) for field in fields} @@ -720,11 +770,14 @@ def backlog(self) -> list[Item]: def candidates(self) -> list[Candidate]: """The open issues of the repository that are not on the board.""" - def changes_since(self, since: datetime) -> list[Change]: - """The Item changes made at or after `since`, oldest first.""" + def changes_since(self, since: datetime, *, except_actor: str | None = None) -> list[Change]: + """The Item changes made at or after `since`, oldest first, leaving out those + `except_actor` made; those cost no read of the board.""" - def add_item(self, number: int) -> None: - """Put issue `number` on the board, raising if it is not an issue of this repository.""" + def add_item(self, number: int) -> Item: + """Put issue `number` on the board and return it as the Item its card makes it, raising + if it is not an issue of this repository. An issue already on the board keeps its card, + which is returned.""" def set_field( self, @@ -741,10 +794,11 @@ def set_field( record of the job's value: by the record alone, a write that stops between the two reads as the job's value a person changed since, so a job that has to tell the two apart also reads whether the field changed. A board field takes one of its board - options; the Release takes an existing Release's version. Anything else, or an Item no - longer on the board, raises before the store changes anything. The record keeps what - the store set for the Item's other fields, even when `item` was read before an earlier - write. + options; the Release takes an existing Release's version. Anything else, an Item no + longer on the board, or a board field someone changed since the store read the card, + unless the card already holds `value`, raises before the store changes anything. The + record keeps what the store set for the Item's other fields, even when `item` was read + before an earlier write. """ def delete_release(self, version: str) -> None: @@ -757,7 +811,9 @@ def create_issue(self, title: str, body: str, *, labels: Sequence[str] = ()) -> """Open an issue with `title`, `body` and `labels`, returning it.""" def close_issue(self, number: int, reason: CloseReason, comment: str) -> None: - """Comment on issue `number`, then close it for `reason`, raising if it is not an issue.""" + """Comment on issue `number`, then close it for `reason`, raising if it is not an issue. + The store's next board read reads the board again, so it shows the card as the board's + own workflow leaves a closed issue's.""" def read_issue_body(self, number: int) -> str: """The body of issue `number`, raising if it is not an issue of this repository.""" @@ -800,7 +856,9 @@ def set_card_field(self, card: Card, field: ItemField, value: str | None) -> Non """Set or clear a board field on any card, then record the value in its job record. The Release is not a board field and raises; so do a value that is not one of the - field's options and a card no longer on the board, before the store changes anything. + field's options, a card no longer on the board, and a field someone changed since the + store read the card, unless the card already holds `value`, before the store changes + anything. """ def remove_card(self, card: Card) -> None: @@ -881,7 +939,8 @@ def comments_on(self, number: int) -> list[str]: def close_as_duplicate(self, number: int, original: int, comment: str | None) -> None: """Comment on issue `number` unless `comment` is None (a retry whose comment is already there), then close it as a duplicate of issue `original`, raising if either is not an - issue of this repository.""" + issue of this repository. The store's next board read reads the board again, as after + `close_issue`.""" def closures(self, number: int) -> list[Closure]: """Every close and reopen of issue `number`, oldest first, from its timeline.""" @@ -982,6 +1041,7 @@ def get_roadmap_store( "require_new_release", "require_option", "require_release", + "require_unchanged", "select_candidates", "with_marks", ] diff --git a/tests/fixtures/roadmap/github-schema-board.graphql b/tests/fixtures/roadmap/github-schema-board.graphql index 27cfd06cc7..5708f56955 100644 --- a/tests/fixtures/roadmap/github-schema-board.graphql +++ b/tests/fixtures/roadmap/github-schema-board.graphql @@ -1,4 +1,4 @@ -# The types of GitHub's public GraphQL schema that the roadmap board reads use (#1125), +# The types of GitHub's public GraphQL schema that the roadmap board reads use (#1125, #1361), # cut from https://docs.github.com/public/fpt/schema.docs.graphql (downloaded 2026-10-04): # each type keeps the fields the documents in devops_cli.roadmap.board_read select, the # fields of the interfaces it implements, and the input types and enums their arguments take. @@ -20,6 +20,10 @@ type Issue implements ProjectV2Owner { url: URI! } +interface Node { + id: ID! +} + enum OrderDirection { ASC DESC @@ -50,10 +54,11 @@ interface ProjectV2FieldCommon { union ProjectV2FieldConfiguration = ProjectV2Field | ProjectV2IterationField | ProjectV2MultiSelectField | ProjectV2SingleSelectField -type ProjectV2Item { +type ProjectV2Item implements Node { content: ProjectV2ItemContent fieldValues(after: String, before: String, first: Int, last: Int, orderBy: ProjectV2ItemFieldValueOrder = { field: POSITION, direction: ASC }): ProjectV2ItemFieldValueConnection! id: ID! + isArchived: Boolean! } enum ProjectV2ItemArchivedState { @@ -136,6 +141,7 @@ type PullRequest implements ProjectV2Owner { } type Query { + node(id: ID!): Node rateLimit(dryRun: Boolean = false): RateLimit repositoryOwner(login: String!): RepositoryOwner } diff --git a/tests/roadmap_board_fake.py b/tests/roadmap_board_fake.py index aedeff6022..641b165040 100644 --- a/tests/roadmap_board_fake.py +++ b/tests/roadmap_board_fake.py @@ -1,19 +1,36 @@ -"""A fake GitHub answering the roadmap store's GraphQL board reads (#1125). +"""A fake GitHub answering the roadmap store's `gh` commands (#1125, #1361). `BoardServer` holds a board listed as `gh project item-list` lists it (the recorded fixtures keep that shape) and answers `RoadmapBoardBudget` and `RoadmapBoardItems` as GraphQL would: archived items left out, `is:open` honoured from each item's `content.state`, a page at a time by cursor, -each answer carrying `rateLimit` with the points it cost and the points left. It starts no `gh` -and opens no socket. +each answer carrying `rateLimit` with the points it cost and the points left. It answers +`RoadmapBoardCard` by node id, archived items included, and a node id it doesn't hold as GitHub +does: a null node with a `NOT_FOUND` error, `gh` exiting 1. A card in `lagging` is left out of +that many listings, as GitHub's listing showed a new card up to two minutes after its add. + +`GitHubFake` is a whole repository and its board at the `gh` process edge: REST issues, +milestones, labels, comments, events and files, the board's fields, and the `gh project` +writes, each applied to what later reads return. It keeps every argv, and charges each GraphQL +request the points GitHub's own estimate (`rateLimit(dryRun: true)`, board #2, 2026-10-08) gives +its shape (`GRAPHQL_POINTS`). Closing an issue runs the board's built-in "Item closed" workflow, +which sets its card's Status to Done. Neither starts `gh` or opens a socket. """ from __future__ import annotations -from collections.abc import Callable +import json +import subprocess +from collections.abc import Callable, Iterable from copy import deepcopy from typing import Any +from urllib.parse import parse_qs, unquote, urlsplit -from devops_cli.roadmap.board_read import BOARD_BUDGET_OPERATION, BOARD_ITEMS_OPERATION +from devops_cli.roadmap.board_read import ( + BOARD_BUDGET_OPERATION, + BOARD_CARD_OPERATION, + BOARD_ITEMS_OPERATION, + item_list_key, +) BOARD_READ = "RoadmapBoard" """The reply key a `RecordedGh` matches both board queries by.""" @@ -32,7 +49,7 @@ def gh_variables(args: list[str]) -> dict[str, str]: def graphql_node(entry: dict[str, Any]) -> dict[str, Any]: - """An item-list entry as a `ProjectV2Item` node.""" + """An item-list entry as a `ProjectV2Item` node, `isArchived` included.""" content = deepcopy(entry.get("content") or {}) content["__typename"] = content.pop("type", "DraftIssue") if isinstance(content.get("repository"), str): @@ -45,7 +62,12 @@ def graphql_node(entry: dict[str, Any]) -> dict[str, Any]: for key, value in entry.items() if key not in _NOT_FIELDS and isinstance(value, str) ] - return {"id": entry["id"], "content": content, "fieldValues": {"nodes": values}} + return { + "id": entry["id"], + "isArchived": bool(entry.get("isArchived")), + "content": content, + "fieldValues": {"nodes": values}, + } class BoardServer: @@ -59,6 +81,7 @@ def __init__( remaining: int = 5000, page_cost: int = 1, probe_cost: int = 1, + card_cost: int = 1, on_page: Callable[[BoardServer, int], None] | None = None, ) -> None: self._source = listing @@ -67,19 +90,28 @@ def __init__( self.remaining = remaining self.page_cost = page_cost self.probe_cost = probe_cost + self.card_cost = card_cost self.on_page = on_page self.pages = 0 self.spent = 0 + # Card ids the next listings leave out, with how many listings each is left out of. + self.lagging: dict[str, int] = {} def selected(self, board_filter: str) -> list[dict[str, Any]]: - """The items a read of `board_filter` sees: not archived, and open for `is:open`.""" + """The items a read of `board_filter` sees: not archived, not lagging, and open for + `is:open`.""" return [ entry for entry in self.listing["items"] if not entry.get("isArchived") + and not self.lagging.get(entry["id"]) and ("is:open" not in board_filter or entry["content"].get("state", "OPEN") == "OPEN") ] + def entry(self, card_id: str) -> dict[str, Any] | None: + """The listing's entry for `card_id`, archived or not.""" + return next((entry for entry in self.listing["items"] if entry["id"] == card_id), None) + def total(self, board_filter: str) -> int: """The filter's total; a listing whose `totalCount` exceeds its items keeps the gap.""" gap: int = max(0, int(self.listing.get("totalCount", 0)) - len(self.listing["items"])) @@ -96,12 +128,15 @@ def _rate_limit(self, cost: int) -> dict[str, Any]: "resetAt": RESET_AT, } - def __call__(self, args: list[str]) -> dict[str, Any]: + def __call__(self, args: list[str]) -> Any: variables = gh_variables(args) + if BOARD_CARD_OPERATION in variables["query"]: + return self._card(variables["id"]) board_filter = variables["filter"] if BOARD_BUDGET_OPERATION in variables["query"]: if callable(self._source): self.listing = deepcopy(self._source()) + self.lagging = {card: left - 1 for card, left in self.lagging.items() if left > 1} items = {"totalCount": self.total(board_filter), "nodes": []} return self._answer(self.probe_cost, items) assert BOARD_ITEMS_OPERATION in variables["query"] @@ -129,6 +164,20 @@ def _answer(self, cost: int, items: dict[str, Any]) -> dict[str, Any]: } } + def _card(self, card_id: str) -> Any: + """One card by node id; one this board doesn't hold answers as GitHub does, exit 1.""" + if callable(self._source) and not self.listing: + self.listing = deepcopy(self._source()) + found = self.entry(card_id) + node = graphql_node(found) if found is not None else None + answer: dict[str, Any] = {"data": {"rateLimit": self._rate_limit(self.card_cost)}} + answer["data"]["node"] = node + if found is not None: + return answer + message = f"Could not resolve to a node with the global id of '{card_id}'" + answer["errors"] = [{"type": "NOT_FOUND", "path": ["node"], "message": message}] + return (1, json.dumps(answer)) + def budget_reply(remaining: int, *, cost: int = 1) -> dict[str, Any]: """The answer to `RoadmapGraphQLBudget`.""" @@ -145,8 +194,353 @@ def budget_reply(remaining: int, *, cost: int = 1) -> dict[str, Any]: def board_page_reply(entries: list[dict[str, Any]]) -> str: """The JSON answer to a one-page `RoadmapBoardItems` read holding `entries`, listed as `gh project item-list` lists them.""" - import json - items = {"items": entries, "totalCount": len(entries)} board_filter_args = ["-f", "query=query RoadmapBoardItems", "-f", "filter=", "-F", "first=100"] return json.dumps(BoardServer(items)(board_filter_args)) + + +# ── A whole repository and its board ────────────────────────────────────────── + +GRAPHQL_POINTS: dict[str, int] = { + "mutation": 1, + "query": 1, + "name_resolution": 101, +} +"""What GitHub's own estimate gives each GraphQL request shape on board #2 (2026-10-08, #1361): +a query that pages no board items, such as the fields, a one-card read or a page of the store's +board query, and a mutation cost about 1 point. `gh project field-list`, and `gh project +item-edit` given `--url` or `--field`, first fetch the board's first 100 items with all their +field values (`ProjectFields`, `firstItems` 100): about 101 more. `gh project item-add` and +`item-create` are charged as one mutation, though gh first resolves the board's owner and the +board, and for an add the issue, with small queries of its own that this fake leaves out, so its +totals for a placement are a floor of a few points under GitHub's.""" + +BOARD_ID = "PVT_board" +OPTIONS: dict[str, tuple[str, ...]] = { + "Status": ("New", "Ready", "In Progress", "In Review", "Done", "Blocked"), + "Priority": ("P0-Critical", "P1-High", "P2-Medium", "P3-Low"), + "Value": ("High", "Medium", "Low"), + "Effort": ("Low", "Medium", "High"), +} +JOB_RECORD = "Job record" + + +def field_id(name: str) -> str: + """The node id `GitHubFake` gives the board field `name`.""" + return f"PVTF_{name.replace(' ', '_').lower()}" + + +def option_id(field: str, name: str) -> str: + """The node id `GitHubFake` gives option `name` of field `field`.""" + return f"{field_id(field)}/{name.replace(' ', '_')}" + + +def fields_reply(board_id: str = BOARD_ID) -> dict[str, Any]: + """The answer to the store's fields query: Status, Priority, Value, Effort and the job + record, with the board's node id.""" + nodes: list[dict[str, Any]] = [ + { + "id": field_id(name), + "name": name, + "dataType": "SINGLE_SELECT", + "options": [{"id": option_id(name, option), "name": option} for option in options], + } + for name, options in OPTIONS.items() + ] + nodes.append({"id": field_id(JOB_RECORD), "name": JOB_RECORD, "dataType": "TEXT"}) + connection = {"totalCount": len(nodes), "nodes": nodes} + return {"data": {"repositoryOwner": {"projectV2": {"id": board_id, "fields": connection}}}} + + +def _flags(args: list[str]) -> dict[str, str]: + """A `gh` argv's `--name value` flags, and each bare `--flag` as an empty value.""" + flags: dict[str, str] = {} + for index, arg in enumerate(args): + if arg.startswith("--"): + following = args[index + 1] if index + 1 < len(args) else "--" + flags[arg] = "" if following.startswith("--") else following + return flags + + +class GitHubFake: + """One repository's issues, milestones and board, answering the store's `gh` commands. + + `issues` maps a number to its REST payload; `on_board` numbers start as cards with the + given `cards` fields. `lag` is how many board listings leave a card just added out. + """ + + def __init__( + self, + repo: str, + *, + milestones: Iterable[dict[str, Any]] = (), + files: dict[str, str] | None = None, + events: Iterable[dict[str, Any]] = (), + lag: int = 0, + commits: Iterable[str] = (), + ) -> None: + self.repo = repo + self.milestones = list(milestones) + self.files = dict(files or {}) + self.events = list(events) + self.commits = set(commits) + self.lag = lag + self.issues: dict[int, dict[str, Any]] = {} + self.comments: dict[int, list[str]] = {} + self.board = BoardServer({"items": [], "totalCount": 0}) + self.calls: list[list[str]] = [] + self.points = 0 + + # ── Seeding ── + + def seed_issue( + self, + number: int, + title: str = "", + *, + state: str = "open", + labels: Iterable[str] = (), + milestone: str | None = None, + card: dict[str, str] | None = None, + ) -> None: + """Issue `number`, and its card holding `card`'s fields when it is on the board.""" + self.issues[number] = { + "number": number, + "title": title or f"Issue {number}", + "html_url": f"https://github.com/{self.repo}/issues/{number}", + "body": "", + "state": state, + "labels": [{"name": label} for label in labels], + "milestone": self._milestone(milestone), + "node_id": f"I_{number}", + "author_association": "COLLABORATOR", + "created_at": "2026-10-01T00:00:00Z", + } + if card is not None: + self._put_card(number, card) + + def card_id(self, number: int) -> str: + return f"PVTI_{number}" + + def card(self, number: int) -> dict[str, Any] | None: + """Issue `number`'s board entry, as the listing holds it.""" + return self.board.entry(self.card_id(number)) + + def graphql_calls(self, *names: str) -> list[list[str]]: + """The GraphQL requests sent, only those naming one of `names` when given.""" + graphql = [args for args in self.calls if args[:2] == ["api", "graphql"]] + graphql += [args for args in self.calls if args[0] == "project"] + return [args for args in graphql if not names or any(n in " ".join(args) for n in names)] + + # ── The process edge ── + + def __call__(self, args: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]: + self.calls.append(args) + reply = self._answer(args, kwargs.get("input")) + returncode, output = reply if isinstance(reply, tuple) else (0, reply) + text = output if isinstance(output, str) else json.dumps(output) + return subprocess.CompletedProcess(args, returncode, text, "" if returncode == 0 else text) + + def _answer(self, args: list[str], stdin: str | None) -> Any: + if args[0] == "project": + return self._project(args) + if args[:2] == ["api", "graphql"]: + return self._graphql(args, stdin) + assert args[0] == "api", f"not a gh command the store sends: {args}" + return self._rest(args) + + def _graphql(self, args: list[str], stdin: str | None) -> Any: + query = stdin or gh_variables(args).get("query", "") + if "RoadmapBoard" in query: + before = self.board.spent + reply = self.board(args) + self.points += self.board.spent - before + return reply + self.points += GRAPHQL_POINTS["query"] + answers: list[tuple[str, Callable[[], Any]]] = [ + ("RoadmapGraphQLBudget", lambda: budget_reply(self.board.remaining)), + ("fields(first", fields_reply), + ("timelineItems", self._timeline), + ("defaultBranchRef", self._default_branch), + ("milestone(number", self._release_pull_requests), + ("closeIssue", lambda: self._close_as_duplicate(stdin or "")), + ] + found = next((answer for key, answer in answers if key in query), None) + assert found is not None, f"no fake for the GraphQL request: {query[:120]}" + return found() + + def _timeline(self) -> dict[str, Any]: + connection = {"totalCount": 0, "nodes": []} + return {"data": {"repository": {"issue": {"timelineItems": connection}}}} + + def _default_branch(self) -> dict[str, Any]: + branch = {"name": "main", "target": {"oid": "a" * 40}} + return {"data": {"repository": {"defaultBranchRef": branch}}} + + def _release_pull_requests(self) -> dict[str, Any]: + connection = {"totalCount": 0, "nodes": []} + return {"data": {"repository": {"milestone": {"pullRequests": connection}}}} + + # ── gh project ── + + def _project(self, args: list[str]) -> Any: + flags, command = _flags(args), args[1] + named = command == "field-list" or ( + command == "item-edit" and ("--url" in flags or "--field" in flags) + ) + self.points += GRAPHQL_POINTS["mutation"] + named * GRAPHQL_POINTS["name_resolution"] + assert not named, f"a board command gh resolves by reading 100 items first: {args}" + if command == "item-add": + number = int(flags["--url"].rsplit("/", 1)[1]) + card = self.card(number) or self._put_card(number, {}, lag=self.lag) + return {"id": card["id"], "title": card["content"]["title"], "type": "Issue"} + if command == "item-edit": + return self._edit(flags) + if command == "item-create": + card = { + "id": "PVTI_draft", + "content": {"type": "DraftIssue", "title": flags["--title"]}, + } + self.board.listing["items"].append(card) + return {"id": card["id"], "title": flags["--title"], "type": "DraftIssue"} + raise AssertionError(f"no fake for: {args}") + + def _edit(self, flags: dict[str, str]) -> str: + assert flags["--project-id"] == BOARD_ID, flags + entry = self.board.entry(flags["--id"]) + assert entry is not None, f"no card {flags['--id']}" + names = {field_id(name): name for name in (*OPTIONS, JOB_RECORD)} + key = item_list_key(names[flags["--field-id"]]) + if "--clear" in flags: + entry.pop(key, None) + elif "--text" in flags: + entry[key] = flags["--text"] + else: + entry[key] = flags["--single-select-option-id"].split("/", 1)[1].replace("_", " ") + return "" + + def _put_card(self, number: int, fields: dict[str, str], *, lag: int = 0) -> dict[str, Any]: + issue = self.issues[number] + content = { + "type": "Issue", + "number": number, + "repository": self.repo, + "title": issue["title"], + "url": issue["html_url"], + "state": issue["state"].upper(), + } + card: dict[str, Any] = {"id": self.card_id(number), "content": content, **fields} + self.board.listing["items"].append(card) + self.board.listing["totalCount"] = len(self.board.listing["items"]) + if lag: + self.board.lagging[card["id"]] = lag + return card + + # ── REST ── + + def _rest(self, args: list[str]) -> Any: + method = args[args.index("-X") + 1] if "-X" in args else "GET" + path = next(arg for arg in args[1:] if "/" in arg and not arg.startswith(("-", "Accept"))) + fields = dict( + args[index + 1].split("=", 1) + for index, arg in enumerate(args) + if arg in ("-f", "-F") and "=" in args[index + 1] + ) + url = urlsplit(path) + query = {key: values[0] for key, values in parse_qs(url.query).items()} + parts = url.path.removeprefix(f"repos/{self.repo}/").split("/") + return self._rest_route(method, url.path, parts, query, fields, args) + + def _rest_route( + self, + method: str, + path: str, + parts: list[str], + query: dict[str, str], + fields: dict[str, str], + args: list[str], + ) -> Any: + page = int(query.get("page", "1")) + if path == "search/issues": + return {"total_count": 0, "incomplete_results": False} + if parts[0] == "contents": + name = unquote("/".join(parts[1:])) + return self.files[name] if name in self.files else (1, "gh: Not Found (HTTP 404)") + if parts[0] == "commits": + return {"sha": parts[1]} if parts[1] in self.commits else (1, "HTTP 422") + if parts[0] == "releases": + return (1, "gh: Not Found (HTTP 404)") + if parts[0] == "milestones": + return self.milestones if page == 1 else [] + if parts == ["issues", "events"]: + return self.events[(page - 1) * 100 : page * 100] + if parts == ["issues"]: + labels = [arg.split("=", 1)[1] for arg in args if arg.startswith("labels[]=")] + return self._issues(method, query, fields | {"labels": json.dumps(labels)}, page) + return self._issue_route(method, int(parts[1]), parts[2:], fields, page) + + def _issues(self, method: str, query: dict[str, str], fields: dict[str, str], page: int) -> Any: + if method == "POST": + number = max(self.issues, default=0) + 1 + self.seed_issue(number, fields["title"], labels=json.loads(fields["labels"])) + self.issues[number]["body"] = fields.get("body", "") + return self.issues[number] + listed = [ + issue + for issue in self.issues.values() + if query.get("state", "open") in ("all", issue["state"]) + and self._in_milestone(issue, query.get("milestone")) + ] + return listed[(page - 1) * 100 : page * 100] + + def _issue_route( + self, method: str, number: int, rest: list[str], fields: dict[str, str], page: int + ) -> Any: + issue = self.issues[number] + if rest == ["labels"]: + issue["labels"].append({"name": fields["labels[]"]}) + return issue["labels"] + if rest == ["comments"] and method == "POST": + self.comments.setdefault(number, []).append(fields["body"]) + return {} + if rest == ["comments"]: + bodies = self.comments.get(number, []) if page == 1 else [] + return [{"body": body} for body in bodies] + if method == "PATCH" and "milestone" in fields: + title = next( + (m["title"] for m in self.milestones if str(m["number"]) == fields["milestone"]), + None, + ) + issue["milestone"] = self._milestone(title) + if method == "PATCH" and fields.get("state") == "closed": + self.close(number, fields["state_reason"]) + return issue + + def close(self, number: int, reason: str) -> None: + """Close issue `number` for `reason`, and let the board's built-in "Item closed" + workflow set its card's Status to Done, as GitHub does after a close.""" + self.issues[number].update(state="closed", state_reason=reason) + card = self.card(number) + if card is not None: + card["content"]["state"] = "CLOSED" + card["status"] = "Done" + + def _close_as_duplicate(self, stdin: str) -> dict[str, Any]: + """The `closeIssue` mutation that closes an issue as a duplicate of another.""" + issue_id = json.loads(stdin)["variables"]["issue"] + number = next(n for n, issue in self.issues.items() if issue["node_id"] == issue_id) + self.close(number, "duplicate") + return {"data": {"closeIssue": {"issue": {"number": number}}}} + + def _milestone(self, title: str | None) -> dict[str, Any] | None: + found = next((m for m in self.milestones if m["title"] == title), None) + return {"number": found["number"], "title": title} if found else None + + @staticmethod + def _in_milestone(issue: dict[str, Any], milestone: str | None) -> bool: + held = issue["milestone"] + if milestone is None: + return True + if milestone == "none": + return held is None + return held is not None and str(held["number"]) == milestone diff --git a/tests/test_roadmap_board_read.py b/tests/test_roadmap_board_read.py index 614c882ecb..a6343ca6cd 100644 --- a/tests/test_roadmap_board_read.py +++ b/tests/test_roadmap_board_read.py @@ -25,11 +25,13 @@ from devops_cli.github.rate_limiter import get_github_rate_limiter, reset_github_rate_limiter from devops_cli.roadmap.board_read import ( BOARD_BUDGET_QUERY, + BOARD_CARD_QUERY, BOARD_ITEMS_QUERY, GRAPHQL_BUDGET_QUERY, GraphQLBudget, GraphQLSpend, board_budget_args, + board_card_args, board_items_args, graphql_budget_args, spend_between, @@ -121,18 +123,19 @@ def test_every_board_document_is_valid_against_githubs_schema() -> None: """The documents are fixed templates; GitHub's schema, cut to the types they use, accepts each of them and rejects a field it doesn't define.""" schema = build_schema(SCHEMA.read_text(encoding="utf-8")) - documents = [BOARD_ITEMS_QUERY, BOARD_BUDGET_QUERY, GRAPHQL_BUDGET_QUERY] + documents = [BOARD_ITEMS_QUERY, BOARD_BUDGET_QUERY, BOARD_CARD_QUERY, GRAPHQL_BUDGET_QUERY] misspelled = BOARD_ITEMS_QUERY.replace("archivedStates", "archived") assert ( [validate(schema, parse(document)) for document in documents], len(validate(schema, parse(misspelled))), - ) == ([[], [], []], 1) + ) == ([[], [], [], []], 1) def test_the_argument_builders_send_the_filter_the_cursor_and_typed_numbers() -> None: """A request plan lists these same argv; the filter goes as a string, the numbers typed.""" first = board_items_args(OWNER, 2, "is:open") later = board_items_args(OWNER, 2, "", after="Y3Vyc29y") + card = board_card_args("PVTI_7") assert ( first[:3], {key: value for key, value in gh_variables(first).items() if key != "query"}, @@ -141,6 +144,7 @@ def test_the_argument_builders_send_the_filter_the_cursor_and_typed_numbers() -> "archivedStates: [NOT_ARCHIVED]" in gh_variables(first)["query"], gh_variables(board_budget_args(OWNER, 2, "is:open"))["filter"], graphql_budget_args()[:3], + {key: value for key, value in gh_variables(card).items() if key != "query"}, ) == ( ["api", "graphql", "-f"], {"owner": OWNER, "filter": "is:open", "number": "2", "first": "100", "fieldValues": "100"}, @@ -149,6 +153,7 @@ def test_the_argument_builders_send_the_filter_the_cursor_and_typed_numbers() -> True, "is:open", ["api", "graphql", "-f"], + {"id": "PVTI_7", "fieldValues": "100"}, ) @@ -156,7 +161,8 @@ def test_the_argument_builders_send_the_filter_the_cursor_and_typed_numbers() -> def test_each_read_passes_its_filter_at_the_source() -> None: - """The job's filter for its whole-board reads, `is:open` for the backlog and candidates.""" + """The job's filter for its whole-board reads, `is:open` for the backlog and candidates, + which share that one read of the store (#1361).""" board = board_of(3, 2) store, gh = store_over( { @@ -178,8 +184,6 @@ def test_each_read_passes_its_filter_at_the_source() -> None: "", "is:open", "is:open", - "is:open", - "is:open", "-status:Done", "-status:Done", ] @@ -263,7 +267,7 @@ def _fields_reply() -> dict[str, Any]: } record = {"id": "PVTF_jobrecord", "name": "Job record", "dataType": "TEXT"} connection = {"totalCount": 2, "nodes": [status, record]} - return {"data": {"repositoryOwner": {"projectV2": {"fields": connection}}}} + return {"data": {"repositoryOwner": {"projectV2": {"id": "PVT_board", "fields": connection}}}} def _rest_pages(listing: list[dict[str, Any]]) -> Callable[[list[str]], Any]: @@ -277,10 +281,10 @@ def page(args: list[str]) -> Any: def test_a_reprioritize_run_on_a_board_of_931_items_charges_its_pages() -> None: """The board of 2026-10-04: 931 items, 280 of them open, one more archived. Through `run_gh`, - with gh's process stubbed, the run charges the GraphQL points its board reads report: two - reads (the items, then the run record), each one budget query and ten pages of 100. The - same run through `gh project item-list` cost 2,025 points while the limiter counted one call - per read. The run ends with the points spent and left, read from GraphQL.""" + with gh's process stubbed, the run charges the GraphQL points its board read reports: one + read, one budget query and ten pages of 100, which the items and the run record share + (#1361). The same run through `gh project item-list` cost 2,025 points while the limiter + counted one call per read. The run ends with the points spent and left, read from GraphQL.""" board = board_of(280, 651, archived=1) server = BoardServer(board) gh = Gh( @@ -326,7 +330,7 @@ def test_a_reprioritize_run_on_a_board_of_931_items_charges_its_pages() -> None: server.pages, charged, (spend.spent, spend.remaining), - ) == (None, [""] * 22, 20, 23, (23, 4977)) + ) == (None, [""] * 11, 10, 12, (12, 4988)) # ── The spend line ──────────────────────────────────────────────────────────── diff --git a/tests/test_roadmap_dry_runs.py b/tests/test_roadmap_dry_runs.py index fddb42d2e9..197337d809 100644 --- a/tests/test_roadmap_dry_runs.py +++ b/tests/test_roadmap_dry_runs.py @@ -26,6 +26,7 @@ from devops_cli.commands.roadmap import app from devops_cli.config.constants import CONST_ROADMAP_RENDER_BOARD_FILTER from devops_cli.dry_run.requests import PlannedRequest +from devops_cli.lang import MESSAGES from devops_cli.roadmap import store as roadmap_store_module from devops_cli.roadmap.board_read import board_budget_args, board_items_args from devops_cli.roadmap.config import open_roadmap @@ -42,7 +43,14 @@ dry_run_reprioritization, plan_reprioritization, ) -from devops_cli.roadmap.request_plan import is_page_repeat +from devops_cli.roadmap.request_plan import ( + StoreRequests, + close_requests, + is_page_repeat, + migrate_requests, + render_requests, + reprioritize_requests, +) from tests.roadmap_board_fake import BOARD_READ, BoardServer, budget_reply from tests.test_roadmap_board_read import _fields_reply, _rest_pages, board_of, issues_of @@ -148,6 +156,114 @@ def test_a_plan_is_built_by_the_stores_own_argument_builders() -> None: assert all(tuple(args) in planned for args in expected) +def _shape(request: PlannedRequest) -> str: + """What a planned `gh` command is: a board, card or fields read, an edit by ids, or its + first arguments.""" + args = list(request.argv[1:]) + query = next((a for a in args if a.startswith("query=")), "") + names = ("RoadmapBoardCard", "RoadmapBoardBudget", "RoadmapBoardItems", "fields(first") + found = next((name for name in names if name in query), None) + if found: + return found + if args[:2] == ["project", "item-edit"]: + return "item-edit by id" if "--id" in args else "item-edit by name" + return " ".join(args[:2]) if args[0] == "project" else " ".join(args[:3]) + + +def test_a_board_write_plans_its_card_read_and_an_edit_by_node_ids() -> None: + """A write lists the fields read it makes once a run, then its one card and the edits by + node ids; never `field-list`, a board page or an edit by URL or field name (#1361).""" + store = StoreRequests(REPO) + plans = { + "set_field": store.set_field("#7", "Value"), + "release": store.set_field("#7", "Release"), + "set_marks": store.set_marks("#7"), + "add_item": store.add_item("#7"), + "set_card_field": store.set_card_field(), + "remove_card": store.remove_card(), + } + assert {name: [_shape(r) for r in plan] for name, plan in plans.items()} == { + "set_field": ["fields(first", "RoadmapBoardCard", "item-edit by id", "item-edit by id"], + "release": [ + "fields(first", + "api repos/dan-petty/devops-cli/milestones?state=all&per_page=100&page=", + "RoadmapBoardCard", + "item-edit by id", + "api -X PATCH", + ], + "set_marks": ["fields(first", "RoadmapBoardCard", "item-edit by id"], + "add_item": [ + "api repos/dan-petty/devops-cli/issues/7", + "project item-add", + "RoadmapBoardCard", + ], + "set_card_field": [ + "fields(first", + "RoadmapBoardCard", + "item-edit by id", + "item-edit by id", + ], + "remove_card": ["RoadmapBoardCard", "project item-delete"], + } + + +def test_the_run_record_card_a_run_creates_is_written_with_no_read_after_its_create() -> None: + plan = StoreRequests(REPO).set_run_record() + create = next(i for i, r in enumerate(plan) if "item-create" in r.argv) + assert ( + [_shape(r) for r in plan[create:]], + plan[create].argv[-2:], + [bool(r.condition) for r in plan[: create + 1]], + ) == ( + ["project item-create", "item-edit by id"], + ("--format", "json"), + [True] * (create + 1), + ) + + +def test_no_roadmap_plan_lists_a_board_command_gh_resolves_by_reading_the_board_first() -> None: + """Every job's plan: no `field-list`, and every `item-edit` by node ids.""" + from devops_cli.roadmap.intake import dry_run_intake + + intake = dry_run_intake(REPO, ref="main") + plans = [ + *render_requests(REPO, None), + *( + r + for pair in (reprioritize_requests(REPO, None), migrate_requests(REPO, None)) + for r in (*pair[0], *pair[1]) + ), + *(r for r in (*close_requests(REPO, None)[0], *close_requests(REPO, None)[1])), + *intake.requests, + *intake.writes, + ] + shapes = {_shape(request) for request in plans if request.argv} + assert ( + "project field-list" in shapes, + "item-edit by name" in shapes, + "item-edit by id" in shapes, + ) == ( + False, + False, + True, + ) + + +def test_intakes_placement_plans_no_board_read_after_its_add() -> None: + """A placement writes to the card the add names: after the add, its plan lists that card's + read, then for each field the card and the edits, and no board page or budget probe.""" + from devops_cli.roadmap.intake import dry_run_intake + + writes = dry_run_intake(REPO, ref="main", issues=(7,)).writes + added = next(i for i, r in enumerate(writes) if "item-add" in r.argv) + after = [_shape(r) for r in writes[added:] if r.argv and r.argv[1] in ("api", "project")] + assert ( + after.count("RoadmapBoardCard"), + {"RoadmapBoardBudget", "RoadmapBoardItems"} & set(after), + [t for t in MESSAGES.roadmap.intake_requests if t == "item"], + ) == (6, set(), []) + + # ── A real run's argv is its plan ───────────────────────────────────────────── _REQUEST, _ARG, _BODY = "\x1e", "\x1f", "\x1d" diff --git a/tests/test_roadmap_github_store.py b/tests/test_roadmap_github_store.py index f632b1f7b0..a539adddf6 100644 --- a/tests/test_roadmap_github_store.py +++ b/tests/test_roadmap_github_store.py @@ -22,19 +22,23 @@ from packaging.version import Version from devops_cli.config.constants import CONST_ROADMAP_RUN_RECORD_BODY +from devops_cli.config.defaults import DEFAULT_GH_GRAPHQL_BUDGET_FLOOR from devops_cli.exceptions.git import ( GitHubFileNotFoundError, GitHubOperationError, GitHubRateLimitError, ) +from devops_cli.exceptions.roadmap import RoadmapCardChangedError from devops_cli.github.rate_limiter import GitHubRateLimiter, reset_github_rate_limiter from devops_cli.roadmap.config import RoadmapConfig from devops_cli.roadmap.github_store import ( GitHubRoadmapStore, + card_edit_args, is_private_args, option_update_request, write_issue_body_args, ) +from devops_cli.roadmap.render import render_roadmap from devops_cli.roadmap.reprioritize import plan_reprioritization from devops_cli.roadmap.store import ( Card, @@ -53,7 +57,7 @@ PullRequestState, RoadmapStore, ) -from tests.roadmap_board_fake import BOARD_READ, BoardServer +from tests.roadmap_board_fake import BOARD_READ, BoardServer, GitHubFake, gh_variables FIXTURES = Path(__file__).parent / "fixtures" / "roadmap" REPO = "dan-petty/devops-cli" @@ -75,15 +79,44 @@ def recorded(name: str) -> Any: LISTING_IN_RELEASE = f"repos/{REPO}/issues?milestone=43&state=all&per_page=100" +# The board's node id, as the recorded board listing (`project list`) gives it. +BOARD_ID = "PVT_kwHOAHXnKc4Biwcg" +CARD_737 = BOARD["items"][0]["id"] +JOB_RECORD_ID = "PVTF_jobrecord" + + def fields_with_job_record() -> dict[str, Any]: listing: dict[str, Any] = deepcopy(FIELDS) - listing["fields"].append( - {"id": "PVTF_jobrecord", "name": "Job record", "type": "ProjectV2Field"} - ) + listing["fields"].append({"id": JOB_RECORD_ID, "name": "Job record", "type": "ProjectV2Field"}) listing["totalCount"] += 1 return listing +def graphql_fields(listing: dict[str, Any]) -> dict[str, Any]: + """The recorded field listing as the store's GraphQL fields query answers it, with the + board's node id.""" + nodes = [ + { + "id": board_field["id"], + "name": board_field["name"], + "dataType": ( + "SINGLE_SELECT" if board_field["type"] == "ProjectV2SingleSelectField" else "TEXT" + ), + "options": board_field.get("options", []), + } + for board_field in listing["fields"] + ] + connection = {"totalCount": len(nodes), "nodes": nodes} + return {"data": {"repositoryOwner": {"projectV2": {"id": BOARD_ID, "fields": connection}}}} + + +ITEM_FIELDS = graphql_fields(fields_with_job_record()) +FIELD_IDS = {f["name"]: f["id"] for f in fields_with_job_record()["fields"]} +OPTION_IDS = { + (f["name"], o["name"]): o["id"] for f in FIELDS["fields"] for o in f.get("options", []) +} + + def created_milestone(number: int, title: str, **changes: Any) -> dict[str, Any]: """The recorded v0.2.25 milestone, as GitHub would return it after a write.""" milestone = next(m for m in MILESTONES if m["title"] == "v0.2.25") @@ -141,7 +174,38 @@ def board_store(replies: dict[str, Any]) -> tuple[GitHubRoadmapStore, RecordedGh def board_item(number: int, **fields: Any) -> Item: - return Item(number=number, title=f"#{number}", url=f"{ISSUE_URL}/{number}", **fields) + """Issue `number` as an Item read from the board: #737's card is the recorded one, with its + Status and Priority, the others are `on_board`'s `PVTI_`.""" + card = CARD_737 if number == 737 else f"PVTI_{number}" + recorded = {"status": "Done", "priority": "P1-High"} if number == 737 else {} + return Item.model_validate( + {"number": number, "title": f"#{number}", "url": f"{ISSUE_URL}/{number}", "card_id": card} + | recorded + | fields + ) + + +def card_edit(card: str, field_name: str, *change: str) -> list[str]: + """The id-addressed `item-edit` of `field_name` on `card`.""" + return card_edit_args(card, BOARD_ID, FIELD_IDS[field_name], list(change)) + + +def graphql_kinds(runner: RecordedGh) -> list[str]: + """Each GraphQL-class command the store sent, by what it is: a board read, a card read, the + fields, an id-addressed edit, or anything else by its first two arguments.""" + kinds = [] + for args, _ in runner.calls: + query = gh_variables(args).get("query", "") if args[:2] == ["api", "graphql"] else "" + if args[0] == "project": + kinds.append(f"{args[1]} by id" if "--id" in args else args[1]) + elif query: + kinds.append( + next( + (name for name in ("RoadmapBoardCard", "RoadmapBoard") if name in query), + "fields" if "fields(first" in query else query[:40], + ) + ) + return kinds # ── Releases ────────────────────────────────────────────────────────────────── @@ -379,29 +443,31 @@ def test_a_job_record_that_cannot_be_decoded_fails_the_read_and_names_its_card( # ── Item writes ─────────────────────────────────────────────────────────────── -def test_a_value_that_is_not_a_board_option_raises_without_writing() -> None: - store, runner = board_store( - {"field-list": fields_with_job_record(), BOARD_READ: BoardServer(BOARD)} - ) +def test_a_value_that_is_not_a_board_option_raises_without_reading_the_card() -> None: + store, runner = board_store({"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(BOARD)}) with pytest.raises(GitHubOperationError, match="not a Priority option"): store.set_field(board_item(737), ItemField.PRIORITY, "P9-Someday") - assert runner.writes == [] + assert (runner.writes, graphql_kinds(runner)) == ([], ["fields"]) -def test_setting_priority_records_it_in_the_job_record_then_edits_the_field() -> None: - # The Item was read before its Status was recorded; the record merges into the board's. +def test_setting_priority_records_it_in_the_job_record_then_edits_the_field_by_ids() -> None: + # The Item was read before its Status was recorded; the record merges into the card's. board = on_board() board["items"][0]["job record"] = '{"Status": "Done"}' store, runner = board_store( - {"field-list": fields_with_job_record(), BOARD_READ: BoardServer(board), "item-edit": ""} + {"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(board), "item-edit": ""} ) store.set_field(board_item(737, status="Done"), ItemField.PRIORITY, "P2-Medium") - edit = ["project", "item-edit", "2", "--owner", "dan-petty", "--url", f"{ISSUE_URL}/737"] record = runner.writes[0][-1] assert (runner.writes, json.loads(record)) == ( [ - [*edit, "--field", "Job record", "--text", record], - [*edit, "--field", "Priority", "--value", "P2-Medium"], + card_edit(CARD_737, "Job record", "--text", record), + card_edit( + CARD_737, + "Priority", + "--single-select-option-id", + OPTION_IDS["Priority", "P2-Medium"], + ), ], {"Priority": "P2-Medium", "Status": "Done"}, ) @@ -411,12 +477,12 @@ def test_a_field_write_sets_marks_in_the_write_that_records_its_value() -> None: """The record of the value and the marks go in one write, before the field: a job that stops after it finds both, and one that stops before it finds neither.""" store, runner = board_store( - {"field-list": fields_with_job_record(), BOARD_READ: BoardServer(BOARD), "item-edit": ""} + {"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(BOARD), "item-edit": ""} ) store.set_field(board_item(737), ItemField.STATUS, "Ready", marks={JobMark.PENDING: "{}"}) - assert [(args[8], args[9:]) for args in runner.writes] == [ - ("Job record", ["--text", '{"Pending": "{}", "Status": "Ready"}']), - ("Status", ["--value", "Ready"]), + assert [args[7:] for args in runner.writes] == [ + [JOB_RECORD_ID, "--text", '{"Pending": "{}", "Status": "Ready"}'], + [FIELD_IDS["Status"], "--single-select-option-id", OPTION_IDS["Status", "Ready"]], ] @@ -424,13 +490,13 @@ def test_two_writes_from_one_read_keep_both_fields_in_the_job_record() -> None: board = on_board() def edit_board(args: list[str]) -> str: - if "Job record" in args: + if JOB_RECORD_ID in args: board["items"][0]["job record"] = args[-1] return "" store, runner = board_store( { - "field-list": fields_with_job_record(), + "fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(board), "item-edit": edit_board, f"api repos/{REPO}/issues/737": ISSUES_IN_RELEASE[2], @@ -440,46 +506,49 @@ def edit_board(args: list[str]) -> str: assert item is not None store.set_field(item, ItemField.PRIORITY, "P2-Medium") store.set_field(item, ItemField.STATUS, "Ready") - assert [json.loads(args[-1]) for args in runner.writes if "Job record" in args] == [ - {"Priority": "P2-Medium"}, - {"Priority": "P2-Medium", "Status": "Ready"}, - ] + assert ( + item.card_id, + [json.loads(args[-1]) for args in runner.writes if JOB_RECORD_ID in args], + ) == (CARD_737, [{"Priority": "P2-Medium"}, {"Priority": "P2-Medium", "Status": "Ready"}]) def test_writing_an_item_that_is_not_on_the_board_raises_without_writing() -> None: - store, runner = board_store( - {"field-list": fields_with_job_record(), BOARD_READ: BoardServer(BOARD)} - ) + store, runner = board_store({"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(BOARD)}) with pytest.raises(GitHubOperationError, match="#739 is not on the board"): store.set_field(board_item(739), ItemField.STATUS, "Ready") assert runner.writes == [] +def test_an_item_whose_card_holds_another_issue_raises_without_writing() -> None: + """A card id names one card: an Item whose card id is another issue's is not on the board.""" + store, runner = board_store({"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(BOARD)}) + with pytest.raises(GitHubOperationError, match="#739 is not on the board"): + store.set_field(board_item(739, card_id=CARD_737), ItemField.STATUS, "Ready") + assert runner.writes == [] + + def test_clearing_a_field_sends_clear_and_records_null() -> None: store, runner = board_store( - {"field-list": fields_with_job_record(), BOARD_READ: BoardServer(BOARD), "item-edit": ""} + {"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(BOARD), "item-edit": ""} ) store.set_field(board_item(737), ItemField.EFFORT, None) - assert [args[8:] for args in runner.writes] == [ - ["Job record", "--text", '{"Effort": null}'], - ["Effort", "--clear"], + assert [args[7:] for args in runner.writes] == [ + [JOB_RECORD_ID, "--text", '{"Effort": null}'], + [FIELD_IDS["Effort"], "--clear"], ] def test_a_board_without_a_job_record_field_raises_before_any_write() -> None: - store, runner = board_store({"field-list": FIELDS}) + store, runner = board_store({"fields(first": graphql_fields(FIELDS)}) with pytest.raises(GitHubOperationError, match="Job record"): store.set_field(board_item(737), ItemField.PRIORITY, "P2-Medium") - assert (runner.writes, [args[:2] for args, _ in runner.calls]) == ( - [], - [["project", "field-list"]], - ) + assert (runner.writes, graphql_kinds(runner)) == ([], ["fields"]) def test_placing_an_item_in_a_release_records_it_then_sets_its_milestone() -> None: store, runner = board_store( { - "field-list": fields_with_job_record(), + "fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(on_board(739)), "milestones?state=all": MILESTONES, "-X PATCH": ISSUES_IN_RELEASE[1], @@ -488,20 +557,329 @@ def test_placing_an_item_in_a_release_records_it_then_sets_its_milestone() -> No ) store.set_field(board_item(739), ItemField.RELEASE, "0.2.25") store.set_field(board_item(739), ItemField.RELEASE, None) - assert [args[3:] if args[0] == "api" else args[8:] for args in runner.writes] == [ - ["Job record", "--text", '{"Release": "v0.2.25"}'], + assert [args[3:] if args[0] == "api" else args[7:] for args in runner.writes] == [ + [JOB_RECORD_ID, "--text", '{"Release": "v0.2.25"}'], [f"repos/{REPO}/issues/739", "-F", "milestone=43"], - ["Job record", "--text", '{"Release": null}'], + [JOB_RECORD_ID, "--text", '{"Release": null}'], [f"repos/{REPO}/issues/739", "-F", "milestone=null"], ] -def test_add_item_adds_the_issue_by_its_url() -> None: - store, runner = board_store({"issues/917": OPEN_ISSUES[1], "item-add": ""}) +def _read_board_and_fields(replies: dict[str, Any]) -> tuple[GitHubRoadmapStore, RecordedGh]: + """A store that has read the board, its issues and its fields, its calls then cleared.""" + store, runner = board_store( + { + "fields(first": ITEM_FIELDS, + "issues?state=all": ISSUES_IN_RELEASE, + "item-edit": "", + **replies, + } + ) + store.items() + store.board_fields() + runner.calls.clear() + return store, runner + + +def test_a_value_write_sends_one_card_read_and_two_id_addressed_edits_and_no_board_read() -> None: + """Once the store has read the board and its fields, a write reads only its card: no + `field-list`, no budget probe, no board page, and no edit that names a card by URL or a + field by name, which gh resolves by reading the board's first 100 items (#1361).""" + store, runner = _read_board_and_fields({BOARD_READ: BoardServer(BOARD)}) + store.set_field(board_item(737), ItemField.VALUE, "High") + assert ( + graphql_kinds(runner), + [args for args, _ in runner.calls if "--url" in args or "--field" in args], + ) == (["RoadmapBoardCard", "item-edit by id", "item-edit by id"], []) + + +def test_a_release_write_sends_one_card_read_one_edit_and_one_milestone_write() -> None: + store, runner = _read_board_and_fields( + { + BOARD_READ: BoardServer(BOARD), + "milestones?state=all": MILESTONES, + "-X PATCH": ISSUES_IN_RELEASE[2], + } + ) + store.set_field(board_item(737), ItemField.RELEASE, "v0.2.25") + assert (graphql_kinds(runner), [args[:3] for args in runner.writes if args[0] == "api"]) == ( + ["RoadmapBoardCard", "item-edit by id"], + [["api", "-X", "PATCH"]], + ) + + +def test_a_write_to_a_card_another_process_archived_raises_before_any_edit() -> None: + board = on_board() + store, runner = _read_board_and_fields({BOARD_READ: BoardServer(board)}) + board["items"][0]["isArchived"] = True + with pytest.raises(GitHubOperationError, match="#737 is not on the board"): + store.set_field(board_item(737), ItemField.VALUE, "High") + assert (runner.writes, graphql_kinds(runner)) == ([], ["RoadmapBoardCard"]) + + +def test_a_mark_another_process_wrote_after_the_listing_was_read_is_kept() -> None: + """The record a write joins is the one the card holds when it is written, not the one the + listing held (ADR 0002's last-set compare).""" + board = on_board() + store, runner = _read_board_and_fields({BOARD_READ: BoardServer(board)}) + (item,) = store.items() + board["items"][0]["job record"] = '{"Nudged": "2026-10-08T00:00:00+00:00"}' + store.set_marks(item, {JobMark.ADMITTED: "43"}) + assert json.loads(runner.writes[-1][-1]) == { + "Admitted": "43", + "Nudged": "2026-10-08T00:00:00+00:00", + } + + +def _person_edits_after_the_read( + **card: str, +) -> tuple[GitHubFake, GitHubRoadmapStore, Item]: + """A store that read #7 with `card`'s fields, after which a person set Priority P1-High.""" + github = GitHubFake(REPO) + github.seed_issue(7, card=card) + store = GitHubRoadmapStore(REPO, board_owner="dan-petty", board_number=2, runner=github) + (item,) = store.items() + (github.card(7) or {})["priority"] = "P1-High" + return github, store, item + + +def _item_edits(github: GitHubFake, start: int) -> list[list[str]]: + return [args for args in github.calls[start:] if args[:2] == ["project", "item-edit"]] + + +def test_a_field_a_person_changed_after_the_listing_was_read_raises_before_any_edit() -> None: + """The store read the board, then a person set Priority: the job's Priority write, planned + from the listing, raises before any edit and the person's value stays (ADR 0002).""" + github, store, item = _person_edits_after_the_read(priority="P2-Medium") + start = len(github.calls) + with pytest.raises(RoadmapCardChangedError, match="#7's Priority") as raised: + store.set_field(item, ItemField.PRIORITY, "P3-Low") + assert ( + _item_edits(github, start), + (github.card(7) or {})["priority"], + {key: raised.value.details[key] for key in ("field", "read", "now")}, + ) == ([], "P1-High", {"field": "Priority", "read": "P2-Medium", "now": "P1-High"}) + + +def test_a_persons_change_stays_caught_after_the_store_wrote_another_field_of_its_card() -> None: + """A write that reads the card takes only its job record into the listing, so a person's + Priority it saw while writing Effort still stops the Priority write that follows.""" + github, store, item = _person_edits_after_the_read(priority="P2-Medium") + store.set_field(item, ItemField.EFFORT, "Low") + start = len(github.calls) + with pytest.raises(RoadmapCardChangedError): + store.set_field(item, ItemField.PRIORITY, "P3-Low") + assert (_item_edits(github, start), (github.card(7) or {})["effort"]) == ([], "Low") + + +def test_a_write_of_the_value_the_card_holds_now_goes_ahead() -> None: + """Writing the value someone else already set reverts nothing: the board's own "Item + added" workflow sets Status New on a new card, and intake writes the same New.""" + github, store, item = _person_edits_after_the_read() + store.set_field(item, ItemField.PRIORITY, "P1-High") + card = github.card(7) or {} + assert (card["priority"], json.loads(card["job record"])) == ( + "P1-High", + {"Priority": "P1-High"}, + ) + + +def test_the_stores_own_write_is_the_value_its_next_write_of_that_field_compares() -> None: + """A reprioritize apply reverts a field, then writes its decision to it, both from the Item + it planned with: the second write compares the card with the first write's value.""" + github = GitHubFake(REPO) + github.seed_issue(7, card={"priority": "P2-Medium"}) + store = GitHubRoadmapStore(REPO, board_owner="dan-petty", board_number=2, runner=github) + (item,) = store.items() + store.set_field(item, ItemField.PRIORITY, "P1-High") + store.set_field(item, ItemField.PRIORITY, "P0-Critical") + assert (github.card(7) or {})["priority"] == "P0-Critical" + + +def test_a_card_field_a_person_changed_after_the_listing_was_read_raises_before_any_edit() -> None: + github = GitHubFake(REPO) + github.seed_issue(7, card={"status": "Ready"}) + store = GitHubRoadmapStore(REPO, board_owner="dan-petty", board_number=2, runner=github) + (card,) = store.cards() + (github.card(7) or {})["status"] = "Blocked" + start = len(github.calls) + with pytest.raises(RoadmapCardChangedError, match="Status"): + store.set_card_field(card, ItemField.STATUS, "Done") + assert (_item_edits(github, start), (github.card(7) or {})["status"]) == ([], "Blocked") + + +@pytest.mark.parametrize("duplicate", [False, True]) +def test_a_render_after_a_close_in_the_same_store_shows_the_status_the_board_set( + duplicate: bool, +) -> None: + """A close lets the board's "Item closed" workflow set the card's Status to Done, so the + store drops the listings it read: the cut a close round renders through the same store + writes Done, not the Status the store read before the close.""" + github = GitHubFake(REPO, milestones=[{"number": 43, "title": "v0.2.25", "state": "open"}]) + github.seed_issue(7, "feat: shipped", milestone="v0.2.25", card={"status": "In Review"}) + github.seed_issue(8, "feat: the original", milestone="v0.2.25", card={"status": "Ready"}) + store = GitHubRoadmapStore(REPO, board_owner="dan-petty", board_number=2, runner=github) + config = RoadmapConfig(board=2) + before = render_roadmap(store, repo=REPO, config=config) + if duplicate: + store.close_as_duplicate(7, 8, None) + else: + store.close_issue(7, CloseReason.COMPLETED, "Delivered.") + after = render_roadmap(store, repo=REPO, config=config) + assert ( + next(line for line in before.splitlines() if "#7 " in line), + next(line for line in after.splitlines() if "#7 " in line), + ) == ( + "- [ ] #7 feat: shipped — Status: In Review · Priority: — · Value: — · Effort: —", + "- [x] #7 feat: shipped — Status: Done · Priority: — · Value: — · Effort: —", + ) + + +def test_a_write_refuses_before_it_starts_while_the_points_left_are_below_the_reserve() -> None: + """The card read reports the points left; below the reserve the write never starts.""" + server = BoardServer(BOARD, remaining=DEFAULT_GH_GRAPHQL_BUDGET_FLOOR) + store, runner = board_store({"fields(first": ITEM_FIELDS, BOARD_READ: server}) + with pytest.raises(GitHubRateLimitError, match="stopped before writing #737"): + store.set_marks(board_item(737), {JobMark.ADMITTED: "43"}) + assert runner.writes == [] + + +def test_the_store_reads_the_board_once_and_its_own_writes_keep_that_listing_current() -> None: + """Every reader of one filter shares one listing per store; a write updates the card in it + with the values it sent, so a later read of the same store sees them without a re-read.""" + board = on_board() + store, runner = board_store( + { + "fields(first": ITEM_FIELDS, + BOARD_READ: BoardServer(board), + "issues?state=all": ISSUES_IN_RELEASE, + "item-edit": "", + f"api repos/{REPO}/issues/737": ISSUES_IN_RELEASE[2], + } + ) + (before,) = store.items() + store.set_field(before, ItemField.VALUE, "Low") + after = store.item(737) + probes = [args for args in graphql_kinds(runner) if args == "RoadmapBoard"] + assert ( + after is not None and (after.value, after.job_record), + len(probes), + len(store.cards()), + ) == ((("Low", {ItemField.VALUE: "Low"})), 2, 4) + + +@pytest.mark.parametrize("size", [120, 1_080]) +def test_a_job_record_mark_costs_three_graphql_points_whatever_the_boards_size(size: int) -> None: + """The store's fields (once a run), the one card and one edit by node ids: 3 points on a + board of 120 cards or of 1,080, board #2's size on 2026-10-08, where the same mark through + `field-list`, a whole-board read and a name-addressed `item-edit` cost about 215 (#1361).""" + github = GitHubFake(REPO) + for number in range(1, size + 1): + github.seed_issue(number, card={"status": "Ready"}) + store = GitHubRoadmapStore(REPO, board_owner="dan-petty", board_number=2, runner=github) + item = board_item(7, card_id=github.card_id(7)) + store.set_marks(item, {JobMark.NUDGED: "2026-10-08T02:20:00+00:00"}) + card = github.card(7) or {} + assert (github.points, json.loads(card["job record"])) == ( + 3, + {"Nudged": "2026-10-08T02:20:00+00:00"}, + ) + + +def test_add_item_adds_the_issue_by_its_url_and_returns_the_card_it_added() -> None: + """`item-add --format json` names the card; its fields come from one read of that card, + never from the board listing, which may not show a new card for minutes (#1361).""" + board = on_board(917) + board["items"][-1]["status"] = "New" + store, runner = board_store( + { + "item-add": {"id": "PVTI_917", "title": OPEN_ISSUES[1]["title"], "type": "Issue"}, + "issues/917": OPEN_ISSUES[1], + BOARD_READ: BoardServer(board), + } + ) + added = store.add_item(917) + assert ( + runner.writes, + graphql_kinds(runner), + (added.number, added.card_id, added.status, added.title, added.state), + ) == ( + [ + [ + "project", + "item-add", + "2", + "--owner", + "dan-petty", + "--url", + f"{ISSUE_URL}/917", + "--format", + "json", + ] + ], + ["item-add", "RoadmapBoardCard"], + (917, "PVTI_917", "New", OPEN_ISSUES[1]["title"], GitHubState.OPEN), + ) + + +def test_adding_an_issue_already_on_the_board_returns_its_existing_card() -> None: + """GitHub's add answers with the card the issue already has, so it keeps its fields.""" + store, _ = board_store( + { + "item-add": {"id": CARD_737, "type": "Issue"}, + "issues/737": ISSUES_IN_RELEASE[2], + BOARD_READ: BoardServer(BOARD), + } + ) + added = store.add_item(737) + assert (added.card_id, added.status, added.priority) == (CARD_737, "Done", "P1-High") + + +def test_an_added_card_joins_the_listing_the_store_already_read() -> None: + """A later read of the same store holds the card it added, though GitHub's listing may + not list it yet.""" + board = on_board() + added = deepcopy(board["items"][0]) + added.update(id="PVTI_917", content={**added["content"], "number": 917}) + server = BoardServer(board) + + def add(_: list[str]) -> dict[str, str]: + board["items"].append(added) + return {"id": "PVTI_917"} + + store, _ = board_store( + { + "item-add": add, + "issues/917": OPEN_ISSUES[1], + "issues?state=all": [*ISSUES_IN_RELEASE, OPEN_ISSUES[1]], + BOARD_READ: server, + } + ) + store.items() + server.lagging["PVTI_917"] = 3 store.add_item(917) - assert runner.writes == [ - ["project", "item-add", "2", "--owner", "dan-petty", "--url", f"{ISSUE_URL}/917"] - ] + assert ([item.number for item in store.items()], server.pages) == ([737, 917], 1) + + +def test_an_added_open_card_joins_the_open_items_listing_without_a_read() -> None: + """Intake reads the open items for its candidates, then adds one: the open items' listing + keeps the card the add returned, so the backlog shows it with no read that GitHub's lag + could leave it out of.""" + github = GitHubFake(REPO, lag=3) + github.seed_issue(5, "feat: new") + store = GitHubRoadmapStore(REPO, board_owner="dan-petty", board_number=2, runner=github) + before = [candidate.number for candidate in store.candidates()] + start = len(github.calls) + store.add_item(5) + read_after = len(github.calls) + assert ( + before, + [candidate.number for candidate in store.candidates()], + [item.number for item in store.backlog()], + [args for args in github.calls[read_after:] if "RoadmapBoard" in " ".join(args)], + github.board.lagging, + start < read_after, + ) == ([5], [], [5], [], {"PVTI_5": 3}, True) def test_add_item_refuses_a_pull_request() -> None: @@ -560,14 +938,14 @@ def test_a_failed_write_raises() -> None: """The job record goes first, so when its write fails the field is never written.""" store, runner = board_store( { - "field-list": fields_with_job_record(), + "fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(BOARD), "item-edit": (1, "GraphQL: Could not resolve"), } ) with pytest.raises(GitHubOperationError, match="Could not set Job record on #737"): store.set_field(board_item(737), ItemField.STATUS, "Ready") - assert [args[8] for args in runner.writes] == ["Job record"] + assert [args[7] for args in runner.writes] == [JOB_RECORD_ID] # ── Paging and caching ──────────────────────────────────────────────────────── @@ -726,7 +1104,7 @@ def test_every_read_passes_use_cache_false() -> None: { "milestones?state=all": MILESTONES, BOARD_READ: BoardServer(BOARD), - "field-list": FIELDS, + "fields(first": graphql_fields(FIELDS), "issues?milestone=43": ISSUES_IN_RELEASE, "issues/737": ISSUES_IN_RELEASE[2], "issues?state=open": OPEN_ISSUES, @@ -740,8 +1118,8 @@ def test_every_read_passes_use_cache_false() -> None: with pytest.raises(GitHubOperationError, match="Job record"): store.set_field(board_item(737), ItemField.STATUS, "Ready") assert ([kwargs["use_cache"] for _, kwargs in runner.calls], len(runner.calls)) == ( - [False] * 14, - 14, + [False] * 10, + 10, ) @@ -800,6 +1178,36 @@ def test_changes_since_keeps_issue_release_label_and_state_events_only() -> None ] +def test_changes_since_drops_an_actors_own_changes_before_it_reads_the_board() -> None: + """A run's own events read no job record, so a round whose events are all its own sends + no GraphQL request (#1361); the others' changes still carry theirs.""" + closed = next(e for e in EVENTS if e["event"] == "closed" and "pull_request" not in e["issue"]) + own = {**closed, "actor": {"login": "roadmap-bot"}, "created_at": "2026-10-02T01:00:00Z"} + store, runner = board_store({"issues/events": [own], BOARD_READ: BoardServer(BOARD)}) + alone = store.changes_since(datetime(2026, 10, 1, tzinfo=UTC), except_actor="roadmap-bot") + sent_alone = graphql_kinds(runner) + runner.replies["issues/events"] = [own, *EVENTS] + mixed = store.changes_since(datetime(2026, 10, 1, tzinfo=UTC), except_actor="roadmap-bot") + assert (alone, sent_alone, {change.actor for change in mixed}, len(mixed)) == ( + [], + [], + {"dan-petty"}, + 5, + ) + + +def test_changes_since_with_an_empty_actor_leaves_out_nothing() -> None: + """An empty session login names no actor, so no change is left out, not even one GitHub + reports with an empty login.""" + closed = next(e for e in EVENTS if e["event"] == "closed" and "pull_request" not in e["issue"]) + nameless = {**closed, "actor": {"login": ""}, "created_at": "2026-10-02T01:00:00Z"} + store, _ = board_store({"issues/events": [nameless], BOARD_READ: BoardServer(BOARD)}) + changes = store.changes_since(datetime(2026, 10, 1, tzinfo=UTC), except_actor="") + assert [(change.number, change.actor) for change in changes] == [ + (closed["issue"]["number"], "") + ] + + def test_changes_since_raises_when_the_events_outrun_the_page_cap( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -889,7 +1297,7 @@ def test_the_factory_opens_the_github_adapter_without_reading( def owned_board(selection: str, nodes: list[Any]) -> dict[str, Any]: connection = {"totalCount": len(nodes), "nodes": nodes} - return {"data": {"repositoryOwner": {"projectV2": {selection: connection}}}} + return {"data": {"repositoryOwner": {"projectV2": {"id": BOARD_ID, selection: connection}}}} def updated_field(node: dict[str, Any]) -> dict[str, Any]: @@ -974,20 +1382,19 @@ def test_cards_are_everything_on_the_board() -> None: def test_a_card_field_is_set_by_node_ids_then_recorded() -> None: store, runner = board_store( - { - "project list": PROJECTS, - "fields(first": FIELDS_REPLY, - BOARD_READ: BoardServer(BOARD), - "item-edit": "", - } + {"fields(first": FIELDS_REPLY, BOARD_READ: BoardServer(BOARD), "item-edit": ""} ) draft = next(card for card in store.cards() if card.kind is CardKind.DRAFT_ISSUE) + runner.calls.clear() store.set_card_field(draft, ItemField.STATUS, "Ready") - edit = ["project", "item-edit", "--id", draft.id, "--project-id", "PVT_kwHOAHXnKc4Biwcg"] - assert runner.writes == [ - [*edit, "--field-id", STATUS_NODE["id"], "--single-select-option-id", "89415499"], - [*edit, "--field-id", "PVTF_jobrecord", "--text", '{"Status": "Ready"}'], - ] + edit = ["project", "item-edit", "--id", draft.id, "--project-id", BOARD_ID] + assert (runner.writes, graphql_kinds(runner)[:2]) == ( + [ + [*edit, "--field-id", STATUS_NODE["id"], "--single-select-option-id", "89415499"], + [*edit, "--field-id", "PVTF_jobrecord", "--text", '{"Status": "Ready"}'], + ], + ["fields", "RoadmapBoardCard"], + ) def test_a_card_write_to_the_release_raises_before_any_read() -> None: @@ -998,15 +1405,18 @@ def test_a_card_write_to_the_release_raises_before_any_read() -> None: assert runner.calls == [] -def test_remove_card_deletes_the_board_item_by_id() -> None: +def test_remove_card_reads_the_card_then_deletes_it_by_id() -> None: store, runner = board_store({BOARD_READ: BoardServer(BOARD), "item-delete": ""}) card = store.cards()[0] + runner.calls.clear() store.remove_card(card) with pytest.raises(GitHubOperationError, match="not on the board"): store.remove_card(card.model_copy(update={"id": "PVTI_gone"})) - assert runner.writes == [ - ["project", "item-delete", "2", "--owner", "dan-petty", "--id", card.id] - ] + assert (runner.writes, graphql_kinds(runner), [c.id for c in store.cards()][:1]) == ( + [["project", "item-delete", "2", "--owner", "dan-petty", "--id", card.id]], + ["RoadmapBoardCard", "item-delete by id", "RoadmapBoardCard"], + [BOARD["items"][1]["id"]], + ) def test_board_finds_the_number_among_the_owners_boards() -> None: @@ -1494,15 +1904,15 @@ def test_comment_posts_one_comment() -> None: ] -def test_set_marks_merges_the_marks_into_the_job_record_the_board_holds_in_one_write() -> None: +def test_set_marks_merges_the_marks_into_the_job_record_the_card_holds_in_one_write() -> None: board = on_board() board["items"][0]["job record"] = '{"Pending": "{}", "Release": "v0.2.25"}' store, runner = board_store( - {"field-list": fields_with_job_record(), BOARD_READ: BoardServer(board), "item-edit": ""} + {"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(board), "item-edit": ""} ) store.set_marks(board_item(737), {JobMark.ADMITTED: "v0.2.25", JobMark.PENDING: None}) - assert [(args[8:10], json.loads(args[-1])) for args in runner.writes] == [ - (["Job record", "--text"], {"Admitted": "v0.2.25", "Pending": None, "Release": "v0.2.25"}) + assert [(args[7:9], json.loads(args[-1])) for args in runner.writes] == [ + ([JOB_RECORD_ID, "--text"], {"Admitted": "v0.2.25", "Pending": None, "Release": "v0.2.25"}) ] @@ -1514,7 +1924,7 @@ def test_set_marks_records_and_forgets_field_values_in_the_same_write() -> None: '{"NeedsSplit": "yes", "Pending": "{}", "Release": "v0.2.26", "Status": "Ready"}' ) store, runner = board_store( - {"field-list": fields_with_job_record(), BOARD_READ: BoardServer(board), "item-edit": ""} + {"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(board), "item-edit": ""} ) store.set_marks( board_item(737), @@ -1522,49 +1932,45 @@ def test_set_marks_records_and_forgets_field_values_in_the_same_write() -> None: recorded={ItemField.STATUS: "In Progress"}, forgotten=(ItemField.RELEASE,), ) - assert [(args[8:10], json.loads(args[-1])) for args in runner.writes] == [ - (["Job record", "--text"], {"NeedsSplit": "yes", "Pending": None, "Status": "In Progress"}) + assert [(args[7:9], json.loads(args[-1])) for args in runner.writes] == [ + ([JOB_RECORD_ID, "--text"], {"NeedsSplit": "yes", "Pending": None, "Status": "In Progress"}) ] def test_every_job_record_write_keeps_the_keys_this_version_does_not_know() -> None: """A newer version's key survives this version's writes: none rebuilds the record from only the keys it read.""" - board = on_board() + board = with_run_record('{"Started": "v0.2.25", "Cadence": "weekly"}') board["items"][0]["job record"] = '{"Admitted": "v0.2.25", "NeedsSplit": "yes"}' - run_record = with_run_record('{"Started": "v0.2.25", "Cadence": "weekly"}') store, runner = board_store( - { - "project list": PROJECTS, - "fields(first": FIELDS_REPLY, - "field-list": fields_with_job_record(), - BOARD_READ: BoardServer(board), - "item-edit": "", - } + {"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(board), "item-edit": ""} ) store.set_marks(board_item(737), {JobMark.PENDING: "{}"}) store.set_field(board_item(737), ItemField.PRIORITY, "P1-High") - marks_and_field = [json.loads(args[-1]) for args in runner.writes if args[-2] == "--text"] - runner.replies[BOARD_READ] = BoardServer(run_record) store.set_run_record({JobMark.STARTED: "v0.2.26"}) - assert (marks_and_field, json.loads(runner.writes[-1][-1])) == ( - [ - {"Admitted": "v0.2.25", "NeedsSplit": "yes", "Pending": "{}"}, - {"Admitted": "v0.2.25", "NeedsSplit": "yes", "Priority": "P1-High"}, - ], + assert [json.loads(args[-1]) for args in runner.writes if args[-2] == "--text"] == [ + {"Admitted": "v0.2.25", "NeedsSplit": "yes", "Pending": "{}"}, + {"Admitted": "v0.2.25", "NeedsSplit": "yes", "Priority": "P1-High"}, {"Cadence": "weekly", "Started": "v0.2.26"}, - ) + ] def test_set_marks_raises_before_any_write_for_an_item_off_the_board() -> None: - store, runner = board_store( - {"field-list": fields_with_job_record(), BOARD_READ: BoardServer(BOARD)} - ) + store, runner = board_store({"fields(first": ITEM_FIELDS, BOARD_READ: BoardServer(BOARD)}) with pytest.raises(GitHubOperationError, match="#739 is not on the board"): store.set_marks(board_item(739), {JobMark.NUDGED: "2026-10-02T00:00:00+00:00"}) assert runner.writes == [] +def test_an_item_no_store_read_has_no_card_to_write_and_raises_before_any_write() -> None: + """An Item built as a probe, not read from a store, carries no card id.""" + store, runner = board_store({"fields(first": ITEM_FIELDS}) + probe = Item(number=737, title="#737", url=f"{ISSUE_URL}/737") + with pytest.raises(GitHubOperationError, match="#737 is not on the board"): + store.set_marks(probe, {JobMark.NUDGED: "2026-10-02T00:00:00+00:00"}) + assert (runner.writes, graphql_kinds(runner)) == ([], ["fields"]) + + def with_run_record(record: str | None) -> dict[str, Any]: """The recorded board with the run record card: a draft issue, as the recorded draft is.""" board: dict[str, Any] = deepcopy(BOARD) @@ -1588,60 +1994,65 @@ def test_the_run_record_is_the_job_record_of_the_draft_card_titled_for_it() -> N def test_set_run_record_creates_its_card_once_then_edits_its_job_record_by_node_id() -> None: - listings = iter([BOARD, with_run_record(None), with_run_record('{"Started": "v0.2.25"}')]) - replies = { - "project list": PROJECTS, - "fields(first": FIELDS_REPLY, - BOARD_READ: BoardServer(lambda: next(listings)), - "item-create": "", - "item-edit": "", - } - store, runner = board_store(replies) - store.set_run_record({JobMark.STARTED: "v0.2.25"}) - store.set_run_record({JobMark.STARTED: "v0.2.26"}) - edit = ["project", "item-edit", "--id", "PVTI_runrecord", "--project-id"] - assert runner.writes == [ - [ - "project", - "item-create", - "2", - "--owner", - "dan-petty", - "--title", - "Roadmap run record", - "--body", - CONST_ROADMAP_RUN_RECORD_BODY, - ], - [ - *edit, - "PVT_kwHOAHXnKc4Biwcg", - "--field-id", - "PVTF_jobrecord", - "--text", - '{"Started": "v0.2.25"}', - ], - [ - *edit, - "PVT_kwHOAHXnKc4Biwcg", - "--field-id", - "PVTF_jobrecord", - "--text", - '{"Started": "v0.2.26"}', - ], - ] + """The card is written by the id `item-create --format json` returns, with no read after + the create; the next write reads that card, and the board listing is read once.""" + board = deepcopy(BOARD) + run_record = with_run_record(None)["items"][-1] + def create(_: list[str]) -> dict[str, Any]: + board["items"].append(run_record) + return {"id": run_record["id"], "title": "Roadmap run record", "type": "DraftIssue"} -def test_set_run_record_raises_when_the_card_it_created_is_not_listed() -> None: - store, _ = board_store( + def edit(args: list[str]) -> str: + run_record["job record"] = args[-1] + return "" + + store, runner = board_store( { - "project list": PROJECTS, "fields(first": FIELDS_REPLY, - BOARD_READ: BoardServer(BOARD), - "item-create": "", + BOARD_READ: BoardServer(board), + "item-create": create, + "item-edit": edit, } ) - with pytest.raises(GitHubOperationError, match="does not list the run record card"): - store.set_run_record({JobMark.STARTED: "v0.2.25"}) + store.set_run_record({JobMark.STARTED: "v0.2.25"}) + store.set_run_record({JobMark.SIZE: "7"}) + edit_args = ["project", "item-edit", "--id", "PVTI_runrecord", "--project-id", BOARD_ID] + assert (runner.writes, graphql_kinds(runner), store.run_record()) == ( + [ + [ + "project", + "item-create", + "2", + "--owner", + "dan-petty", + "--title", + "Roadmap run record", + "--body", + CONST_ROADMAP_RUN_RECORD_BODY, + "--format", + "json", + ], + [*edit_args, "--field-id", JOB_RECORD_ID, "--text", '{"Started": "v0.2.25"}'], + [ + *edit_args, + "--field-id", + JOB_RECORD_ID, + "--text", + '{"Size": "7", "Started": "v0.2.25"}', + ], + ], + [ + "fields", + "RoadmapBoard", + "RoadmapBoard", + "item-create", + "item-edit by id", + "RoadmapBoardCard", + "item-edit by id", + ], + {JobMark.STARTED: "v0.2.25", JobMark.SIZE: "7"}, + ) def test_release_changes_read_one_issues_events_for_its_joins_and_leaves() -> None: diff --git a/tests/test_roadmap_intake.py b/tests/test_roadmap_intake.py index 5253ee3355..b9cfa29fab 100644 --- a/tests/test_roadmap_intake.py +++ b/tests/test_roadmap_intake.py @@ -1,7 +1,9 @@ """`devops roadmap intake` over the in-memory roadmap store, a fake embedder and a fake model (#742). Each case builds the roadmap a person leaves, runs intake, and reads back what the store holds -and what intake wrote. No case runs `gh`, reaches a model or opens a socket. +and what intake wrote. The last cases run the GitHub store over `GitHubFake`, a fake at the `gh` +process edge, to count the requests a placement sends (#1361). No case runs `gh`, reaches a +model or opens a socket. """ from __future__ import annotations @@ -37,6 +39,11 @@ from devops_cli.exceptions.security import SecurityError from devops_cli.lang import MESSAGES from devops_cli.roadmap import store as roadmap_store_module +from devops_cli.roadmap.board_read import ( + BOARD_BUDGET_OPERATION, + BOARD_CARD_OPERATION, + BOARD_ITEMS_OPERATION, +) from devops_cli.roadmap.config import RoadmapConfig, open_roadmap from devops_cli.roadmap.github_store import GitHubRoadmapStore from devops_cli.roadmap.intake import ( @@ -73,6 +80,7 @@ ItemField, ) from devops_cli.telemetry.tracer import OTelTelemetryClient, get_tracer +from tests.roadmap_board_fake import GitHubFake, field_id REPO = "example/roadmap" NOW = datetime(2026, 10, 4, 12, 0, tzinfo=UTC) @@ -852,7 +860,6 @@ def test_a_dry_run_is_an_intake_plan_of_planned_requests_with_placeholders() -> "file": "create_issue", "label": "label_issue", "add": "add_item", - "item": "item", "release": "set_field", "field": "set_field", "comment": "comment", @@ -1454,3 +1461,151 @@ def test_a_person_files_through_the_command_without_the_agent_label( _intake("--title", "feat: mine", "--body-file", str(body), "--filed-by", "person", "--confirm") (new,) = [i.number for i in board.store.issues() if i.title == "feat: mine"] assert _labels(board, new) == ("type/feature",) + + +# ── On the GitHub store, at the `gh` process edge (#1361) ───────────────────── +# The store runs every command through `GitHubFake`, which answers as GitHub does: its board +# listing may leave a card just added out, as GitHub's showed one up to two minutes late on +# 2026-10-07, and it charges each GraphQL request the points GitHub's estimate gives its shape. + +GITHUB_MILESTONES = [ + {"number": 25, "title": PREVIOUS, "state": "closed", "closed_at": "2026-10-03T12:00:00Z"}, + {"number": 26, "title": CURRENT, "state": "open"}, + {"number": 27, "title": NEXT, "state": "open"}, +] +CRITICAL_FIX = NewCandidate( + title="fix: crash on start", + body="Introduced by abc1234.", + evidence=(Evidence(kind=EvidenceKind.REGRESSION_COMMIT, value="abc1234"),), +) + + +def on_github(board: int = 0, *, lag: int = 0) -> tuple[GitHubFake, GitHubRoadmapStore]: + """A repository whose board holds `board` finished items, and the store over it.""" + github = GitHubFake( + REPO, + milestones=GITHUB_MILESTONES, + files={".github/labels.yml": LABELS_YML}, + commits=("abc1234",), + lag=lag, + ) + for number in range(1, board + 1): + github.seed_issue( + number, + f"feat: finished item {number}", + labels=("type/feature",), + card={"status": "Ready", "priority": "P3-Low", "value": "Low", "effort": "Low"}, + ) + owner = REPO.split("/")[0] + return github, GitHubRoadmapStore(REPO, board_owner=owner, board_number=1, runner=github) + + +def _intake_on_github( + store: GitHubRoadmapStore, model: FakeModel, **options: Any +) -> tuple[IntakePlan, Any]: + plan = plan_intake(store, config=CONFIG, model=model, **options) + return plan, lambda: apply_intake(store, plan, refine=lambda *_: None) + + +def _sent(github: GitHubFake, start: int, operation: str) -> int: + """How many requests naming `operation` the store sent from call `start` on.""" + return sum(operation in " ".join(args) for args in github.calls[start:]) + + +def _edits(github: GitHubFake, start: int) -> list[tuple[str, str]]: + """Each id-addressed `item-edit` from call `start` on: the field's id and the value sent.""" + return [ + (args[args.index("--field-id") + 1], args[-1]) + for args in github.calls[start:] + if args[:2] == ["project", "item-edit"] + ] + + +def test_intake_writes_to_the_card_it_added_while_the_board_listing_leaves_it_out() -> None: + """The lag of 2026-10-07: the listing leaves a new card out of its next three reads. Intake + files a critical fix and places it in the current release, writing Release, Status, Value, + Effort and Priority to the card the add named; after the add it sends no board listing + query, only one card read for the add and one for each field write. At 910b823 it failed + here with "is not on the board after intake added it".""" + github, store = on_github(board=3, lag=3) + model = FakeModel(proposals={CRITICAL_FIX.title: REGRESSION}) + _, apply = _intake_on_github(store, model, new=CRITICAL_FIX) + applied = apply() + (number,) = applied.filed + added = next(i for i, args in enumerate(github.calls) if args[:2] == ["project", "item-add"]) + card = github.card(number) or {} + assert ( + [_sent(github, added, name) for name in (BOARD_BUDGET_OPERATION, BOARD_ITEMS_OPERATION)], + _sent(github, added, BOARD_CARD_OPERATION), + github.board.lagging, + {key: card.get(key) for key in ("status", "priority", "value", "effort")}, + json.loads(card["job record"])["Release"], + github.issues[number]["milestone"]["title"], + ) == ( + [0, 0], + 6, + {f"PVTI_{number}": 3}, + {"status": "New", "priority": "P0-Critical", "value": "Medium", "effort": "Low"}, + CURRENT, + CURRENT, + ) + + +@pytest.mark.parametrize("board", [120, 1_080]) +def test_a_placement_costs_the_same_few_graphql_points_whatever_the_boards_size( + board: int, +) -> None: + """Filing and placing a critical fix in the release: the fields once, the add and its card, + then for each of five writes the card and its edits by node ids. The cost is a small + constant, the same on a board of 120 cards or of 1,080: about 17 in the fake, which charges + `item-add` as one mutation though gh first resolves its owner, board and issue with queries + of its own. On 2026-10-07 the same placement cost about 1,500, most of it in `field-list`, + name-addressed edits and whole-board re-reads.""" + github, store = on_github(board=board) + model = FakeModel(proposals={CRITICAL_FIX.title: REGRESSION}) + _, apply = _intake_on_github(store, model, new=CRITICAL_FIX) + github.points = 0 + apply() + assert github.points == 17 + + +def test_an_item_on_the_board_with_status_and_value_gets_only_effort_and_priority() -> None: + """#1336's state: a card with Status and Value from a placement that stopped. Intake + writes the record and the field for Effort, then Priority, to the card it has, and sends + no board listing query.""" + github, store = on_github() + record = json.dumps({"Status": "New", "Value": "Medium"}) + github.seed_issue(1, "feat: export the board as CSV", card={"status": "New", "value": "Medium"}) + (github.card(1) or {})["job record"] = record + plan, apply = _intake_on_github(store, FakeModel()) + start = len(github.calls) + apply() + assert ( + plan.decisions[0].subject.item is not None, + [field for field, _ in _edits(github, start)], + [value for _, value in _edits(github, start)][1::2], + _sent(github, start, "RoadmapBoardItems") + _sent(github, start, "RoadmapBoardBudget"), + _sent(github, start, "item-add"), + ) == ( + True, + [field_id("Job record"), field_id("Effort"), field_id("Job record"), field_id("Priority")], + ["PVTF_effort/Low", "PVTF_priority/P2-Medium"], + 0, + 0, + ) + + +def test_an_intake_of_three_placements_reads_the_board_once() -> None: + """On a board of 250 cards: one budget probe and three pages for the whole run, its three + placements included.""" + github, store = on_github(board=250) + for number in (251, 252, 253): + github.seed_issue(number, f"feat: new idea {number}") + _, apply = _intake_on_github(store, FakeModel()) + applied = apply() + assert ( + applied.placed, + _sent(github, 0, BOARD_BUDGET_OPERATION), + _sent(github, 0, BOARD_ITEMS_OPERATION), + [(github.card(n) or {}).get("priority") for n in (251, 252, 253)], + ) == (3, 1, 3, ["P2-Medium"] * 3) diff --git a/tests/test_roadmap_run.py b/tests/test_roadmap_run.py index abe2232ae7..019537bbba 100644 --- a/tests/test_roadmap_run.py +++ b/tests/test_roadmap_run.py @@ -1,7 +1,9 @@ """Tests for `devops roadmap run` and due table execution (#981). All tests run in-memory without network or cluster access, testing due evaluation, -schedule persistence, clone management, service wiring, and MCP integration. +schedule persistence, clone management, service wiring, and MCP integration. The last cases run +the GitHub store over `GitHubFake`, a fake at the `gh` process edge, to count a round's board +reads (#1361). """ from __future__ import annotations @@ -26,6 +28,8 @@ CONST_ROADMAP_INTAKE_BATCH_KEYS, ) from devops_cli.exceptions import GitOperationError, RoadmapRunError +from devops_cli.roadmap.board_read import BOARD_BUDGET_OPERATION, BOARD_ITEMS_OPERATION +from devops_cli.roadmap.github_store import GitHubRoadmapStore from devops_cli.roadmap.memory_store import InMemoryRoadmapStore from devops_cli.roadmap.run import ( JobOutcome, @@ -37,6 +41,7 @@ ) from devops_cli.roadmap.store import Change, ChangeKind, CloseReason, GitHubState from devops_cli.server.service import TriggerBatch +from tests.roadmap_board_fake import GitHubFake REPO = "example/roadmap" RELEASE = "v0.2.26" @@ -893,3 +898,93 @@ def test_metrics_job_registered_in_default_due_table_and_adapter( ) fail_outcome = _run_metrics_adapter(repo="example/repo") assert isinstance(fail_outcome, JobOutcome) is True + + +# ── On the GitHub store, at the `gh` process edge (#1361) ───────────────────── + + +def _labeled(count: int, actor: str) -> list[dict[str, Any]]: + """`count` label events by `actor` on issues #1.., newest first, in no milestone.""" + return [ + { + "event": "labeled", + "created_at": (NOW - timedelta(seconds=10 + n)).strftime("%Y-%m-%dT%H:%M:%SZ"), + "actor": {"login": actor}, + "issue": {"number": n + 1, "milestone": None}, + "label": {"name": "scope/cli"}, + } + for n in range(count) + ] + + +def _github_round( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, events: list[dict[str, Any]] +) -> tuple[GitHubFake, GitHubRoadmapStore]: + """A repository with 60 cards and a current release, its jobs all run five minutes ago, the + Service logged in as `roadmap-bot`, and the store a round opens over it.""" + github = GitHubFake( + REPO, + milestones=[ + {"number": 25, "title": "v0.2.25", "state": "closed"}, + {"number": 26, "title": RELEASE, "state": "open"}, + ], + events=events, + ) + for number in range(1, 61): + github.seed_issue(number, card={"status": "Ready"}) + t5 = (NOW - timedelta(minutes=5)).isoformat() + sched_file = tmp_path / "roadmap" / "example" / "roadmap" / "schedule.json" + sched_file.parent.mkdir(parents=True, exist_ok=True) + sched_file.write_text( + json.dumps({"intake": t5, "close": t5, "reprioritize": t5}), encoding="utf-8" + ) + monkeypatch.setattr("devops_cli.roadmap.run._get_session_login", lambda: "roadmap-bot") + store = GitHubRoadmapStore(REPO, board_owner="example", board_number=1, runner=github) + return github, store + + +def test_a_round_judging_50_foreign_label_changes_reads_the_board_once( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """None of the changes is in the current release, so reprioritize's trigger looks up every + one of the 50 Items: all of them, and the job records the changes carry, come from the one + listing the round's store reads.""" + github, store = _github_round(tmp_path, monkeypatch, _labeled(50, "alice")) + ran = run_due_jobs( + REPO, + store, + batch={("poll", "", ""): 1}, + table=build_stub_table(), + data_dir=tmp_path, + now=NOW, + ) + sent = [" ".join(args) for args in github.graphql_calls()] + assert ( + ran, + sum(BOARD_BUDGET_OPERATION in args for args in sent), + sum(BOARD_ITEMS_OPERATION in args for args in sent), + sum( + "issues/" in " ".join(args) and "events" not in " ".join(args) for args in github.calls + ), + ) == ((), 1, 1, 50) + + +def test_a_poll_whose_changes_are_all_the_services_own_sends_no_graphql_request( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The Service's own events are dropped before any job record is read, so a poll with no + interval due and nothing else since the cutoff reads only the issue events.""" + github, store = _github_round(tmp_path, monkeypatch, _labeled(12, "roadmap-bot")) + ran = run_due_jobs( + REPO, + store, + batch={("poll", "", ""): 1}, + table=build_stub_table(), + data_dir=tmp_path, + now=NOW, + ) + assert (ran, github.graphql_calls(), [args[1][:24] for args in github.calls]) == ( + (), + [], + ["repos/example/roadmap/is"], + ) diff --git a/tests/test_roadmap_store_contract.py b/tests/test_roadmap_store_contract.py index 1629d935bb..755fbe7fbe 100644 --- a/tests/test_roadmap_store_contract.py +++ b/tests/test_roadmap_store_contract.py @@ -11,6 +11,7 @@ import pytest from devops_cli.exceptions.git import GitHubFileNotFoundError, GitHubOperationError +from devops_cli.exceptions.roadmap import RoadmapCardChangedError from devops_cli.exceptions.validation import InvalidVersionError from devops_cli.roadmap.github_store import GitHubRoadmapStore from devops_cli.roadmap.memory_store import InMemoryRoadmapStore, JobWrite @@ -195,6 +196,56 @@ def test_adding_an_item_puts_an_issue_on_the_board(store: InMemoryRoadmapStore) assert ([c.number for c in store.candidates()], store.item(number) is not None) == ([], True) +def test_adding_an_item_returns_it_with_its_card_and_adding_it_again_keeps_that_card( + store: InMemoryRoadmapStore, +) -> None: + """The writes that place it go to the card the add returns (#1361).""" + number = store.seed_issue("intake me") + added = store.add_item(number) + store.set_field(added, ItemField.STATUS, "Ready") + again = store.add_item(number) + assert ( + added.number, + added.card_id is not None, + again.card_id == added.card_id, + again.status, + [card.id for card in store.cards()] == [added.card_id], + ) == (number, True, True, "Ready", True) + + +def test_an_item_whose_card_is_not_its_own_is_not_on_the_board( + store: InMemoryRoadmapStore, +) -> None: + """A write goes to the Item's card: one built without the card it has raises, and writes + nothing.""" + item = store.add_item(store.seed_issue("intake me")) + before = len(store.job_writes()) + with pytest.raises(GitHubOperationError, match="not on the board"): + store.set_field(item.model_copy(update={"card_id": None}), ItemField.STATUS, "Ready") + assert store.job_writes()[before:] == [] + + +def test_changes_since_leaves_out_the_changes_one_actor_made( + store: InMemoryRoadmapStore, clock: SteppedClock +) -> None: + since = clock.now + number = store.seed_issue("labeled twice") + store.as_actor("roadmap-bot").label_issue(number, "type/bug") + store.as_actor("alice").label_issue(number, "scope/cli") + changes = store.changes_since(since, except_actor="roadmap-bot") + assert [(change.actor, change.label) for change in changes] == [("alice", "scope/cli")] + + +def test_changes_since_with_an_empty_actor_leaves_out_nothing( + store: InMemoryRoadmapStore, clock: SteppedClock +) -> None: + since = clock.now + number = store.seed_issue("labeled by a nameless actor") + store.as_actor("").label_issue(number, "type/bug") + changes = store.changes_since(since, except_actor="") + assert [(change.actor, change.label) for change in changes] == [("", "type/bug")] + + def test_adding_a_pull_request_raises(store: InMemoryRoadmapStore) -> None: number = store.seed_issue("a pull request", pull_request=True) with pytest.raises(GitHubOperationError, match="not an issue"): @@ -252,6 +303,84 @@ def test_a_persons_change_differs_from_the_job_record(store: InMemoryRoadmapStor ) == ("P1-High", "P2-Medium") +# ── A job never reverts a change it did not read (ADR 0002, #1361) ──────────── + + +def test_a_job_write_of_a_field_a_person_changed_since_it_was_read_raises_and_writes_nothing( + store: InMemoryRoadmapStore, +) -> None: + item = store.item(store.seed_issue("prioritize me", on_board=True)) + assert item is not None + store.as_actor("alice").set_field(item, ItemField.PRIORITY, "P1-High") + before = len(store.job_writes()) + with pytest.raises(RoadmapCardChangedError, match="Priority is P1-High") as raised: + store.set_field(item, ItemField.PRIORITY, "P3-Low") + kept = store.item(item.number) + assert ( + store.job_writes()[before:], + kept.priority if kept else None, + {key: raised.value.details[key] for key in ("card", "field", "read", "now")}, + ) == ( + [], + "P1-High", + {"card": f"#{item.number}", "field": "Priority", "read": None, "now": "P1-High"}, + ) + + +def test_a_persons_change_stays_caught_after_the_job_wrote_another_field_of_the_card( + store: InMemoryRoadmapStore, +) -> None: + item = store.item(store.seed_issue("size and prioritize me", on_board=True)) + assert item is not None + store.as_actor("alice").set_field(item, ItemField.PRIORITY, "P1-High") + store.set_field(item, ItemField.EFFORT, "Low") + with pytest.raises(RoadmapCardChangedError): + store.set_field(item, ItemField.PRIORITY, "P3-Low") + kept = store.item(item.number) + assert ((kept.effort, kept.priority) if kept else None) == ("Low", "P1-High") + + +def test_a_job_write_of_the_value_the_card_holds_now_goes_ahead( + store: InMemoryRoadmapStore, +) -> None: + """Writing what someone else already set reverts nothing, such as the Status the board sets + on a card just added.""" + item = store.add_item(store.seed_issue("intake me")) + store.as_actor("alice").set_field(item, ItemField.STATUS, "Backlog") + store.set_field(item, ItemField.STATUS, "Backlog") + written = store.item(item.number) + assert ((written.status, written.job_record) if written else None) == ( + "Backlog", + {ItemField.STATUS: "Backlog"}, + ) + + +def test_the_jobs_own_write_is_what_its_next_write_of_that_field_compares( + store: InMemoryRoadmapStore, +) -> None: + """A revert, then a decision, on one field of an Item read once: both go ahead.""" + item = store.item(store.seed_issue("revert then decide", on_board=True)) + assert item is not None + store.set_field(item, ItemField.PRIORITY, "P2-Medium") + store.set_field(item, ItemField.PRIORITY, "P0-Critical") + written = store.item(item.number) + assert (written.priority if written else None) == "P0-Critical" + + +def test_a_job_card_write_of_a_field_a_person_changed_since_it_was_read_raises( + store: InMemoryRoadmapStore, +) -> None: + number = store.seed_issue("a card", on_board=True) + (card,) = [card for card in store.cards() if card.number == number] + person_view = store.as_actor("alice") + person_view.set_card_field(card, ItemField.STATUS, "Ready") + before = len(store.job_writes()) + with pytest.raises(RoadmapCardChangedError, match="Status"): + store.set_card_field(card, ItemField.STATUS, "Done") + kept = store.item(number) + assert (store.job_writes()[before:], kept.status if kept else None) == ([], "Ready") + + def test_an_item_the_store_never_wrote_has_an_empty_job_record( store: InMemoryRoadmapStore, ) -> None: