From 287b9cdb0b28603c3c33dfbeaf8a265679173a25 Mon Sep 17 00:00:00 2001 From: Simon Koudijs Date: Wed, 25 Nov 2026 09:48:37 +0000 Subject: [PATCH 1/2] fix(commitrequest)!: author an empty commit like the saver's other commits, and close small TODO items A CommitRequest's author is resolved by the same ResolveAuthor that names every write, but the controller kept only the username, so the empty commit of a save no window reached was signed "oidc:alice " while the person's window commits read "Alice Jansen ". status.author is now an object {username, name, email}, the attach carries the whole UserInfo, and the empty commit is signed by the shared author code. Windows still match on the username. - Rename the request-record concept to empty commit: PendingWriteEmptyCommit ("empty_commit"), decideEmptyCommit, buildEmptyCommitWrite, executeEmptyCommit. - Frame the empty commit with requestTemplate, as its API doc already promised. - Decide saves that expire in the same pass in registration order, not map order. - E6 stops its editing goroutine through DeferCleanup when its Eventually fails. - Nits: a doubled doc comment on commitWindowFor; the kstatus test case named after closeDelay, whose fixture also still had Ready=False while waiting. - TODO.md brought up to date with v0.56.0; goconst noted as not enabled at all. BREAKING CHANGE: CommitRequest status.author is an object with username, name and email instead of a string, at schema revision 2. Delete every CommitRequest before upgrading, on the control cluster and on source clusters that serve them, and apply commitrequest-crd.yaml on those source clusters: one stored request with a string author stops every CommitRequest on its cluster from being served. See docs/UPGRADING.md. Co-Authored-By: Claude Opus 5.5 --- api/v1alpha3/commitrequest_schema_test.go | 1 + api/v1alpha3/commitrequest_types.go | 36 +++++++--- api/v1alpha3/zz_generated.deepcopy.go | 20 ++++++ .../bases/configbutler.ai_commitrequests.yaml | 31 +++++++-- docs/TODO.md | 32 ++++----- docs/UPGRADING.md | 33 +++++++++ docs/architecture.md | 5 +- docs/commit-messages.md | 2 +- docs/configuration.md | 18 +++-- .../gittarget-branch-worker-pending-writes.md | 4 +- docs/design/push-cooldown.md | 2 +- docs/spec/commit-window-refactor.md | 2 +- docs/spec/commitrequest-design.md | 2 +- docs/spec/status-conditions-guide.md | 2 +- internal/controller/commitrequest_core.go | 46 ++++++++++--- .../controller/commitrequest_core_test.go | 29 +++++--- internal/controller/commitrequest_decide.go | 2 +- .../controller/commitrequest_kstatus_test.go | 4 +- internal/git/attribution_outcome_test.go | 12 ++-- internal/git/branch_worker.go | 6 +- internal/git/branch_worker_metrics_test.go | 2 +- internal/git/commit_executor.go | 25 +++---- internal/git/commit_request_attach.go | 16 ++--- internal/git/commit_request_attach_loop.go | 58 +++++++++------- internal/git/commit_request_attach_test.go | 6 +- internal/git/commit_request_empty_test.go | 69 ++++++++++++++++++- internal/git/commit_request_folder_test.go | 2 +- internal/git/network_bound_test.go | 4 +- internal/git/pending_writes.go | 10 +-- internal/git/pending_writes_loop.go | 8 +-- internal/git/request_template_test.go | 32 ++++++++- internal/git/types.go | 6 +- internal/git/window_admission_test.go | 6 +- internal/git/window_model_test.go | 6 +- internal/git/window_set_test.go | 18 ++++- internal/git/write_gate.go | 4 +- internal/git/write_gate_test.go | 2 +- internal/watch/event_router_test.go | 2 +- test/e2e/bi_directional_echoes_e2e_test.go | 10 ++- test/e2e/commit_request_e2e_test.go | 6 +- test/e2e/source_cluster_e2e_test.go | 2 +- 41 files changed, 415 insertions(+), 168 deletions(-) diff --git a/api/v1alpha3/commitrequest_schema_test.go b/api/v1alpha3/commitrequest_schema_test.go index 2f8ac120f..b81713517 100644 --- a/api/v1alpha3/commitrequest_schema_test.go +++ b/api/v1alpha3/commitrequest_schema_test.go @@ -20,6 +20,7 @@ import ( // the new hash here. var commitRequestSchemaHashes = map[int]string{ 1: "395df39c86bc4c0350eb2c476dd0ae02db2a7513f03962103416123b0cbb5476", + 2: "41060fecb5109059cb04f03124c60d3166a1b3e8b55ee225382a556087a2f5fc", } // commitRequestRevisionLine is the last line of the kind's description. diff --git a/api/v1alpha3/commitrequest_types.go b/api/v1alpha3/commitrequest_types.go index 147ef5c71..1ef47d814 100644 --- a/api/v1alpha3/commitrequest_types.go +++ b/api/v1alpha3/commitrequest_types.go @@ -177,6 +177,26 @@ type CommitRequestWindow struct { MaxDuration *metav1.Duration `json:"maxDuration,omitempty"` } +// CommitRequestAuthor is who created a CommitRequest. A commit the request +// makes on its own, with nothing else in it, is authored by this person. +type CommitRequestAuthor struct { + // Username is the Kubernetes username. The request saves only writes + // whose author has this username. + // +required + // +kubebuilder:validation:MinLength=1 + Username string `json:"username"` + + // Name is the display name the login carried, such as the OIDC name + // claim. Omitted, a commit names the author by username. + // +optional + Name string `json:"name,omitempty"` + + // Email is the address the login carried, such as the OIDC email claim. + // Omitted, a commit gets an address made from the username. + // +optional + Email string `json:"email,omitempty"` +} + // CommitRequestStatus defines the observed state of CommitRequest. Progress // and outcome are reported entirely through conditions (kstatus-compatible), // so the object carries no lifecycle phase string: @@ -198,11 +218,11 @@ type CommitRequestStatus struct { ObservedGeneration int64 `json:"observedGeneration,omitempty"` // Author is who created this request, as the audit events of the cluster - // it was created on name them. Empty when they name nobody, or when author - // attribution is off: then the request saves only writes that name nobody - // either. + // it was created on name them. Omitted when they name nobody, or when + // author attribution is off: then the request saves only writes that name + // nobody either. // +optional - Author string `json:"author,omitempty"` + Author *CommitRequestAuthor `json:"author,omitempty"` // Conditions are the latest observations of this CommitRequest's state. // Reconciling and Stalled follow kstatus. @@ -274,7 +294,7 @@ type CommitRequestStatus struct { // +kubebuilder:printcolumn:name="GitTarget",type=string,JSONPath=`.spec.gitTargetRef.name` // +kubebuilder:printcolumn:name="Ready",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].status` // +kubebuilder:printcolumn:name="Reason",type=string,JSONPath=`.status.conditions[?(@.type=="Ready")].reason` -// +kubebuilder:printcolumn:name="Author",type=string,JSONPath=`.status.author` +// +kubebuilder:printcolumn:name="Author",type=string,JSONPath=`.status.author.username` // +kubebuilder:printcolumn:name="Commit",type=string,JSONPath=`.status.commit` // +kubebuilder:printcolumn:name="Pushed",type=string,JSONPath=`.status.conditions[?(@.type=="Pushed")].status`,priority=1 // +kubebuilder:printcolumn:name="Applied",type=string,JSONPath=`.status.conditions[?(@.type=="Applied")].status`,priority=1 @@ -289,7 +309,7 @@ type CommitRequestStatus struct { // spec is immutable, and status.commit reports the commit once it is on the // remote. // -// Schema revision 1, compatible from revision 1. +// Schema revision 2, compatible from revision 2. type CommitRequest struct { metav1.TypeMeta `json:",inline"` @@ -331,8 +351,8 @@ func (s *CommitRequest) GitTargetKey() types.NamespacedName { // schema this operator was built with, and the oldest revision it can serve: the last line of the // kind's description. const ( - CommitRequestSchemaRevision = 1 - CommitRequestSchemaFloor = 1 + CommitRequestSchemaRevision = 2 + CommitRequestSchemaFloor = 2 ) func init() { diff --git a/api/v1alpha3/zz_generated.deepcopy.go b/api/v1alpha3/zz_generated.deepcopy.go index e666b9eef..919a62852 100644 --- a/api/v1alpha3/zz_generated.deepcopy.go +++ b/api/v1alpha3/zz_generated.deepcopy.go @@ -397,6 +397,21 @@ func (in *CommitRequest) DeepCopyObject() runtime.Object { return nil } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *CommitRequestAuthor) DeepCopyInto(out *CommitRequestAuthor) { + *out = *in +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CommitRequestAuthor. +func (in *CommitRequestAuthor) DeepCopy() *CommitRequestAuthor { + if in == nil { + return nil + } + out := new(CommitRequestAuthor) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CommitRequestList) DeepCopyInto(out *CommitRequestList) { *out = *in @@ -453,6 +468,11 @@ func (in *CommitRequestSpec) DeepCopy() *CommitRequestSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CommitRequestStatus) DeepCopyInto(out *CommitRequestStatus) { *out = *in + if in.Author != nil { + in, out := &in.Author, &out.Author + *out = new(CommitRequestAuthor) + **out = **in + } if in.Conditions != nil { in, out := &in.Conditions, &out.Conditions *out = make([]v1.Condition, len(*in)) diff --git a/config/crd/bases/configbutler.ai_commitrequests.yaml b/config/crd/bases/configbutler.ai_commitrequests.yaml index ce6381390..4d701bde5 100644 --- a/config/crd/bases/configbutler.ai_commitrequests.yaml +++ b/config/crd/bases/configbutler.ai_commitrequests.yaml @@ -24,7 +24,7 @@ spec: - jsonPath: .status.conditions[?(@.type=="Ready")].reason name: Reason type: string - - jsonPath: .status.author + - jsonPath: .status.author.username name: Author type: string - jsonPath: .status.commit @@ -60,7 +60,7 @@ spec: spec is immutable, and status.commit reports the commit once it is on the remote. - Schema revision 1, compatible from revision 1. + Schema revision 2, compatible from revision 2. properties: apiVersion: description: |- @@ -251,10 +251,29 @@ spec: author: description: |- Author is who created this request, as the audit events of the cluster - it was created on name them. Empty when they name nobody, or when author - attribution is off: then the request saves only writes that name nobody - either. - type: string + it was created on name them. Omitted when they name nobody, or when + author attribution is off: then the request saves only writes that name + nobody either. + properties: + email: + description: |- + Email is the address the login carried, such as the OIDC email claim. + Omitted, a commit gets an address made from the username. + type: string + name: + description: |- + Name is the display name the login carried, such as the OIDC name + claim. Omitted, a commit names the author by username. + type: string + username: + description: |- + Username is the Kubernetes username. The request saves only writes + whose author has this username. + minLength: 1 + type: string + required: + - username + type: object branch: description: Branch is the branch the commit is made on. Set once the request ends. diff --git a/docs/TODO.md b/docs/TODO.md index 98a50a923..f6e7097c8 100644 --- a/docs/TODO.md +++ b/docs/TODO.md @@ -2,8 +2,8 @@ The open work, in one list. Each item is one or two lines with a code pointer or the design page that argues it. Ranked within each group, most urgent first. **Before the next release** marks what -should land before the next tag is cut (the last release is v0.55.0). Checked against `main` at -`1bc97904` on 2026-10-24. +should land before the next tag is cut (the last release is v0.56.0). Checked against `main` at +`a13c23d9` on 2026-11-25. ## Before the next release @@ -112,14 +112,6 @@ Their argument for each is in [gitops-api-open-asks.md](future/gitops-api-open-a the wall clock, so the model sends each late write inside it). Two guards no input reaches are pinned by unit tests instead: the outage ending when its writes settle with no push, and an attach that closes a later window in the same pass. -- [ ] `expireWaitingCommitRequests` ranges over a map, so empty commits for saves that expire in - the same pass land in random order; sort by `seq` (`internal/git/commit_request_attach_loop.go`). -- [ ] `buildRequestRecordWrite` keeps only the username (`UserInfo{Username: pcr.author}`); carry the - full `UserInfo` so a record commit has the same author identity as a window commit. -- [ ] A record commit skips `requestTemplate`, though its doc comment says it is phrased like every - other commit; fix the code or the comment. -- [ ] Nits: a doubled doc comment on `commitWindowFor`; "close-delay" in the test names in - `internal/controller/commitrequest_kstatus_test.go`. - [ ] **Parent observation, step 1**: keep parent availability and its timestamp after the write branch exists, from existing advertisements, with no extra connections. [gittarget-parent-observation.md](design/gittarget-parent-observation.md#implementation-and-validation). @@ -153,7 +145,7 @@ Their argument for each is in [gitops-api-open-asks.md](future/gitops-api-open-a - [ ] Accepted for now: no rate bound on push deliveries. Folding bounds the queue, not the rate, so a `GitReceiver` token holder can keep a worker reading; a per-worker cooldown would bound it. - [ ] Re-assess unifying the pending-write kinds - (grouped window, resync and request record, since #450 removed the atomic kind). Deferred. + (grouped window, resync and empty commit, since #450 removed the atomic kind). Deferred. - [ ] Improve queue and worker observability, with more high-load tests. ## Watch plane @@ -208,19 +200,21 @@ Their argument for each is in [gitops-api-open-asks.md](future/gitops-api-open-a Address before the next feature that widens commit-message, snapshot or write-window behavior. - [ ] **Run image-refresh only when its inputs change**, a path filter in `ci.yml`; it removes a 14–18 minute leg from most PRs. [e2e-suite-trim.md](design/e2e-suite-trim.md). -- [ ] **F-f: E6 can leak its editing goroutine**: `close(stop)` runs only after the `Eventually` - succeeds. Use `DeferCleanup` (`test/e2e/bi_directional_echoes_e2e_test.go`). - [ ] The e2e detail gaps and redundancy tables in [e2e-suite-trim.md](design/e2e-suite-trim.md): four specs that look tested and are not, then the moves and merges. - [ ] `SetDefaultEventuallyTimeout` is global and set in 17 e2e files, so the last `Describe` body - built wins; use per-spec timeouts (`Eventually(...).WithTimeout`). -- [ ] e2e for the commit-window stack: two authors editing disjoint files at once, then a - `path_conflict`; E5 extended to the withheld-field carry; a restart of a source cluster's - controller with a save in flight; `catchUp: AfterPush` at shutdown. + built wins; use per-spec timeouts (`Eventually(...).WithTimeout`). Moving each call into a + `BeforeEach` is not enough: Ginkgo runs top-level containers in random order, so a spec that sets + none would inherit whichever container ran before it, and a `BeforeAll` runs before its own + container's `BeforeEach`. Needs a full e2e run to verify. +- [ ] e2e for the commit-window stack: E5 extended to the withheld-field carry; a restart of a + source cluster's controller with a save in flight; `catchUp: AfterPush` at shutdown. (Two and + three authors at once and a `path_conflict` are covered since #478.) - [ ] e2e Test A: a delete missed while the controller is scaled to 0; then Tests B and C. [e2e-coverage-gaps-and-improvements-plan.md](design/e2e-coverage-gaps-and-improvements-plan.md). -- [ ] Re-enable `goconst` with a path-scoped exclusion (`test/`, `internal/git/commit.go`) instead - of the repo-wide disable in [.golangci.yml](../.golangci.yml). +- [ ] Enable `goconst`. It is not in the `enable` list of [.golangci.yml](../.golangci.yml) (only a + `_test.go` exclusion names it), so it never runs; enable it with a path-scoped exclusion (`test/`, + `internal/git/commit.go`). - [ ] Release-image reuse PRs 2, 3 and 5 ([release-image-reuse-plan.md](design/release-image-reuse-plan.md)). - [ ] Metrics Phase 5: dashboard JSON, recording and alert rules ([metrics-observability-plan.md](design/metrics-observability-plan.md) §7). diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md index 79976bf3b..e64af599a 100644 --- a/docs/UPGRADING.md +++ b/docs/UPGRADING.md @@ -7,6 +7,39 @@ guidance that the changelog's breaking-change entries link to. We are pre-1.0, so breaking changes bump the **minor** version (release-please is configured with `bump-minor-pre-major`) rather than the major. Read the relevant entry before upgrading across it. +## A `CommitRequest`'s `status.author` is an object + +`status.author` names the request's creator as `username`, plus the `name` and `email` their login +carried (an OIDC name and email claim), when the audit event has them: + +```yaml +status: + author: + username: oidc:alice + name: Alice Jansen + email: alice@corp.example +``` + +It was the username alone. Read `.status.author.username` where you read `.status.author`; the +`Author` column of `kubectl get commitrequests` already does. With the name and email kept, an empty +commit (`whenNothingToCommit: CommitEmpty`, when no write reached the save in time) is authored as +`Alice Jansen `, like the person's other commits, instead of by username. Its +message is also framed by the target's `requestTemplate`, as every other save's is. + +A stored `CommitRequest` whose `status.author` is still a string cannot be read by this release, and +one such object stops every `CommitRequest` on that cluster from being served, not only itself. +Finished requests stay for 48 hours, so there usually are some. Before upgrading, let the saves in +progress finish, then delete every `CommitRequest` on the cluster GitOps Reverser runs in and on +each source cluster that serves them (`spec.commitRequests` on its `KubeProvider`): + +```bash +kubectl delete commitrequests --all --all-namespaces +``` + +The `CommitRequest` CRD is at schema revision 2. On each such source cluster, apply this release's +`commitrequest-crd.yaml` too: a revision 1 CRD rejects the new `status.author`, so a request there +is never claimed. + ## An empty repository gets its default branch first In an empty repository with `spec.parentBranch` omitted, a `GitBranch` whose `spec.branch` is not diff --git a/docs/architecture.md b/docs/architecture.md index 68816d542..e5837df0a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -423,8 +423,9 @@ fields: default) and `maxDuration` (default `2s`). A request never opens a window; only writes do. - `spec.whenNothingToCommit`: `Resolve` (default) or `CommitEmpty`, which records the message in an empty commit when the request ends with nothing to commit. -- `status.author`: the creator, as the request's audit event names them; empty when it names nobody, - and then the request can attach only to an unnamed window. +- `status.author`: the creator, as the request's audit event names them: `username`, and the `name` + and `email` the login carried, if any. Omitted when it names nobody, and then the request can + attach only to an unnamed window. - `status.conditions`: kstatus-compatible. **Ready** is the summary (Unknown while the save runs, True once the request reached a terminal outcome that is not an error: a pushed commit, or a benign no-commit); **Reconciling**/**Stalled** are the kstatus progress/blocked pair. **Pushed** reports diff --git a/docs/commit-messages.md b/docs/commit-messages.md index 540c1ca3f..e13acb855 100644 --- a/docs/commit-messages.md +++ b/docs/commit-messages.md @@ -15,7 +15,7 @@ message only on some branch passes validation and falls back at commit time. | Input, in precedence order | Message source | |---|---| -| Attached [save request](configuration.md#commitrequest) **and** `requestTemplate` set | `requestTemplate`, with the request's message as `.RequestMessage` | +| [Save request](configuration.md#commitrequest) message, on its window or its empty commit, **and** `requestTemplate` set | `requestTemplate`, with the request's message as `.RequestMessage`; an empty commit lists no resources | | Non-empty literal override, including an attached [save request](configuration.md#commitrequest) | Exact supplied text | | Live window of any size | `liveTemplate` | | Atomic snapshot or resync | `reconcileTemplate` | diff --git a/docs/configuration.md b/docs/configuration.md index d5ad6497a..2acd36a61 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -1487,10 +1487,11 @@ ever update. #### Commit message templates Three templates decide how a commit is phrased: `liveTemplate` for a live window, -`reconcileTemplate` for an atomic snapshot or resync, and `requestTemplate` for a window a -[save request](#commitrequest) attached to. Each is a Go template over a documented context, -checked when the target reconciles rather than at commit time, and each has a built-in default, so a -target that sets none still writes useful messages. +`reconcileTemplate` for an atomic snapshot or resync, and `requestTemplate` for a commit a +[save request](#commitrequest) gave its message: the window it attached to, or its empty commit. +Each is a Go template over a documented context, checked when the target reconciles rather than at +commit time, and each has a built-in default, so a target that sets none still writes useful +messages. ```yaml spec: @@ -3258,7 +3259,9 @@ A request no grant admits fails before it attaches: `Ready=False`, `Stalled=True A request's author is found from its own audit event, on the cluster it was created on, the same way an edit's author is: from the same index, with the same `--author-attribution-grace`. So a save attaches only to its creator's windows, by the ordinary author rule, and `status.author` names the -creator. The author is recorded in the request's first status write, before it attaches. Create a +creator: `username`, plus the `name` and `email` the login carried (an OIDC name and email claim), +when it carried them. The author is recorded in the request's first status write, before it +attaches. Create a request on a source cluster as JSON: `kubectl` and browsers send JSON, and an API server that drops the audit event of a YAML body loses the save's author without an error. @@ -3286,8 +3289,9 @@ namespace decides only whether a grant admits it. reason, without changing Git. - `Resolve` (the default) finishes without a commit. -- `CommitEmpty` records `spec.message` in an empty commit, authored like any other commit by the - request's submitter. It requires `spec.message`. +- `CommitEmpty` records `spec.message` in an empty commit, authored by the request's submitter + with the same name and email as their other commits, and framed by `requestTemplate` like any + other save. It requires `spec.message`. | Outcome | `Resolve` | `CommitEmpty` | |---|---|---| diff --git a/docs/design/gittarget-branch-worker-pending-writes.md b/docs/design/gittarget-branch-worker-pending-writes.md index b9a79e50d..eb7bd0e04 100644 --- a/docs/design/gittarget-branch-worker-pending-writes.md +++ b/docs/design/gittarget-branch-worker-pending-writes.md @@ -56,7 +56,7 @@ message, and save were still intact. Step 2 fixes it. Three pieces of loop-owned state: - **`pendingWrites`**: decided entries, in order, that are not yet published. Entry kinds are the existing - `PendingWrite` kinds (window, atomic, resync, request record). Accepted entries + `PendingWrite` kinds (window, atomic, resync, empty commit). Accepted entries survive saturation. There is no `owedSnapshot` entry (a placeholder that would request a snapshot again) replacing discarded accepted work. - **`checkout`**: `{root, rootGen, applied}`. The checkout equals `root` plus the commits of @@ -144,7 +144,7 @@ Source review at `373bf8d7` confirms the pending-writes path and step 4 refusal `skipUnchangedLiveUpdate` stored the content hash before enqueue, so a refused UPDATE was skipped on cursor resume, which then advanced the cursor. - **The byte budget was incomplete** (fixed in step 5b). `syncAdmission` used `pendingWritesBytes` - and a pending retry. `buildRequestRecordWrite` and `buildRefusalTouchWrite` left `ByteSize` at + and a pending retry. `buildEmptyCommitWrite` and `buildRefusalTouchWrite` left `ByteSize` at zero, so repeated empty saves grew the pending writes without reaching the byte threshold, and payload on the FIFO was not counted at all. - **Retry pacing had an exception** (fixed after the 2026-10-04 review). `decide` let resyncs diff --git a/docs/design/push-cooldown.md b/docs/design/push-cooldown.md index bb35a4bb1..0d89f9bb1 100644 --- a/docs/design/push-cooldown.md +++ b/docs/design/push-cooldown.md @@ -106,7 +106,7 @@ when it cannot sit beside them: | Overlapping footprints | `path-conflict` | | The retained-byte budget | `buffer-limit` | | `commit.window.idleTimeout: 0s` | every event commits on arrival | -| Resync snapshots and request records | they commit outside the windows | +| Resync snapshots and the empty commits of saves no window reached | they commit outside the windows | Several `GitTarget`s sharing a branch is the multi-tenant shape, and there every switch between targets is a close: diff --git a/docs/spec/commit-window-refactor.md b/docs/spec/commit-window-refactor.md index 38c2eb2a1..3cbfe1780 100644 --- a/docs/spec/commit-window-refactor.md +++ b/docs/spec/commit-window-refactor.md @@ -139,7 +139,7 @@ between: - `PendingWriteAtomic` represents one caller-defined atomic write. - `PendingWriteResync` represents one GitTarget's snapshot, applied by mark-and-sweep. -- `PendingWriteRequestRecord` records a `CommitRequest`'s message in an empty +- `PendingWriteEmptyCommit` records a `CommitRequest`'s message in an empty commit when no window reached the request and it asked for `whenNothingToCommit: CommitEmpty`. diff --git a/docs/spec/commitrequest-design.md b/docs/spec/commitrequest-design.md index cacce0e0c..1c635de0d 100644 --- a/docs/spec/commitrequest-design.md +++ b/docs/spec/commitrequest-design.md @@ -169,7 +169,7 @@ route, so the fact follower reads those audit facts at all. | Outcome | The request | |---|---| | attribution is off | names no author, and nothing waits for one | -| a fact names the creator | names them, in `status.author` | +| a fact names the creator | names them, in `status.author` (`username`, and the `name` and `email` the login carried) | | no fact, on a provider whose `AuditFactsReceived` is not `True` | names no author: the cluster sends no audit | | no fact, on a provider that has received facts | `Ready=True`, reason `AuthorUnresolved`: its fact went missing, so it saves nothing rather than take the window that should stay unattributed | diff --git a/docs/spec/status-conditions-guide.md b/docs/spec/status-conditions-guide.md index c6e35da52..9eed1d773 100644 --- a/docs/spec/status-conditions-guide.md +++ b/docs/spec/status-conditions-guide.md @@ -359,7 +359,7 @@ Canonical reads: - failed: `Ready=False`, `Stalled=True`, reason `FinalizeFailed`, `NotAllowed`, `GitTargetNotFound` or `SaveInProgress` → kstatus Failed -`status.author` empty means no audit fact named the creator, or attribution is off: the request +`status.author` omitted means no audit fact named the creator, or attribution is off: the request claims no actor and can attach only to an unnamed window. That does not itself determine the Git author: the attached watch window is configured-author (the committer) when watch attribution is disabled, or explicitly unresolved when watch attribution ran but could not name an actor. diff --git a/internal/controller/commitrequest_core.go b/internal/controller/commitrequest_core.go index 6b2452786..e76cf557a 100644 --- a/internal/controller/commitrequest_core.go +++ b/internal/controller/commitrequest_core.go @@ -367,7 +367,7 @@ func (c *commitRequestCore) claim( return commitRequestRequeueNow, err } p.log.Info("CommitRequest claimed", "name", client.ObjectKeyFromObject(cr), - "gitTarget", client.ObjectKeyFromObject(target), "author", author) + "gitTarget", client.ObjectKeyFromObject(target), "author", author.Username) return c.drive(ctx, p, cr, target, provider) } @@ -385,9 +385,9 @@ func (c *commitRequestCore) claim( // rather than take the unnamed window. A provider that cannot be read then is an error, retried. func (c *commitRequestCore) creator( ctx context.Context, cr *configbutleraiv1alpha3.CommitRequest, provider *configbutleraiv1alpha3.KubeProvider, -) (string, bool, error) { +) (git.UserInfo, bool, error) { if c.authors == nil { - return "", false, nil + return git.UserInfo{}, false, nil } c.streams.ensure(provider.AuditRoute()) user, outcome := c.authors.ResolveAuthor(ctx, watch.AuthorQuery{ @@ -400,26 +400,30 @@ func (c *commitRequestCore) creator( Creation: true, }) if outcome.NamesActor() { - return user.Username, false, nil + return user, false, nil } if outcome == git.AttributionNotAttempted { - return "", false, nil + return git.UserInfo{}, false, nil } var current configbutleraiv1alpha3.KubeProvider if err := c.reader.Get(ctx, provider.Key(), ¤t); err != nil { - return "", false, fmt.Errorf("read KubeProvider %s after the author wait: %w", provider.Key(), err) + return git.UserInfo{}, false, fmt.Errorf("read KubeProvider %s after the author wait: %w", provider.Key(), err) } - return "", apimeta.IsStatusConditionTrue(current.Status.Conditions, KubeProviderConditionAuditFactsReceived), nil + return git.UserInfo{}, apimeta.IsStatusConditionTrue( + current.Status.Conditions, + KubeProviderConditionAuditFactsReceived, + ), nil } // writeClaim writes the first status of a request: its author, the GitTarget that admitted it, and // Ready=Unknown. A conflict reads the request again, and the claim is written onto it only while it is // still unclaimed; otherwise claimed=false, and the next step decides from what is there. func (c *commitRequestCore) writeClaim( - ctx context.Context, p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest, author, targetUID string, + ctx context.Context, p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest, author git.UserInfo, + targetUID string, ) (bool, error) { for attempt := 1; ; attempt++ { - cr.Status.Author = author + cr.Status.Author = commitRequestAuthor(author) cr.Status.GitTargetUID = targetUID markCommitRequestProgressing(cr, "", "") err := p.store.updateStatus(ctx, cr) @@ -437,6 +441,26 @@ func (c *commitRequestCore) writeClaim( } } +// commitRequestAuthor is the status.author that records user: nil when attribution named nobody. +// The UID is left out; nothing the worker does with a request's author reads it. +func commitRequestAuthor(user git.UserInfo) *configbutleraiv1alpha3.CommitRequestAuthor { + if user.Username == "" { + return nil + } + return &configbutleraiv1alpha3.CommitRequestAuthor{ + Username: user.Username, Name: user.DisplayName, Email: user.Email, + } +} + +// requestAuthorUserInfo is the identity status.author records, as ResolveAuthor returned it, so a +// commit the request makes on its own is signed as that person's other commits are. +func requestAuthorUserInfo(author *configbutleraiv1alpha3.CommitRequestAuthor) git.UserInfo { + if author == nil { + return git.UserInfo{} + } + return git.UserInfo{Username: author.Username, DisplayName: author.Name, Email: author.Email} +} + // reread reads cr again; same is false when it is gone or was replaced by another request of its name. func (c *commitRequestCore) reread( ctx context.Context, p commitRequestPath, cr *configbutleraiv1alpha3.CommitRequest, @@ -453,7 +477,7 @@ func (c *commitRequestCore) attachFor(cr *configbutleraiv1alpha3.CommitRequest) window := resolveRequestWindow(cr.Spec) attribution := git.AttributionNotAttempted switch { - case cr.Status.Author != "": + case cr.Status.Author != nil: attribution = git.AttributionResolved case c.authors != nil: attribution = git.AttributionUnresolved @@ -463,7 +487,7 @@ func (c *commitRequestCore) attachFor(cr *configbutleraiv1alpha3.CommitRequest) Namespace: cr.Namespace, Name: cr.Name, UID: string(cr.UID), - Author: cr.Status.Author, + Author: requestAuthorUserInfo(cr.Status.Author), Attribution: attribution, GitTargetName: key.Name, GitTargetNamespace: key.Namespace, diff --git a/internal/controller/commitrequest_core_test.go b/internal/controller/commitrequest_core_test.go index 2660b8729..b81596ee8 100644 --- a/internal/controller/commitrequest_core_test.go +++ b/internal/controller/commitrequest_core_test.go @@ -51,7 +51,18 @@ func (f *fakeAuthors) lookups() int { // jane is an author the audit facts name. func jane() *fakeAuthors { - return &fakeAuthors{user: git.UserInfo{Username: "jane@example.com"}, outcome: git.AttributionResolved} + return &fakeAuthors{user: janeUser, outcome: git.AttributionResolved} +} + +// janeUser is jane as her audit events name her: the login carries a display name and an email, so a +// test sees whether the whole identity, not only the username, reaches the worker. +var janeUser = git.UserInfo{Username: "jane@example.com", DisplayName: "Jane Doe", Email: "jane.doe@example.com"} + +// janeStatus is status.author as the claim records janeUser. +func janeStatus() *configv1alpha3.CommitRequestAuthor { + return &configv1alpha3.CommitRequestAuthor{ + Username: "jane@example.com", Name: "Jane Doe", Email: "jane.doe@example.com", + } } // controlPath is the control-cluster path over c. @@ -337,14 +348,14 @@ func TestCommitRequestCore_AConflictAfterTheOutcomeReappliesIt(t *testing.T) { // without looking the author up again: the claim moved the resourceVersion the fact was keyed by. func TestCommitRequestCore_ARestartResumesAClaimedSave(t *testing.T) { cr := withInProgress(newCommitRequest("save")) - cr.Status.Author = "jane@example.com" + cr.Status.Author = janeStatus() c := newCommitRequestClient(t, nil, cr) authors := jane() f := committed() serveStep(t, &commitRequestCore{reader: c, finalizer: f, authors: authors}, controlPath(c), "save") require.Len(t, f.calls, 1) - assert.Equal(t, "jane@example.com", f.calls[0].Author) + assert.Equal(t, janeUser, f.calls[0].Author, "the recorded author, name and email included") assert.Equal(t, git.AttributionResolved, f.calls[0].Attribution) assert.Zero(t, authors.lookups(), "the recorded author is used") assert.Equal(t, crReasonCommitted, commitRequestReady(t, c, "save").Reason) @@ -367,7 +378,7 @@ func TestCommitRequestCore_TheAuthorComesFromAuditAndIsClaimedFirst(t *testing.T path := controlPath(c) path.store = authorCheckingStore{typedCommitRequestStore: typedCommitRequestStore{reader: c, writer: c}, onWrite: func(cr *configv1alpha3.CommitRequest) { - if len(f.calls) == 0 && cr.Status.Author == "jane@example.com" { + if len(f.calls) == 0 && cr.Status.Author != nil && *cr.Status.Author == *janeStatus() { claimedFirst = true } }} @@ -384,8 +395,8 @@ func TestCommitRequestCore_TheAuthorComesFromAuditAndIsClaimedFirst(t *testing.T assert.Equal(t, 1, streams.Len(), "the stream of commitrequests on the route is followed") assert.True(t, claimedFirst, "the author is written before the attach") require.Len(t, f.calls, 1) - assert.Equal(t, "jane@example.com", f.calls[0].Author) - assert.Equal(t, "jane@example.com", fetchCommitRequest(t, c, "save").Status.Author) + assert.Equal(t, janeUser, f.calls[0].Author, "the attach carries the whole identity") + assert.Equal(t, janeStatus(), fetchCommitRequest(t, c, "save").Status.Author) } // authorCheckingStore calls onWrite with each status it writes. @@ -410,8 +421,8 @@ func TestCommitRequestCore_ADelayedAuditFactStillNamesTheAuthor(t *testing.T) { serveStep(t, &commitRequestCore{reader: c, finalizer: f, authors: authors}, controlPath(c), "save") require.Len(t, f.calls, 1) - assert.Equal(t, "jane@example.com", f.calls[0].Author) - assert.Equal(t, "jane@example.com", fetchCommitRequest(t, c, "save").Status.Author) + assert.Equal(t, janeUser, f.calls[0].Author, "the attach carries the whole identity") + assert.Equal(t, janeStatus(), fetchCommitRequest(t, c, "save").Status.Author) } // A request no audit fact names is refused on a provider that has received facts, since its fact went @@ -442,7 +453,7 @@ func TestCommitRequestCore_ARequestNoFactNames(t *testing.T) { serveStep(t, &commitRequestCore{reader: c, finalizer: f, authors: unnamed}, controlPath(c), "save") require.Len(t, f.calls, 1) - assert.Empty(t, f.calls[0].Author) + assert.Empty(t, f.calls[0].Author.Username) assert.Equal(t, git.AttributionUnresolved, f.calls[0].Attribution) }) } diff --git a/internal/controller/commitrequest_decide.go b/internal/controller/commitrequest_decide.go index c973265e3..6bf0dacf0 100644 --- a/internal/controller/commitrequest_decide.go +++ b/internal/controller/commitrequest_decide.go @@ -108,7 +108,7 @@ func (c *commitRequestCore) decide( "ready", commitRequestConditionStatus(current, ConditionTypeReady), "reason", readyReason, "message", readyMessage, - "author", current.Status.Author, + "author", requestAuthorUserInfo(current.Status.Author).Username, "branch", current.Status.Branch, "commit", current.Status.Commit, "gitTarget", current.GitTargetKey().String(), diff --git a/internal/controller/commitrequest_kstatus_test.go b/internal/controller/commitrequest_kstatus_test.go index 1602c7962..024cdf52a 100644 --- a/internal/controller/commitrequest_kstatus_test.go +++ b/internal/controller/commitrequest_kstatus_test.go @@ -24,9 +24,9 @@ func TestCommitRequestKstatusContract(t *testing.T) { wantMsg string }{ { - name: "in the close-delay wait", + name: "waiting for a window", conds: []map[string]interface{}{ - conditionMap(ConditionTypeReady, "False", string(git.PhaseWaitingForWindow), waitingForWindowMessage), + conditionMap(ConditionTypeReady, "Unknown", string(git.PhaseWaitingForWindow), waitingForWindowMessage), conditionMap( ConditionTypeReconciling, "True", diff --git a/internal/git/attribution_outcome_test.go b/internal/git/attribution_outcome_test.go index a7a581dfa..de55be7a2 100644 --- a/internal/git/attribution_outcome_test.go +++ b/internal/git/attribution_outcome_test.go @@ -170,7 +170,7 @@ func TestPendingCommitRequest_UnresolvedRequestAttachesToUnresolvedWindow(t *tes "an unresolved window carries no author; the sentinel is applied at the write path") request := &pendingCommitRequest{ - author: "", // an unnamed CommitRequest claims no actor + author: UserInfo{Username: ""}, // an unnamed CommitRequest claims no actor attribution: AttributionUnresolved, gitTargetName: "target", gitTargetNamespace: "default", @@ -181,7 +181,7 @@ func TestPendingCommitRequest_UnresolvedRequestAttachesToUnresolvedWindow(t *tes // The default deployment: command-author capture is off, so the request says "not // attempted" while the window says "unresolved". Neither names an actor, so they match. notAttempted := &pendingCommitRequest{ - author: "", + author: UserInfo{Username: ""}, attribution: AttributionNotAttempted, gitTargetName: "target", gitTargetNamespace: "default", @@ -195,7 +195,7 @@ func TestPendingCommitRequest_DoesNotCrossAttributionOutcomes(t *testing.T) { resolvedWindow := newOpenWindow(attributedEvent("jane@acme.com", AttributionResolved), nil) unresolvedRequest := &pendingCommitRequest{ - author: "", + author: UserInfo{Username: ""}, attribution: AttributionUnresolved, gitTargetName: "target", gitTargetNamespace: "default", @@ -204,7 +204,7 @@ func TestPendingCommitRequest_DoesNotCrossAttributionOutcomes(t *testing.T) { "an unattributed request must not claim a named actor's window") resolvedRequest := &pendingCommitRequest{ - author: "jane@acme.com", + author: UserInfo{Username: "jane@acme.com"}, attribution: AttributionResolved, gitTargetName: "target", gitTargetNamespace: "default", @@ -212,7 +212,7 @@ func TestPendingCommitRequest_DoesNotCrossAttributionOutcomes(t *testing.T) { assert.True(t, resolvedRequest.matchesWindow(resolvedWindow)) otherActor := &pendingCommitRequest{ - author: "bob@acme.com", + author: UserInfo{Username: "bob@acme.com"}, attribution: AttributionResolved, gitTargetName: "target", gitTargetNamespace: "default", @@ -224,7 +224,7 @@ func TestPendingCommitRequest_DoesNotCrossAttributionOutcomes(t *testing.T) { func TestPendingCommitRequest_StillScopedToOneGitTarget(t *testing.T) { window := newOpenWindow(attributedEvent("", AttributionUnresolved), nil) request := &pendingCommitRequest{ - author: "", + author: UserInfo{Username: ""}, attribution: AttributionUnresolved, gitTargetName: "other-target", gitTargetNamespace: "default", diff --git a/internal/git/branch_worker.go b/internal/git/branch_worker.go index 61573c2af..0f2decd0a 100644 --- a/internal/git/branch_worker.go +++ b/internal/git/branch_worker.go @@ -728,7 +728,7 @@ func (w *BranchWorker) EnqueueAttach(req *AttachCommitRequest) { w.pendingResyncsMu.Unlock() w.Log.Info("CommitRequest attach enqueued", "request", req.Namespace+"/"+req.Name, - "author", req.Author, + "author", req.Author.Username, "target", req.GitTargetNamespace+"/"+req.GitTargetName, "attach", string(req.Attach), "messageOverride", req.Message != "") @@ -3140,9 +3140,7 @@ func (w *BranchWorker) getGitProvider(ctx context.Context) (*configv1alpha3.GitP return &provider, nil } -// commitWindowFor returns the commit-window duration for ONE GitTarget. -// -// commitWindowFor resolves a GitTarget's commit window timers. +// commitWindowFor resolves ONE GitTarget's commit window timers. // // The window is a GitTarget field but this worker serves every target sharing a (provider, // branch), so resolving per target is what makes the field mean what it says. Affordable because a diff --git a/internal/git/branch_worker_metrics_test.go b/internal/git/branch_worker_metrics_test.go index 0a4ce40ac..23709d97b 100644 --- a/internal/git/branch_worker_metrics_test.go +++ b/internal/git/branch_worker_metrics_test.go @@ -251,7 +251,7 @@ func TestHandleShutdown_DrainsBufferedAttach(t *testing.T) { require.NoError(t, err) w := newMetricsTestWorker() - w.EnqueueAttach(&AttachCommitRequest{Namespace: "default", Name: "save", Author: "alice"}) + w.EnqueueAttach(&AttachCommitRequest{Namespace: "default", Name: "save", Author: UserInfo{Username: "alice"}}) require.Equal(t, int64(1), w.inflightItems.Load()) loop := newBranchWorkerEventLoop(w, time.Second) diff --git a/internal/git/commit_executor.go b/internal/git/commit_executor.go index b60b81084..2c0e7bbe2 100644 --- a/internal/git/commit_executor.go +++ b/internal/git/commit_executor.go @@ -171,7 +171,7 @@ func restoreWorktree(repo *gogit.Repository, start plumbing.Hash) error { // counts the same writes (checkoutApplied), so the two can never disagree. func (p PendingWrite) retained() bool { switch { - case p.Kind == PendingWriteRequestRecord || p.CommitRequest != nil: + case p.Kind == PendingWriteEmptyCommit || p.CommitRequest != nil: return true case p.Kind == PendingWriteResync: return p.resyncActions == nil || !p.resyncActions.empty() @@ -229,10 +229,11 @@ func (p PendingWrite) resolveMessage() messageResolution { switch { case p.Kind == PendingWriteResync: return messageResolutionPreRendered - // Framing is bound to the GROUPED kind, not merely to "carries a message". A CommitRequest - // attaches its message to an open live window, which finalizes as PendingWriteCommit, so that - // is the only write requestTemplate describes. - case p.Kind == PendingWriteCommit && + // Framing is bound to the kinds a CommitRequest's message produces, not merely to "carries a + // message": the window it attached to, which finalizes as PendingWriteCommit, and the empty + // commit of a request no window reached. Both are "a commit whose CommitRequest supplied a + // message", which is what requestTemplate frames; a resync's message is never the requester's. + case (p.Kind == PendingWriteCommit || p.Kind == PendingWriteEmptyCommit) && p.CommitMessage != "" && p.CommitConfig.Message.RequestTemplate != "": return messageResolutionRequestTemplate @@ -356,8 +357,8 @@ func (w *BranchWorker) executePendingWrite( pendingWrite *PendingWrite, ) (int, plumbing.Hash, messageResolution, error) { switch pendingWrite.Kind { - case PendingWriteRequestRecord: - return w.executeRequestRecord(ctx, worktree, *pendingWrite) + case PendingWriteEmptyCommit: + return w.executeEmptyCommit(ctx, worktree, *pendingWrite) case PendingWriteResync: // Resync writes never carry a CommitRequest, so their commit hash is unused; // report ZeroHash to keep the per-write SHA bookkeeping uniform. @@ -529,9 +530,9 @@ func (w *BranchWorker) planPendingWriteEvents( return anyChanges, changedBy, nil } -// executeRequestRecord commits a CommitRequest's message with an untouched tree: the record a -// request that ran out of time to attach leaves when it asked for whenNothingToCommit: CommitEmpty. -func (w *BranchWorker) executeRequestRecord( +// executeEmptyCommit commits a CommitRequest's message with an untouched tree: what a request that +// ran out of time to attach leaves when it asked for whenNothingToCommit: CommitEmpty. +func (w *BranchWorker) executeEmptyCommit( ctx context.Context, worktree *gogit.Worktree, pendingWrite PendingWrite, @@ -544,7 +545,7 @@ func (w *BranchWorker) executeRequestRecord( hash, err := worktree.Commit(message, options) if err != nil { return 0, plumbing.ZeroHash, messageResolutionUnsupported, - fmt.Errorf("failed to create request record commit: %w", err) + fmt.Errorf("failed to create the empty commit: %w", err) } log.FromContext(ctx).Info("Empty commit created to record a CommitRequest that found nothing to commit", "gitTarget", pendingWrite.GitTargetNamespace+"/"+pendingWrite.GitTargetName, @@ -555,7 +556,7 @@ func (w *BranchWorker) executeRequestRecord( // mayCommitEmpty reports whether this write is allowed to produce an empty commit, and so whether // its commit is worth inspecting for one. func (p PendingWrite) mayCommitEmpty() bool { - return p.Kind == PendingWriteRequestRecord || p.AllowEmpty + return p.Kind == PendingWriteEmptyCommit || p.AllowEmpty } // isEmptyCommit reports whether a commit changed no file: its tree is its first parent's. A zero diff --git a/internal/git/commit_request_attach.go b/internal/git/commit_request_attach.go index 4b05f606d..9309f0c75 100644 --- a/internal/git/commit_request_attach.go +++ b/internal/git/commit_request_attach.go @@ -122,11 +122,11 @@ type AttachCommitRequest struct { Name string UID string - // Author is the effective user that requested the finalize, captured from - // validating admission. Only a window whose author - // matches is attached; this binds "the open window" to "the requesting - // author's open window". - Author string + // Author is who created the request, as its own audit event names them: the identity + // ResolveAuthor returns for every write, so an empty commit is signed exactly as a window + // commit of the same person is. Only a window whose author has the same Username is + // attached; this binds "the open window" to "the requesting author's open window". + Author UserInfo // Attribution is the outcome of attributing THIS CommitRequest, from the command-authorship // path. It is matched alongside Author rather than inferred from it, because an empty Author // alone cannot say whether an actor was sought: it is both "attribution is off" and @@ -178,7 +178,7 @@ func (a AttachCommitRequest) id() commitRequestID { // window's timers close it, or committed locally and awaiting the push that settles it. type pendingCommitRequest struct { id commitRequestID - author string + author UserInfo attribution AttributionOutcome gitTargetName string gitTargetNamespace string @@ -263,14 +263,14 @@ func (p *pendingCommitRequest) matchesWindow(w *openWindow) bool { if p.gitTargetName != w.GitTarget || p.gitTargetNamespace != w.GitTargetNamespace { return false } - return p.author == w.Author && p.attribution.NamesActor() == w.Attribution.NamesActor() + return p.author.Username == w.Author && p.attribution.NamesActor() == w.Attribution.NamesActor() } // sameSaver reports whether two requests would save one window: the same GitTarget and the same // author, by the comparison matchesWindow makes. func (p *pendingCommitRequest) sameSaver(other *pendingCommitRequest) bool { return p.gitTargetName == other.gitTargetName && p.gitTargetNamespace == other.gitTargetNamespace && - p.author == other.author && p.attribution.NamesActor() == other.attribution.NamesActor() + p.author.Username == other.author.Username && p.attribution.NamesActor() == other.attribution.NamesActor() } // commitRequestOutcomeEntry is a resolved outcome retained for the controller to diff --git a/internal/git/commit_request_attach_loop.go b/internal/git/commit_request_attach_loop.go index 20aedc687..ae188f2fd 100644 --- a/internal/git/commit_request_attach_loop.go +++ b/internal/git/commit_request_attach_loop.go @@ -3,9 +3,11 @@ package git import ( + "cmp" "context" "errors" "fmt" + "slices" "time" "github.com/ConfigButler/gitops-reverser/api/v1alpha3" @@ -224,14 +226,14 @@ func (l *branchWorkerEventLoop) handleAttachCommitRequest(req *AttachCommitReque l.w.recordCommitRequestOutcome(id, FinalizeResult{Branch: l.w.Branch, Outcome: FinalizeSaveInProgress}) l.w.Log.Info("CommitRequest refused: an earlier save of the same author on the GitTarget is in progress", "request", id.Namespace+"/"+id.Name, "earlier", earlier.id.Namespace+"/"+earlier.id.Name, - "author", req.Author, "target", req.GitTargetNamespace+"/"+req.GitTargetName) + "author", req.Author.Username, "target", req.GitTargetNamespace+"/"+req.GitTargetName) return } l.pendingCRs[id] = pcr l.w.setCommitRequestPhase(id, PhaseWaitingForWindow) l.w.Log.Info("CommitRequest registered with worker", "request", id.Namespace+"/"+id.Name, - "author", req.Author, + "author", req.Author.Username, "target", req.GitTargetNamespace+"/"+req.GitTargetName, "attach", string(req.Attach), "attachTimeout", req.AttachTimeout.String()) @@ -335,7 +337,7 @@ func (l *branchWorkerEventLoop) noteForeignWindow() { pcr.sawForeignWindow = true l.w.Log.Info("CommitRequest is waiting on a window that belongs to someone else", "request", pcr.id.Namespace+"/"+pcr.id.Name, - "requestAuthor", pcr.author, + "requestAuthor", pcr.author.Username, "requestTarget", pcr.gitTargetNamespace+"/"+pcr.gitTargetName, "windowAuthor", foreign.Author, "windowTarget", foreign.GitTargetNamespace+"/"+foreign.GitTarget) @@ -387,7 +389,7 @@ func (l *branchWorkerEventLoop) attachToWindow(window *openWindow, pcr *pendingC l.w.setCommitRequestPhase(id, PhaseCollectingWindow) l.w.Log.Info("CommitRequest attached to open window", "request", id.Namespace+"/"+id.Name, - "author", pcr.author, + "author", pcr.author.Username, "target", pcr.gitTargetNamespace+"/"+pcr.gitTargetName, "maxDuration", pcr.maxDuration.String()) l.closeOrArmWindow() @@ -395,63 +397,69 @@ func (l *branchWorkerEventLoop) attachToWindow(window *openWindow, pcr *pendingC // expireWaitingCommitRequests resolves every request whose attach deadline passed while it was // still waiting. An attached request is not here: its window's timers close it, and whichever path -// closes the window resolves it. +// closes the window resolves it. Requests expiring in the same pass are handled in registration +// order, so their empty commits land in Git in the order the saves were made. func (l *branchWorkerEventLoop) expireWaitingCommitRequests() { now := l.w.now() - for id, pcr := range l.pendingCRs { - if pcr.attached || pcr.attachDeadline.After(now) { - continue + var expired []*pendingCommitRequest + for _, pcr := range l.pendingCRs { + if !pcr.attached && !pcr.attachDeadline.After(now) { + expired = append(expired, pcr) } + } + slices.SortFunc(expired, func(a, b *pendingCommitRequest) int { return cmp.Compare(a.seq, b.seq) }) + for _, pcr := range expired { + id := pcr.id // Which of the two refusals this is depends on whether anything was open that this // request could not have: see pendingCommitRequest.expiryOutcome. outcome := pcr.expiryOutcome() if outcome == FinalizeNoOpenWindow { // NoWindow says the save saw no writes. On a target that refuses them that is not the - // cause, and with CommitEmpty the record would say so in Git: see write_gate.go. + // cause, and with CommitEmpty the empty commit would say so in Git: see write_gate.go. if err := l.w.requestWriteRefusal(l.w.ctx, pcr); err != nil { l.resolveCommitRequest(id, FinalizeResult{Err: err}) continue } } if outcome == FinalizeNoOpenWindow && pcr.commitEmpty { - recorded, err := l.recordCommitRequest(pcr) + decided, err := l.decideEmptyCommit(pcr) if err != nil { // The request asked for its message to be recorded and it was not: a failure, not // a benign NoWindow that would report Ready=True for a save that left no trace. l.resolveCommitRequest(id, FinalizeResult{Err: err}) continue } - if recorded { - continue // it now rides the record write, and the push resolves it + if decided { + continue // it now rides the empty commit, and the push resolves it } } l.resolveCommitRequest(id, FinalizeResult{Outcome: outcome}) } } -// recordCommitRequest decides an empty commit recording a request's message, for a request that ran -// out of time to attach and asked for whenNothingToCommit: CommitEmpty. Every reason no record can -// be made is returned, including a write gate (an empty commit is a write too), so the request fails -// instead of reporting a save it did not make. Once decided, the request rides the record write -// like an attached request rides its window: a remote that cannot be reached holds it, and only a -// failure of the commit itself fails it. -func (l *branchWorkerEventLoop) recordCommitRequest(pcr *pendingCommitRequest) (bool, error) { - pendingWrite, err := l.w.buildRequestRecordWrite(l.w.ctx, pcr) +// decideEmptyCommit decides an empty commit recording a request's message, for a request that ran +// out of time to attach and asked for whenNothingToCommit: CommitEmpty. Every reason the empty +// commit cannot be made is returned, including a write gate (an empty commit is a write too), so +// the request fails instead of reporting a save it did not make. Once decided, the request rides +// the empty commit like an attached request rides its window: a remote that cannot be reached holds +// it, and only a failure of the commit itself fails it. +func (l *branchWorkerEventLoop) decideEmptyCommit(pcr *pendingCommitRequest) (bool, error) { + pendingWrite, err := l.w.buildEmptyCommitWrite(l.w.ctx, pcr) if err != nil { l.w.Log.Error(err, "Cannot build the empty commit recording a CommitRequest", "request", pcr.id.Namespace+"/"+pcr.id.Name) return false, fmt.Errorf("record the message in an empty commit: %w", err) } - // A record whose commit fails for good resolves the request itself, so either way the request + // An empty commit that fails for good resolves the request itself, so either way the request // is no longer the caller's to resolve. l.decide(*pendingWrite) return true, nil } -// buildRequestRecordWrite assembles the record commit's write, phrased and signed like every other +// buildEmptyCommitWrite assembles the record commit's write, phrased and signed like every other // commit the target makes and authored by the request's submitter. A target that refuses writes // gets none, and the refusal is returned (see write_gate.go). -func (w *BranchWorker) buildRequestRecordWrite( +func (w *BranchWorker) buildEmptyCommitWrite( ctx context.Context, pcr *pendingCommitRequest, ) (*PendingWrite, error) { @@ -472,7 +480,7 @@ func (w *BranchWorker) buildRequestRecordWrite( } id := pcr.id return &PendingWrite{ - Kind: PendingWriteRequestRecord, + Kind: PendingWriteEmptyCommit, CommitMessage: pcr.message, CommitConfig: ResolveCommitConfig(provider.Spec.Commit). WithTargetMessage(metadata.CommitMessage), @@ -482,7 +490,7 @@ func (w *BranchWorker) buildRequestRecordWrite( Targets: map[pendingTargetKey]ResolvedTargetMetadata{ {Name: pcr.gitTargetName, Namespace: pcr.gitTargetNamespace}: metadata, }, - RequestAuthor: UserInfo{Username: pcr.author}, + RequestAuthor: pcr.author, RequestAttribution: pcr.attribution, CommitRequest: &id, }, nil diff --git a/internal/git/commit_request_attach_test.go b/internal/git/commit_request_attach_test.go index 14d8a038d..3a3279c8f 100644 --- a/internal/git/commit_request_attach_test.go +++ b/internal/git/commit_request_attach_test.go @@ -44,7 +44,7 @@ func attachReq(author string, d time.Duration) *AttachCommitRequest { Namespace: "default", Name: crName, UID: "uid-" + crName, - Author: author, + Author: UserInfo{Username: author}, GitTargetName: crTarget, GitTargetNamespace: "default", Attach: configv1alpha3.AttachCurrentOrNext, @@ -493,7 +493,7 @@ func TestAttach_ASecondSaveOfTheSameAuthorIsRefusedWhileTheFirstIsInProgress(t * serviceAttach(loop, attachReq("alice", 60*time.Second)) bob := second() - bob.Author = "bob" + bob.Author = UserInfo{Username: "bob"} serviceAttach(loop, bob) _, resolved := secondOutcome(t, worker) @@ -921,7 +921,7 @@ func TestMatchesWindow_AcrossIndependentlyConfiguredSubsystems(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { p := &pendingCommitRequest{ - author: tc.reqAuth, + author: UserInfo{Username: tc.reqAuth}, attribution: tc.request, gitTargetName: crTarget, gitTargetNamespace: "default", diff --git a/internal/git/commit_request_empty_test.go b/internal/git/commit_request_empty_test.go index 16b3da418..2cb8f6933 100644 --- a/internal/git/commit_request_empty_test.go +++ b/internal/git/commit_request_empty_test.go @@ -69,7 +69,44 @@ func TestCommitEmpty_NoWindowBeforeTheTimeoutRecordsTheMessage(t *testing.T) { commit, err := serverRepo.CommitObject(plumbing.NewHash(res.Commit)) require.NoError(t, err) - assert.Equal(t, "alice", commit.Author.Name, "the record is authored by the request's submitter") + assert.Equal(t, "alice", commit.Author.Name, "the empty commit is authored by the request's submitter") +} + +// An empty commit has no write to take its author from, so it takes the request's: the identity +// ResolveAuthor gave for the request, name and email included. A person's empty commit and their +// window commit must then carry the same Git author. +func TestCommitEmpty_IsAuthoredAsTheSubmittersWindowCommits(t *testing.T) { + worker, serverRepo, _ := setupCommitPushSplitWorker(t) + createPlainGitTarget(t, worker, "team-a", "team-a") + loop := newBranchWorkerEventLoop(worker, time.Hour) + defer loop.stopTimers() + alice := UserInfo{Username: "oidc:alice", DisplayName: "Alice Jansen", Email: "alice@corp.example"} + + event := configMapTargetEvent("existing", alice.Username, "team-a") + event.UserInfo = alice + loop.handleQueueItem(WorkItem{Request: &WriteRequest{Events: []Event{event}}}) + require.True(t, loop.finalizeOpenWindow()) + loop.pushPending() + + req := commitEmptyReq(alice.Username, "save: nothing changed") + req.Author = alice + serviceAttach(loop, req) + forceDue(loop) + loop.endWake(0) + loop.pushPending() + + res, ok := outcome(t, worker) + require.True(t, ok) + require.NoError(t, res.Err) + requirePushedEmptyCommit(t, serverRepo, res, "save: nothing changed") + emptyCommit, err := serverRepo.CommitObject(plumbing.NewHash(res.Commit)) + require.NoError(t, err) + windowCommit, err := emptyCommit.Parent(0) + require.NoError(t, err) + assert.Equal(t, "Alice Jansen", emptyCommit.Author.Name, "the display name, not the username") + assert.Equal(t, "alice@corp.example", emptyCommit.Author.Email, "the email the login carried") + assert.Equal(t, windowCommit.Author.Name, emptyCommit.Author.Name, "the same author as her window commit") + assert.Equal(t, windowCommit.Author.Email, emptyCommit.Author.Email, "the same email as her window commit") } func TestCommitEmpty_AWindowThatChangedNothingRecordsTheMessage(t *testing.T) { @@ -476,3 +513,33 @@ func TestCommitEmpty_ABufferFlushStillServesTheWaitingSaves(t *testing.T) { assert.Len(t, loop.pendingWrites, 1, "no record was made while alice's work was in flight") }) } + +// Saves whose attach deadlines pass in the same wake leave their empty commits in the order the +// saves were registered, not in the pending set's map order. A small map iterates as a rotation of +// its slots, so one round matches registration order often by chance; twenty rounds do not. +func TestCommitEmpty_SavesExpiringTogetherCommitInRegistrationOrder(t *testing.T) { + authors := []string{"alice", "bob", "carol", "dave", "erin"} + for range 20 { + worker, _, _ := setupCommitPushSplitWorker(t) + createPlainGitTarget(t, worker, "team-a", "team-a") + loop := newBranchWorkerEventLoop(worker, time.Hour) + holdPushes(loop) // keep the decided writes in view + + for _, author := range authors { + req := commitEmptyReq(author, "save: by "+author) + req.Name, req.UID = "save-"+author, "uid-save-"+author + serviceAttach(loop, req) + } + past := time.Now().Add(-time.Millisecond) + for _, pcr := range loop.pendingCRs { + pcr.attachDeadline = past + } + loop.expireWaitingCommitRequests() + loop.stopTimers() + + require.Len(t, loop.pendingWrites, len(authors), "one empty commit per save") + for i, author := range authors { + require.Equal(t, "save: by "+author, loop.pendingWrites[i].CommitMessage, "decided in registration order") + } + } +} diff --git a/internal/git/commit_request_folder_test.go b/internal/git/commit_request_folder_test.go index dca004cab..4d605b7ab 100644 --- a/internal/git/commit_request_folder_test.go +++ b/internal/git/commit_request_folder_test.go @@ -95,7 +95,7 @@ func (r *saveRun) register(name, message string) { func saveRequest(name, message string) *AttachCommitRequest { return &AttachCommitRequest{ Namespace: "default", Name: name, UID: "uid-" + name, - Author: "alice", GitTargetName: crTarget, GitTargetNamespace: "default", + Author: UserInfo{Username: "alice"}, GitTargetName: crTarget, GitTargetNamespace: "default", Message: message, Attach: configv1alpha3.AttachCurrentOrNext, AttachTimeout: 5 * time.Second, diff --git a/internal/git/network_bound_test.go b/internal/git/network_bound_test.go index 797a711c7..c52172a7f 100644 --- a/internal/git/network_bound_test.go +++ b/internal/git/network_bound_test.go @@ -298,9 +298,9 @@ func TestPushCycle_ALostReplyThatLandedIsPublishedNotReplayed(t *testing.T) { f := newLedgerFixture(t, "lost-reply", true) f.createLedgerTarget("apps", nil) - record, err := f.worker.buildRequestRecordWrite(f.worker.ctx, &pendingCommitRequest{ + record, err := f.worker.buildEmptyCommitWrite(f.worker.ctx, &pendingCommitRequest{ id: commitRequestID{Namespace: "default", Name: "save", UID: "save-uid"}, - author: "alice", + author: UserInfo{Username: "alice"}, gitTargetName: ledgerTargetName, gitTargetNamespace: "default", message: "save", diff --git a/internal/git/pending_writes.go b/internal/git/pending_writes.go index f3abce4e6..de27c628e 100644 --- a/internal/git/pending_writes.go +++ b/internal/git/pending_writes.go @@ -250,7 +250,7 @@ func (p PendingWrite) Author() string { // writes, including any OIDC display name and email. Empty writes have no // per-user author and return the zero value. func (p PendingWrite) AuthorUserInfo() UserInfo { - if p.Kind == PendingWriteRequestRecord { + if p.Kind == PendingWriteEmptyCommit { return p.RequestAuthor } if len(p.Events) == 0 { @@ -303,7 +303,7 @@ const ( // mirrors AuthorUserInfo: the window is single-author, so the first event's outcome describes // the whole write. Empty writes never attempt attribution. func (p PendingWrite) AttributionOutcome() AttributionOutcome { - if p.Kind == PendingWriteRequestRecord { + if p.Kind == PendingWriteEmptyCommit { return p.RequestAttribution } if len(p.Events) == 0 { @@ -312,10 +312,10 @@ func (p PendingWrite) AttributionOutcome() AttributionOutcome { return p.Events[0].Attribution } -// nothingToCommitOutcome is the cause an empty commit records: a request record says no window -// arrived in time, and an empty grouped window says what arrived already matched Git. +// nothingToCommitOutcome is the cause an empty commit records: a PendingWriteEmptyCommit says no +// window arrived in time, and an empty grouped window says what arrived already matched Git. func (p PendingWrite) nothingToCommitOutcome() FinalizeOutcome { - if p.Kind == PendingWriteRequestRecord { + if p.Kind == PendingWriteEmptyCommit { return FinalizeNoOpenWindow } return FinalizeAlreadyPresent diff --git a/internal/git/pending_writes_loop.go b/internal/git/pending_writes_loop.go index a46878520..7c6110929 100644 --- a/internal/git/pending_writes_loop.go +++ b/internal/git/pending_writes_loop.go @@ -14,8 +14,8 @@ import ( // This file is the branch worker's ordered pending writes, and the one driver that turns them into // commits and publications. See docs/design/gittarget-branch-worker-pending-writes.md. // -// Every write the loop makes, whatever produced it (a closed window, a resync, a save's empty -// record), takes one path: +// Every write the loop makes, whatever produced it (a closed window, a resync, the empty commit of +// a save no window reached), takes one path: // // - decide appends it to the pending writes. The write gates and building the write have passed, so the // decision stands from here on. Deciding does nothing else: no commit, no push, no settlement. @@ -62,7 +62,7 @@ var errAdmissionClosed = fmt.Errorf( // pendingWriteOverheadBytes is what every retained item is charged beyond its payload: each event a // window or a write keeps (its identity, author, path), and a write that keeps none (its target // metadata, commit configuration, signer, the save it carries). Without it an item with no payload, -// a delete or a save's empty record, cost nothing to keep, and a branch +// a delete or a save's empty commit, cost nothing to keep, and a branch // whose remote was down admitted them for as long as the outage lasted. const pendingWriteOverheadBytes = 1024 @@ -430,7 +430,7 @@ func (l *branchWorkerEventLoop) settleDropped(pendingWrite PendingWrite, err err } l.w.Log.Error(err, "Resync commit failed after its caller was answered; dropping it", "resources", len(req.Desired)) - case pendingWrite.Kind == PendingWriteRequestRecord: + case pendingWrite.Kind == PendingWriteEmptyCommit: l.w.Log.Error(err, "The empty commit recording a CommitRequest failed", "gitTarget", pendingWrite.GitTargetNamespace+"/"+pendingWrite.GitTargetName) l.failDecidedRequest(pendingWrite, fmt.Errorf("record the message in an empty commit: %w", err)) diff --git a/internal/git/request_template_test.go b/internal/git/request_template_test.go index 41d4cfd64..98e7b4f17 100644 --- a/internal/git/request_template_test.go +++ b/internal/git/request_template_test.go @@ -244,9 +244,35 @@ func TestNewRequestTemplateProbe_IsFreshEachTime(t *testing.T) { assert.NotEmpty(t, first) } -// requestTemplate describes the commit a CommitRequest's message produces, and a CommitRequest -// attaches to a live window, which finalizes as PendingWriteCommit. A resync arrives pre-rendered -// and is never framed, whatever requestTemplate says. +// The empty commit of a request no window reached is a commit its CommitRequest supplied the +// message for, so the target's requestTemplate frames it as it frames the window commit: one +// wording for a save, whether or not anything was written in time. With nothing written it lists +// no resources. +func TestFramedRequestMessage_FramesTheEmptyCommitToo(t *testing.T) { + empty := PendingWrite{ + Kind: PendingWriteEmptyCommit, + CommitMessage: "chore: checkpoint", + CommitConfig: requestConfig("{{.RequestMessage}}\n\nSaved by {{.Author}}"), + RequestAuthor: UserInfo{Username: "alice"}, + Targets: map[pendingTargetKey]ResolvedTargetMetadata{ + {Name: "platform", Namespace: "default"}: {Name: "platform", Namespace: "default"}, + }, + } + require.Equal(t, messageResolutionRequestTemplate, empty.resolveMessage()) + + message, _, resolution, err := empty.commitMetadata() + require.NoError(t, err) + assert.Equal(t, messageResolutionRequestTemplate, resolution) + assert.Equal(t, "chore: checkpoint\n\nSaved by alice", message) + + unframed := empty + unframed.CommitConfig = ResolveCommitConfig(nil) + assert.Equal(t, messageResolutionRequest, unframed.resolveMessage(), + "without a requestTemplate the message is committed as written") +} + +// requestTemplate describes the commit a CommitRequest's message produces. A resync arrives +// pre-rendered and is never framed, whatever requestTemplate says. func TestResolveMessage_AResyncIsNeverFramed(t *testing.T) { resync := requestWrite("pre-rendered", requestConfig(requestBodyTemplate)) resync.Kind = PendingWriteResync diff --git a/internal/git/types.go b/internal/git/types.go index 86a38a99f..03bfd964c 100644 --- a/internal/git/types.go +++ b/internal/git/types.go @@ -274,10 +274,10 @@ const ( // content-derived mark-and-sweep against the worktree (upsert every desired // resource, drop every watched managed document the snapshot did not contain). PendingWriteResync PendingWriteKind = "resync" - // PendingWriteRequestRecord carries no content. It records a CommitRequest's message + // PendingWriteEmptyCommit carries no content. It records a CommitRequest's message // in an empty commit when the request ran out of time to attach, and asked for that with // whenNothingToCommit: CommitEmpty. It is not a window: only writes open windows. - PendingWriteRequestRecord PendingWriteKind = "request_record" + PendingWriteEmptyCommit PendingWriteKind = "empty_commit" ) type pendingTargetKey struct { @@ -381,7 +381,7 @@ type PendingWrite struct { // CommitRequest attached to it asked for whenNothingToCommit: CommitEmpty. A suspended target // still writes nothing. AllowEmpty bool - // RequestAuthor and RequestAttribution author a PendingWriteRequestRecord, which has no + // RequestAuthor and RequestAttribution author a PendingWriteEmptyCommit, which has no // events to take an author from: they are the request submitter's, matched the same way a // window's author is. RequestAuthor UserInfo diff --git a/internal/git/window_admission_test.go b/internal/git/window_admission_test.go index a1946330a..482c6662f 100644 --- a/internal/git/window_admission_test.go +++ b/internal/git/window_admission_test.go @@ -260,7 +260,9 @@ func TestWindowAdmission_ShutdownDecidesTheWritesAlreadyQueued(t *testing.T) { return event } require.True(t, f.worker.Enqueue(queued("alice", "x", "x3"))) - f.worker.EnqueueAttach(&AttachCommitRequest{Namespace: "default", Name: "save", Author: "carol"}) + f.worker.EnqueueAttach( + &AttachCommitRequest{Namespace: "default", Name: "save", Author: UserInfo{Username: "carol"}}, + ) require.True(t, f.worker.Enqueue(queued("bob", "z", "z2"))) f.loop.handleShutdown() @@ -650,7 +652,7 @@ func TestWindowAdmission_AWindowAnAttachClosedTakesNoRequest(t *testing.T) { waiting := func(author string, seq uint64) *pendingCommitRequest { return &pendingCommitRequest{ id: commitRequestID{Namespace: "default", Name: "save-" + author, UID: "uid-" + author}, - author: author, gitTargetName: echoTarget, gitTargetNamespace: "default", seq: seq, + author: UserInfo{Username: author}, gitTargetName: echoTarget, gitTargetNamespace: "default", seq: seq, message: "feat: " + author, maxDuration: time.Hour, attachDeadline: f.worker.now().Add(time.Minute), } } diff --git a/internal/git/window_model_test.go b/internal/git/window_model_test.go index 802ab1090..60156fa5f 100644 --- a/internal/git/window_model_test.go +++ b/internal/git/window_model_test.go @@ -1462,7 +1462,7 @@ func (r *windowModelRun) save() { name := "save-" + strconv.Itoa(r.saves) req := &AttachCommitRequest{ Namespace: "default", Name: name, UID: "uid-" + name, - Author: author, GitTargetName: echoTarget, GitTargetNamespace: "default", + Author: UserInfo{Username: author}, GitTargetName: echoTarget, GitTargetNamespace: "default", Message: fmt.Sprintf("feat: %s by %s", name, author), Attach: configv1alpha3.AttachCurrentOrNext, } @@ -1479,7 +1479,7 @@ func (r *windowModelRun) save() { // register sends the save req, which names the run's next save. func (r *windowModelRun) register(req *AttachCommitRequest) { - name, author := req.Name, req.Author + name, author := req.Name, req.Author.Username r.notef("%s registers %s attach=%s attachTimeout=%s maxDuration=%s idle=%v", author, name, req.Attach, req.AttachTimeout, req.MaxDuration, req.IdleTimeout) s := &modelSave{name: name, author: author, message: req.Message, next: req.Attach == configv1alpha3.AttachNext, @@ -1542,7 +1542,7 @@ func (r *windowModelRun) restructure() { r.saves++ r.register(&AttachCommitRequest{ Namespace: "default", Name: "save-" + strconv.Itoa(r.saves), UID: "uid-save-" + strconv.Itoa(r.saves), - Author: "carol", GitTargetName: echoTarget, GitTargetNamespace: "default", + Author: UserInfo{Username: "carol"}, GitTargetName: echoTarget, GitTargetNamespace: "default", Message: "feat: carol's save", Attach: configv1alpha3.AttachCurrentOrNext, AttachTimeout: 20 * time.Second, MaxDuration: 40 * time.Second, }) diff --git a/internal/git/window_set_test.go b/internal/git/window_set_test.go index 6c30c53d2..3b19b5827 100644 --- a/internal/git/window_set_test.go +++ b/internal/git/window_set_test.go @@ -62,8 +62,16 @@ func TestCommitWindows_ASetSaysWhichWindowAWriteOrARequestBelongsTo(t *testing.T assert.Nil(t, set.forWrite(bob)) assert.Equal(t, []*openWindow{window}, set.others(set.forWrite(bob))) - aliceSave := &pendingCommitRequest{author: "alice", gitTargetName: "team-a", gitTargetNamespace: "default"} - bobSave := &pendingCommitRequest{author: "bob", gitTargetName: "team-a", gitTargetNamespace: "default"} + aliceSave := &pendingCommitRequest{ + author: UserInfo{Username: "alice"}, + gitTargetName: "team-a", + gitTargetNamespace: "default", + } + bobSave := &pendingCommitRequest{ + author: UserInfo{Username: "bob"}, + gitTargetName: "team-a", + gitTargetNamespace: "default", + } assert.Same(t, window, set.forRequest(aliceSave)) assert.Nil(t, set.foreignTo(aliceSave)) assert.Nil(t, set.forRequest(bobSave)) @@ -72,7 +80,11 @@ func TestCommitWindows_ASetSaysWhichWindowAWriteOrARequestBelongsTo(t *testing.T bobs := set.open(bob, nil, time.Now()) assert.Same(t, bobs, set.forRequest(bobSave)) assert.Nil(t, set.foreignTo(bobSave), "a window of the request's own author is open: nobody stands in its way") - carolSave := &pendingCommitRequest{author: "carol", gitTargetName: "team-a", gitTargetNamespace: "default"} + carolSave := &pendingCommitRequest{ + author: UserInfo{Username: "carol"}, + gitTargetName: "team-a", + gitTargetNamespace: "default", + } assert.Same(t, window, set.foreignTo(carolSave), "the oldest window it cannot attach to") id := commitRequestID{Namespace: "default", Name: "save", UID: "uid-save"} diff --git a/internal/git/write_gate.go b/internal/git/write_gate.go index f9b70b9ff..ed56f7b70 100644 --- a/internal/git/write_gate.go +++ b/internal/git/write_gate.go @@ -14,8 +14,8 @@ import ( // Ready=True with nothing written. That holds whichever path ends the request and whatever its // whenNothingToCommit says: // -// - a request no window reached (expireWaitingCommitRequests, before the record it may make); -// - the record itself (buildRequestRecordWrite); +// - a request no window reached (expireWaitingCommitRequests, before the empty commit it may make); +// - that empty commit itself (buildEmptyCommitWrite); // - a window a request is attached to (finalizeWindow before it builds the write, // and gateBuiltWindow after, right before the commit). A render-fidelity refusal seen at // either look stops the whole window; suspension fails only the request, and the write still diff --git a/internal/git/write_gate_test.go b/internal/git/write_gate_test.go index 3306def9a..9b0cc9877 100644 --- a/internal/git/write_gate_test.go +++ b/internal/git/write_gate_test.go @@ -354,7 +354,7 @@ func TestWriteGate_AWindowMismatchIsStillAMismatch(t *testing.T) { worker, _, loop := seededLoop(t) suspendTarget(t, worker) req := requestFor("save", "team-a", true) - req.Author = "bob" + req.Author = UserInfo{Username: "bob"} serviceAttach(loop, req) writeTo(loop, "alices-edit") diff --git a/internal/watch/event_router_test.go b/internal/watch/event_router_test.go index 3aafe2f63..1391a6784 100644 --- a/internal/watch/event_router_test.go +++ b/internal/watch/event_router_test.go @@ -37,7 +37,7 @@ func saveAttach(gitTargetName, gitTargetNamespace string) git.AttachCommitReques Namespace: gitTargetNamespace, Name: "save", UID: "uid-save", - Author: "alice", + Author: git.UserInfo{Username: "alice"}, GitTargetName: gitTargetName, GitTargetNamespace: gitTargetNamespace, } diff --git a/test/e2e/bi_directional_echoes_e2e_test.go b/test/e2e/bi_directional_echoes_e2e_test.go index 927839be6..474516aae 100644 --- a/test/e2e/bi_directional_echoes_e2e_test.go +++ b/test/e2e/bi_directional_echoes_e2e_test.go @@ -292,6 +292,13 @@ func echoScenarios(run func() *echoRun) { By("editing an object every second while a Git-side push to another one waits") stop := make(chan struct{}) var wg sync.WaitGroup + // Stopped once, either below or by the cleanup, so a failed Eventually does not leave the + // editor running into the next spec. + stopEditing := sync.OnceFunc(func() { + close(stop) + wg.Wait() + }) + DeferCleanup(stopEditing) last := "b0" wg.Go(func() { defer GinkgoRecover() @@ -311,8 +318,7 @@ func echoScenarios(run func() *echoRun) { live, _ := r.liveValue(g, "busy-push") g.Expect(live).To(Equal("p1"), "the push is applied while edits keep arriving") }, timingReceiverBudget, time.Second).Should(Succeed()) - close(stop) - wg.Wait() + stopEditing() r.eventuallyEverywhere("busy", last, echoApplyBudget) r.consistentlyEverywhere("busy", last) diff --git a/test/e2e/commit_request_e2e_test.go b/test/e2e/commit_request_e2e_test.go index a022f2075..5c9919bcb 100644 --- a/test/e2e/commit_request_e2e_test.go +++ b/test/e2e/commit_request_e2e_test.go @@ -117,7 +117,7 @@ var _ = Describe("Save Request", Label("commit-request", "audit-consumer"), Orde // audit event, and it is the author of the edit's window, which it saved. By("verifying the CommitRequest's author came from audit and authored the commit") Eventually(func(g Gomega) { - author := commitRequestField(g, testNs, commitRequestName, "{.status.author}") + author := commitRequestField(g, testNs, commitRequestName, "{.status.author.username}") g.Expect(author).NotTo(BeEmpty(), "the request's author is found from its audit event") commitAuthor, logErr := gitRun(repo.CheckoutDir, "log", "-1", "--pretty=%an") g.Expect(logErr).NotTo(HaveOccurred()) @@ -456,7 +456,7 @@ spec: fmt.Sprintf("%s/%s/configmaps/app-flags.yaml", basePath, testNs), ), "the commit changes the two ConfigMaps and nothing else: the CommitRequest is never mirrored") if !configuredAuthorModeEnabled() { - author := commitRequestField(Default, testNs, requestName, "{.status.author}") + author := commitRequestField(Default, testNs, requestName, "{.status.author.username}") commitAuthor, err := gitRun(repo.CheckoutDir, "log", "-1", "--pretty=%an", reportedSHA) Expect(err).NotTo(HaveOccurred()) Expect(author).NotTo(BeEmpty()) @@ -564,7 +564,7 @@ spec: By("checking every commit that holds the folder") author := "" if !configuredAuthorModeEnabled() { - author = commitRequestField(Default, p.ns, requestName, "{.status.author}") + author = commitRequestField(Default, p.ns, requestName, "{.status.author.username}") } for _, sha := range saved { paths, err := gitRun( diff --git a/test/e2e/source_cluster_e2e_test.go b/test/e2e/source_cluster_e2e_test.go index 9888f6416..48fba3472 100644 --- a/test/e2e/source_cluster_e2e_test.go +++ b/test/e2e/source_cluster_e2e_test.go @@ -867,7 +867,7 @@ spec: g.Expect(saveField(g, `{.status.conditions[?(@.type=="Ready")].reason}`)).To(Equal("Committed")) commit = saveField(g, "{.status.commit}") g.Expect(commit).NotTo(BeEmpty()) - g.Expect(saveField(g, "{.status.author}")).To(BeEmpty(), "kcp sends no audit facts") + g.Expect(saveField(g, "{.status.author.username}")).To(BeEmpty(), "kcp sends no audit facts") g.Expect(saveField(g, `{.metadata.annotations.configbutler\.ai/delete-after}`)).NotTo(BeEmpty(), "ReconcileAndDeleteFinished stamps a finished request for deletion") }, 2*time.Minute, 2*time.Second).Should(Succeed()) From 259ddc5680809cc828e54fddc9072495f5831790 Mon Sep 17 00:00:00 2001 From: Simon Koudijs Date: Wed, 25 Nov 2026 09:58:48 +0000 Subject: [PATCH 2/2] fix(git): name the empty commit's GitTarget in requestTemplate, and say it is framed An empty commit has no event to take its GitTarget from, so Target() was empty and a requestTemplate that renders {{.GitTarget}} printed nothing. It names its target explicitly, as a resync does. docs/commit-messages.md still said requestTemplate renders only for an attached window. Co-Authored-By: Claude Opus 5.5 --- docs/commit-messages.md | 5 +++-- internal/git/pending_writes.go | 4 +++- internal/git/request_template_test.go | 6 ++++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/commit-messages.md b/docs/commit-messages.md index e13acb855..6331b5921 100644 --- a/docs/commit-messages.md +++ b/docs/commit-messages.md @@ -77,8 +77,9 @@ spec: {{end -}} ``` -It renders only for a window a save request attached to; every other window is unaffected. Omit it -and request messages are committed verbatim, exactly as before. +It renders only for a commit a save request gave its message: the window the request attached to, +or the empty commit of a request no window reached in time. Every other window is unaffected. Omit +it and request messages are committed verbatim, exactly as before. The request is **never** parsed as a template. Its message arrives as `.RequestMessage` and is committed unaltered, so a save-button user supplies the content while the operator owns the diff --git a/internal/git/pending_writes.go b/internal/git/pending_writes.go index de27c628e..6327ab42c 100644 --- a/internal/git/pending_writes.go +++ b/internal/git/pending_writes.go @@ -354,8 +354,10 @@ func (p PendingWrite) Target() ResolvedTargetMetadata { return ResolvedTargetMetadata{Name: name, Namespace: namespace} } +// targetIdentity names the GitTarget a write is for. A resync and an empty commit carry no event to +// take it from, so they name it explicitly. func (p PendingWrite) targetIdentity() (string, string) { - if p.Kind == PendingWriteResync { + if p.Kind == PendingWriteResync || p.Kind == PendingWriteEmptyCommit { return p.GitTargetName, p.GitTargetNamespace } if len(p.Events) == 0 { diff --git a/internal/git/request_template_test.go b/internal/git/request_template_test.go index 98e7b4f17..338c8960e 100644 --- a/internal/git/request_template_test.go +++ b/internal/git/request_template_test.go @@ -252,8 +252,9 @@ func TestFramedRequestMessage_FramesTheEmptyCommitToo(t *testing.T) { empty := PendingWrite{ Kind: PendingWriteEmptyCommit, CommitMessage: "chore: checkpoint", - CommitConfig: requestConfig("{{.RequestMessage}}\n\nSaved by {{.Author}}"), + CommitConfig: requestConfig("{{.RequestMessage}}\n\nSaved by {{.Author}} in {{.GitTarget}}"), RequestAuthor: UserInfo{Username: "alice"}, + GitTargetName: "platform", GitTargetNamespace: "default", Targets: map[pendingTargetKey]ResolvedTargetMetadata{ {Name: "platform", Namespace: "default"}: {Name: "platform", Namespace: "default"}, }, @@ -263,7 +264,8 @@ func TestFramedRequestMessage_FramesTheEmptyCommitToo(t *testing.T) { message, _, resolution, err := empty.commitMetadata() require.NoError(t, err) assert.Equal(t, messageResolutionRequestTemplate, resolution) - assert.Equal(t, "chore: checkpoint\n\nSaved by alice", message) + assert.Equal(t, "chore: checkpoint\n\nSaved by alice in platform", message, + "the empty commit names its GitTarget, though it has no event to take it from") unframed := empty unframed.CommitConfig = ResolveCommitConfig(nil)