diff --git a/docs/UPGRADING.md b/docs/UPGRADING.md index e64af599a..82fe83f2b 100644 --- a/docs/UPGRADING.md +++ b/docs/UPGRADING.md @@ -7,6 +7,18 @@ 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. +## `close_reason="identity_change"` is three reasons + +`gitopsreverser_git_commit_windows_total` no longer has `close_reason="identity_change"`. What it +counted is now one of three values: `other_target` (a write of another `GitTarget` on the same +branch), `unproven_footprint` (another author wrote where the files cannot be proven apart), or +`single_window` (another author wrote after the worker fell back to one window at a time). A query or +alert on `identity_change` matches nothing; sum the three for the old total. See +[interpreting metrics](interpreting-metrics.md). + +A `CommitRequest` whose window a write outside it closed early this way, or by `path_conflict` or +`footprint_fallback`, still ends with the same reason, and its `Ready` message says why it closed. + ## A `CommitRequest`'s `status.author` is an object `status.author` names the request's creator as `username`, plus the `name` and `email` their login diff --git a/docs/configuration.md b/docs/configuration.md index 2acd36a61..ab3ee2be0 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -3339,7 +3339,12 @@ request produced a pushed commit: under the earlier request's message first. Saves by different authors do not race for a message: each author's writes collect in a window of their own, side by side while their files are proven not to overlap, and otherwise a write by another author closes the open window, and - its message, before it opens one of its own. + its message, before it opens one of its own. When a write outside a request's window closes it + that way, the request still ends as its outcome says, and its `Ready` message adds why the window + closed early: another author's write touched a file it held, the two could not be proven apart, a + write of another `GitTarget` on the branch arrived, or the branch worker holds one window at a + time. The author's edits after that are not part of the save. `git_commit_windows_total` counts + these closes by `close_reason`, with `timer_source="commit_request"` for a save's window. `SaveInProgress` is decided when the branch worker registers the request, which is after its author was found, not when it is created. A client that relies on it to keep two of its saves diff --git a/docs/design/concurrent-author-windows.md b/docs/design/concurrent-author-windows.md index 3b8384434..5c002161e 100644 --- a/docs/design/concurrent-author-windows.md +++ b/docs/design/concurrent-author-windows.md @@ -152,8 +152,8 @@ A write is **proven independent** only when all of these hold: | An object under a kustomization, a generator source, or any layout the worker renders | unknown | no | | An object the index cannot place | unknown | no | -"No" closes every other open window first, which is today's behavior, reported as -`identity_change` as it is now. The rule never guesses: unknown is treated as overlapping +"No" closes every other open window first, reported as `unproven_footprint` (`identity_change` +before the split into precise reasons). The rule never guesses: unknown is treated as overlapping everything. Shared files and kustomize layouts are the obvious next candidates once the base change is measured; each needs its own proof. @@ -200,7 +200,9 @@ unrelated push split a save that is protected today. | `buffer_limit` | every window | none | | `path_conflict` | the windows whose footprint the new write overlaps | none | | `footprint_fallback` | every window but the newest, when a commit outside its footprint makes the worker hold one window at a time | none | -| `identity_change` | every other window | stays for writes of another `GitTarget` and for unproven footprints | +| `other_target` | every other window, before a write of another `GitTarget` | none | +| `unproven_footprint` | a window whose footprint, or the write's, cannot be proven | none | +| `single_window` | every other window, once the worker holds one window at a time | none | | `idle_timeout`, `max_duration`, `attach_next` | that window only | none | Why the first two exist matters for every later change to them: @@ -304,7 +306,7 @@ release, because stage 2 shipped without a flag. model. Every existing test passes unchanged. 2. **Built. Allow several windows for proven-independent destinations.** Writes keep whole-object commits and apply behavior stays as it is. Writes of another `GitTarget` keep closing other windows - (`identity_change`), and every layout in the footprint table's "no" rows stays serial. + (`other_target`), and every layout in the footprint table's "no" rows stays serial. 3. **Built. Test the failure boundaries.** Both close orders, conflicting writes, delete and recreate, `attach_next`, zero-duration windows, resync, shutdown, failed publication and replay, and buffer pressure, each against the reference model, which @@ -313,10 +315,10 @@ release, because stage 2 shipped without a flag. the release instead of a default-off rollout. What the flag's measurement period was for is read from the metrics: `git_commit_windows_open` shows windows open side by side, `git_commit_windows_single` a worker that fell back to one at a time, and - `git_commit_windows_total` by `close_reason` the forced splits (`identity_change`, - `path_conflict`, `footprint_fallback`). Memory is not measured yet: the retained-byte budget - charges windows and pending writes, but not the footprint indexes, the accepted versions or the - withheld-field records. + `git_commit_windows_total` by `close_reason` the forced splits (`path_conflict`, + `unproven_footprint`, `other_target`, `single_window`, `footprint_fallback`). Memory is not + measured yet: the retained-byte budget charges windows and pending writes, but not the footprint + indexes, the accepted versions or the withheld-field records. 5. **Proposed. Reconsider the follow-ups** in [window-field-ownership-and-apply-hold.md](window-field-ownership-and-apply-hold.md), using those measurements. Field ownership and the apply hold are separate changes, each with its own @@ -453,3 +455,7 @@ branch stay serial; the proof at arrival is the placement index, with its cost u 2. Is a cap on open windows needed beyond the byte cap, such as one per `GitTarget`? 3. When a save's own window is closed early by `path_conflict`, it commits with the save's message and less than the person meant to save. Is that acceptable, or should the save report it? + **Answered:** the save reports it, for this and every other close a write outside the window + causes (`unproven_footprint`, `other_target`, `single_window`, `footprint_fallback`). The request + ends as before, and its `Ready` and `Reconciling` messages add why the window closed early, so its + edits after that are not part of the save. diff --git a/docs/design/push-cooldown.md b/docs/design/push-cooldown.md index 0d89f9bb1..94f5d026d 100644 --- a/docs/design/push-cooldown.md +++ b/docs/design/push-cooldown.md @@ -100,9 +100,9 @@ when it cannot sit beside them: | Source | Close reason | | --- | --- | -| A write of another `GitTarget` on the same branch (per-target encryption and bootstrap stay serial) | `author-or-target-change` | -| A write, or an open window, whose footprint cannot be proven | `author-or-target-change` | -| A worker that fell back to one window at a time | `author-or-target-change`, after `footprint-fallback` | +| A write of another `GitTarget` on the same branch (per-target encryption and bootstrap stay serial) | `other-target` | +| A write, or an open window, whose footprint cannot be proven | `unproven-footprint` | +| A worker that fell back to one window at a time | `single-window`, after `footprint-fallback` | | Overlapping footprints | `path-conflict` | | The retained-byte budget | `buffer-limit` | | `commit.window.idleTimeout: 0s` | every event commits on arrival | diff --git a/docs/interpreting-metrics.md b/docs/interpreting-metrics.md index 9d4498661..eb7933671 100644 --- a/docs/interpreting-metrics.md +++ b/docs/interpreting-metrics.md @@ -206,7 +206,7 @@ boundary, the commit, the push. Background: | `git_queue_refusals_total` | counter | `gitbranch_namespace`, `gitbranch_name`, `provider_namespace`, `provider_name`, `kind` | Work refused at enqueue: the queue was full, intake was paused through an outage, or the worker was stopping. `kind` is `write` / `attach` / `resync` / `refresh`. The producer keeps a refused item and offers it again: the watch delivers a write again from its cursor, the controller re-sends a save, a resync is gathered again, and the next reconcile asks for a refresh. What it can cost, when its watch cursor expires before the write comes back, is the write's own commit and, under `prune.mode: OnEvent`, a deleted object's removal from Git. | | `git_commit_failures_total` | counter | `gitbranch_namespace`, `gitbranch_name`, `provider_namespace`, `provider_name`, `reason` | A live commit window that died between routing and pushing; a resync's failure is `git_resync_failures_total`. `reason` is `refused` (a Git path a human must fix) / `error`. Every increment is a window's events lost until the next resync. An unreachable remote does not count: a decided window waits for the publication retry instead. | | `git_writes_dropped_total` | counter | `gitbranch_namespace`, `gitbranch_name`, `provider_namespace`, `provider_name`, `reason` | A live event the branch worker dropped because its `GitTarget`'s render fidelity was not established. `reason` is `render_fidelity_diverged`: a rendered value does not match the live object, and every write is dropped until a fresh replay measures the folder clean. Or it is `render_fidelity_pending`: a collection of the `GitTarget` has not finished its replay, which closes every collection of that target until it does. A live event that meets a pending gate is held, not dropped, and committed with its author once the gate opens; it is counted here only when the hold gives up, 10 minutes after the first one was held or once the branch holds more than its retained-byte budget, and the worker then asks for a fresh snapshot, which commits the current state as the operator (a deletion comes back only under prune mode `Always`). Nothing replays a dropped write, so each one is an edit missing from Git until the object changes again or its collection replays. The worker logs the first drop under each gate status at Info, naming the collections the gate waits for, and each hold, release and give-up at Info. | -| `git_commit_windows_total` | counter | `gittarget_namespace`, `gittarget_name`, `close_reason`, `timer_source` | One per closed commit window, whether or not it then produced a commit. `close_reason` is `idle_timeout` / `max_duration` / `attach_next` / `identity_change` / `path_conflict` / `footprint_fallback` (a commit changed a file outside its window's footprint, so the worker holds one window at a time from then on, and closes all but the newest of the windows open) / `buffer_limit` / `resync_before_apply` / `foreign_commit` (a Git host said the branch may have moved, so the window is published now) / `apply_due` (an apply came due for an applier on the branch, so the window's edits are published before the apply is sent) / `shutdown`; `timer_source` is `target` or `commit_request`. See [tuning commit windows](#tuning-commit-windows). | +| `git_commit_windows_total` | counter | `gittarget_namespace`, `gittarget_name`, `close_reason`, `timer_source` | One per closed commit window, whether or not it then produced a commit. `close_reason` is `idle_timeout` / `max_duration` / `attach_next` / `path_conflict` / `unproven_footprint` / `other_target` / `single_window` / `footprint_fallback` (a commit changed a file outside its window's footprint, so the worker holds one window at a time from then on, and closes all but the newest of the windows open) / `buffer_limit` / `resync_before_apply` / `foreign_commit` (a Git host said the branch may have moved, so the window is published now) / `apply_due` (an apply came due for an applier on the branch, so the window's edits are published before the apply is sent) / `shutdown`; `timer_source` is `target` or `commit_request`. See [tuning commit windows](#tuning-commit-windows). | | `git_commit_window_duration_seconds` | histogram | `gittarget_namespace`, `gittarget_name` | How long each window collected: from the write that opened it to the start of its finalize. Its count equals `git_commit_windows_total` summed over `close_reason` and `timer_source`. | | `git_commit_windows_open` | gauge | `gitbranch_namespace`, `gitbranch_name`, `provider_namespace`, `provider_name` | Commit windows the branch worker holds open. Above 1 means authors are collecting side by side, one window each, because their files are proven not to overlap. A branch that only ever reads 0 or 1 while several people edit it gets no concurrency: their writes are in shared files, kustomize folders, or another layout the worker cannot prove independent. Read at scrape time. | | `git_commit_windows_single` | gauge | `gitbranch_namespace`, `gitbranch_name`, `provider_namespace`, `provider_name` | 1 once the branch worker has fallen back to one commit window at a time, after a commit would have changed a file outside its window's footprint (a bug: the worker refused the commit and asked for a resync). It stays 1 until the worker restarts. The worker logs the refused paths at Error (`SingleWindowFallback`). Read at scrape time. | @@ -647,13 +647,20 @@ picture toward `max_duration`. writes kept arriving closer together than `idleTimeout`; raise `maxDuration` if those changes belong in one commit. It does not prove continuous activity: an `idleTimeout` close to `maxDuration` ends quiet windows this way too. -- `identity_change` means a write arrived that could not join an open window, nor be proven to change - other files than it: a different GitTarget on the same branch, or a different author or - attribution state writing where the worker cannot prove a file of its own (a file with other - documents, a kustomize folder, a placement template). A high share means commits are being split - by interleaving rather than by time, and no timer changes that. - `path_conflict` means another author's write changes a file the window's writes change, so the window committed first. Authors editing different files keep a window each. +- `unproven_footprint` means another author, or another attribution state, wrote where the worker + cannot prove the files apart: a file with other documents, a kustomize folder, a placement + template, an encrypted type. The write, or the window, may touch the other's file, so the window + committed first. +- `other_target` means a write of another GitTarget on the same branch arrived: GitTargets on one + branch commit one window at a time, for their encryption and bootstrap. +- `single_window` means another author wrote after the worker fell back to one window at a time (see + `footprint_fallback`), so their windows no longer stay open side by side. + + These four split commits by interleaving rather than by time, and no timer changes that. With + `timer_source="commit_request"` they count saves cut short: the save commits what its window held + when it closed, and its `Ready` message says why. - `attach_next` is a save with `attach: Next` closing the author's open window before it waits. - `buffer_limit` means the worker's retained-write budget was reached, and the window was flushed to stay within it. Writes committed but not yet pushed count toward that budget, so this reads diff --git a/internal/controller/commitrequest_controller_unit_test.go b/internal/controller/commitrequest_controller_unit_test.go index 78d41e8db..ba69b6339 100644 --- a/internal/controller/commitrequest_controller_unit_test.go +++ b/internal/controller/commitrequest_controller_unit_test.go @@ -725,6 +725,12 @@ func TestCommitRequestReconcile_TerminalWriteRetriesOnConflict(t *testing.T) { // --- pure helpers (formerly internal/queue/commit_request_test.go) --- +// windowClosedEarlyValues are every value git.FinalizeResult.WindowClosedEarly takes. +var windowClosedEarlyValues = []string{ + git.WindowClosedEarlyPathConflict, git.WindowClosedEarlyUnprovenFootprint, git.WindowClosedEarlyOtherTarget, + git.WindowClosedEarlySingleWindow, git.WindowClosedEarlyFootprintFallback, +} + func TestApplyFinalizeResultToStatus(t *testing.T) { t.Run("committed", func(t *testing.T) { var cr configv1alpha3.CommitRequest @@ -780,6 +786,45 @@ func TestApplyFinalizeResultToStatus(t *testing.T) { assert.Equal(t, "boom", stalled.Message) }) + t.Run("a window another write closed early says why, and still settles as its outcome", func(t *testing.T) { + for _, closedEarly := range windowClosedEarlyValues { + note := windowClosedEarlyNote(closedEarly) + for _, outcome := range []git.FinalizeOutcome{git.FinalizeCommitted, git.FinalizeAlreadyPresent} { + var cr configv1alpha3.CommitRequest + applyFinalizeResultToStatus(&cr, git.FinalizeResult{Outcome: outcome, Commit: "abc", Branch: "main", + WindowClosedEarly: closedEarly}, nil) + want := "; the window closed early, because " + note + + ": edits made after that are not part of this save" + for _, conditionType := range []string{ConditionTypeReady, ConditionTypeReconciling} { + condition := apimeta.FindStatusCondition(cr.Status.Conditions, conditionType) + require.NotNil(t, condition, "%s %s", closedEarly, outcome) + assert.True(t, strings.HasSuffix(condition.Message, want), "%s %s %s: %q", + closedEarly, outcome, conditionType, condition.Message) + } + requireCondition(t, cr, ConditionTypeReady, metav1.ConditionTrue, string(outcome)) + } + } + + var failed configv1alpha3.CommitRequest + applyFinalizeResultToStatus(&failed, git.FinalizeResult{Outcome: git.FinalizeCommitted, + WindowClosedEarly: git.WindowClosedEarlyPathConflict}, errors.New("boom")) + stalled := requireCondition(t, failed, ConditionTypeStalled, metav1.ConditionTrue, crReasonFinalizeFailed) + assert.Equal(t, "boom", stalled.Message, "a failure says only why it failed") + }) + + t.Run("every way a window closes early has its own note, and nothing else has one", func(t *testing.T) { + notes := map[string]bool{} + for _, closedEarly := range windowClosedEarlyValues { + note := windowClosedEarlyNote(closedEarly) + assert.NotEmpty(t, note, closedEarly) + assert.False(t, notes[note], "%s shares its note", closedEarly) + notes[note] = true + } + for _, other := range []string{"", "idle_timeout", "max_duration", "shutdown", "made_up"} { + assert.Empty(t, windowClosedEarlyNote(other), other) + } + }) + t.Run("unknown outcome stalls", func(t *testing.T) { var cr configv1alpha3.CommitRequest applyFinalizeResultToStatus(&cr, git.FinalizeResult{}, nil) diff --git a/internal/controller/commitrequest_finalize.go b/internal/controller/commitrequest_finalize.go index a75888978..64ff8ab15 100644 --- a/internal/controller/commitrequest_finalize.go +++ b/internal/controller/commitrequest_finalize.go @@ -253,6 +253,41 @@ func applyFinalizeResultToStatus( // An empty or unknown outcome with no error is a bug, not a benign // rejection; fail it so it is not silently hidden. failCommitRequest(cr, crReasonUnexpectedOutcome, "unexpected finalize outcome: "+string(result.Outcome)) + return + } + if note := windowClosedEarlyNote(result.WindowClosedEarly); note != "" { + appendCommitRequestMessage(cr, "; the window closed early, because "+note+ + ": edits made after that are not part of this save", ConditionTypeReady, ConditionTypeReconciling) + } +} + +// windowClosedEarlyNote says why a write outside the request's window closed it early, for a +// git.FinalizeResult.WindowClosedEarly; "" for any other value. The request still settles as its outcome +// says, but it saves less than its author may have meant to. +func windowClosedEarlyNote(closedEarly string) string { + switch closedEarly { + case git.WindowClosedEarlyPathConflict: + return "another author's write touched a file it held" + case git.WindowClosedEarlyUnprovenFootprint: + return "another author wrote while the files of that write, or of this window, could not be proven apart" + case git.WindowClosedEarlyOtherTarget: + return "a write of another GitTarget on the same branch arrived, and GitTargets on one branch " + + "commit one at a time" + case git.WindowClosedEarlySingleWindow: + return "another author wrote while the branch worker holds one window at a time" + case git.WindowClosedEarlyFootprintFallback: + return "the branch worker fell back to one window at a time" + default: + return "" + } +} + +// appendCommitRequestMessage adds note to the message of each of cr's conditions named. +func appendCommitRequestMessage(cr *configv1alpha3.CommitRequest, note string, conditionTypes ...string) { + for _, conditionType := range conditionTypes { + if condition := apimeta.FindStatusCondition(cr.Status.Conditions, conditionType); condition != nil { + condition.Message += note + } } } diff --git a/internal/git/branch_worker.go b/internal/git/branch_worker.go index 0f2decd0a..ea3965b38 100644 --- a/internal/git/branch_worker.go +++ b/internal/git/branch_worker.go @@ -440,7 +440,6 @@ const ( windowFinalizeReasonMaxDuration windowFinalizeReason = "max-duration" windowFinalizeReasonAttachNext windowFinalizeReason = "attach-next" windowFinalizeReasonResyncBeforeApply windowFinalizeReason = "resync-before-apply" - windowFinalizeReasonIdentityChange windowFinalizeReason = "author-or-target-change" windowFinalizeReasonBufferLimit windowFinalizeReason = "buffer-limit" windowFinalizeReasonShutdown windowFinalizeReason = "shutdown" windowFinalizeReasonForeignCommit windowFinalizeReason = "foreign-commit" @@ -452,8 +451,34 @@ const ( // windowFinalizeReasonFootprintFallback closes the windows open side by side when a commit outside // its footprint makes the worker fall back to one window at a time (fallBackToSingleWindow). windowFinalizeReasonFootprintFallback windowFinalizeReason = "footprint-fallback" + // windowFinalizeReasonOtherTarget closes the open windows before a write of another GitTarget on + // the branch: per-target encryption and bootstrap stay serial. + windowFinalizeReasonOtherTarget windowFinalizeReason = "other-target" + // windowFinalizeReasonUnprovenFootprint closes a window before a write of another author when the + // write's footprint, or the window's, cannot be proven, so the two may touch the same file. + windowFinalizeReasonUnprovenFootprint windowFinalizeReason = "unproven-footprint" + // windowFinalizeReasonSingleWindow closes a window before a write of another author once the worker + // holds one window at a time, after a footprint fallback. + windowFinalizeReasonSingleWindow windowFinalizeReason = "single-window" ) +// closedEarlyByAnotherWrite reports whether a window closed for this reason was cut short by a write +// outside it, or by the worker's fallback to one window, rather than by its own timers or its owner. +// A request attached to such a window is told so. +func (r windowFinalizeReason) closedEarlyByAnotherWrite() bool { + switch r { + case windowFinalizeReasonPathConflict, windowFinalizeReasonOtherTarget, windowFinalizeReasonUnprovenFootprint, + windowFinalizeReasonSingleWindow, windowFinalizeReasonFootprintFallback: + return true + case windowFinalizeReasonUnspecified, windowFinalizeReasonIdleTimeout, windowFinalizeReasonMaxDuration, + windowFinalizeReasonAttachNext, windowFinalizeReasonResyncBeforeApply, windowFinalizeReasonBufferLimit, + windowFinalizeReasonShutdown, windowFinalizeReasonForeignCommit, windowFinalizeReasonApplyDue: + return false + default: + return false + } +} + // NewBranchWorker creates a worker for a (provider, branch) combination. A zero // BranchWorkerLimits gets the defaults for both knobs; see BranchWorkerLimits. func NewBranchWorker( @@ -1645,6 +1670,11 @@ func (l *branchWorkerEventLoop) finalizeWindow(window *openWindow, reason window windowTarget := targetNamespace + "/" + targetName pendingCR := window.pendingCR effectiveMessage := window.pendingMessage + if pendingCR != nil && reason.closedEarlyByAnotherWrite() { + if pcr := l.pendingCRs[*pendingCR]; pcr != nil { + pcr.closedEarlyBy = reason + } + } // The render-fidelity gate drops the whole window, request or not: its events were planned // against a render nobody has checked. Suspension is read from the write built below, because // a suspended target still scans. See write_gate.go. @@ -3046,16 +3076,14 @@ const ( ) // metricLabel is the commit_windows_total `close_reason` value for this reason. The log field keeps -// its hyphenated form; a label value follows the snake_case the other labels use. Only -// identity_change is named apart from its log form, author-or-target-change. +// its hyphenated form; a label value follows the snake_case the other labels use. func (r windowFinalizeReason) metricLabel() string { switch r { - case windowFinalizeReasonIdentityChange: - return "identity_change" case windowFinalizeReasonIdleTimeout, windowFinalizeReasonMaxDuration, windowFinalizeReasonAttachNext, windowFinalizeReasonBufferLimit, windowFinalizeReasonResyncBeforeApply, windowFinalizeReasonShutdown, windowFinalizeReasonForeignCommit, windowFinalizeReasonApplyDue, windowFinalizeReasonPathConflict, - windowFinalizeReasonFootprintFallback, windowFinalizeReasonUnspecified: + windowFinalizeReasonFootprintFallback, windowFinalizeReasonOtherTarget, windowFinalizeReasonUnprovenFootprint, + windowFinalizeReasonSingleWindow, windowFinalizeReasonUnspecified: return strings.ReplaceAll(string(r), "-", "_") default: return "unspecified" diff --git a/internal/git/commit_request_attach.go b/internal/git/commit_request_attach.go index 9309f0c75..74bbb09d7 100644 --- a/internal/git/commit_request_attach.go +++ b/internal/git/commit_request_attach.go @@ -107,8 +107,24 @@ type FinalizeResult struct { // Held is why a request the worker holds has not reached the remote yet: the worker's // publication report while it cannot publish, empty otherwise. See PublicationStatus. Held string + // WindowClosedEarly is the close reason, as git_commit_windows_total's close_reason names it, of a + // window this request was attached to that a write outside it closed before the window's own + // timers ran out: "path_conflict", "unproven_footprint", "other_target", "single_window" or + // "footprint_fallback". The author's edits after that write are not in this request's commit. + // Empty when the window closed for any other reason. + WindowClosedEarly string } +// The values of FinalizeResult.WindowClosedEarly: the close_reason of git_commit_windows_total for a +// window a write outside it closed early. +const ( + WindowClosedEarlyPathConflict = "path_conflict" + WindowClosedEarlyUnprovenFootprint = "unproven_footprint" + WindowClosedEarlyOtherTarget = "other_target" + WindowClosedEarlySingleWindow = "single_window" + WindowClosedEarlyFootprintFallback = "footprint_fallback" +) + // AttachCommitRequest is the "attach this CommitRequest to the author's window, with its // message and its timers" work item. It rides the same per-worker FIFO // event queue as resource events, so by audit-stream ordering it is processed @@ -217,6 +233,9 @@ type pendingCommitRequest struct { // instant check at expiry would miss the common case and report the refusal as "nothing was // pending" — intermittently, which is worse than never. sawForeignWindow bool + // closedEarlyBy is the reason a write outside the window this request is attached to closed it + // early (closedEarlyByAnotherWrite), empty otherwise. It is reported on the request's result. + closedEarlyBy windowFinalizeReason } // expiryOutcome is the terminal outcome for a request whose attach timeout ran out without it diff --git a/internal/git/commit_request_attach_loop.go b/internal/git/commit_request_attach_loop.go index ae188f2fd..850615c37 100644 --- a/internal/git/commit_request_attach_loop.go +++ b/internal/git/commit_request_attach_loop.go @@ -520,8 +520,12 @@ func (l *branchWorkerEventLoop) resolveCommitRequest(id commitRequestID, result if result.Branch == "" { result.Branch = l.w.Branch } + pcr := l.pendingCRs[id] + if pcr != nil && pcr.closedEarlyBy != "" { + result.WindowClosedEarly = pcr.closedEarlyBy.metricLabel() + } l.w.recordCommitRequestOutcome(id, result) - if pcr := l.pendingCRs[id]; pcr != nil && pcr.catchUpNow { + if pcr != nil && pcr.catchUpNow { l.catchUpAfterSave(pcr, result.Commit) } delete(l.pendingCRs, id) @@ -530,6 +534,7 @@ func (l *branchWorkerEventLoop) resolveCommitRequest(id commitRequestID, result "request", id.Namespace+"/"+id.Name, "outcome", string(result.Outcome), "commit", result.Commit, + "windowClosedEarly", result.WindowClosedEarly, "err", result.Err) } diff --git a/internal/git/commit_window_metrics_test.go b/internal/git/commit_window_metrics_test.go index 0233fc082..b72ce6968 100644 --- a/internal/git/commit_window_metrics_test.go +++ b/internal/git/commit_window_metrics_test.go @@ -85,8 +85,8 @@ func TestCommitWindowMetrics_EachCloseReasonIsCountedUnderItsOwnName(t *testing. Events: []Event{configMapTargetEvent("b", "bob", "team-a")}, }}) - // identity_change: once the worker holds one window at a time, another author's write closes - // bob's window whatever it writes. + // single_window: once the worker holds one window at a time, another author's write closes bob's + // window whatever it writes. loop.singleWindow = true loop.handleQueueItem(WorkItem{Request: &WriteRequest{ Events: []Event{configMapTargetEvent("c", "carol", "team-a")}, @@ -97,7 +97,7 @@ func TestCommitWindowMetrics_EachCloseReasonIsCountedUnderItsOwnName(t *testing. assert.Equal(t, int64(1), windowsClosed(t, reader, "max_duration", windowTimerSourceTarget)) assert.Equal(t, int64(1), windowsClosed(t, reader, "path_conflict", windowTimerSourceTarget)) - assert.Equal(t, int64(1), windowsClosed(t, reader, "identity_change", windowTimerSourceTarget)) + assert.Equal(t, int64(1), windowsClosed(t, reader, "single_window", windowTimerSourceTarget)) assert.Equal(t, int64(1), windowsClosed(t, reader, "shutdown", windowTimerSourceTarget)) requireOneObservationPerWindow(t, reader, 4) } @@ -109,7 +109,6 @@ func TestCommitWindowMetrics_EveryCloseReasonHasItsLabel(t *testing.T) { windowFinalizeReasonIdleTimeout: "idle_timeout", windowFinalizeReasonMaxDuration: "max_duration", windowFinalizeReasonAttachNext: "attach_next", - windowFinalizeReasonIdentityChange: "identity_change", windowFinalizeReasonBufferLimit: "buffer_limit", windowFinalizeReasonResyncBeforeApply: "resync_before_apply", windowFinalizeReasonShutdown: "shutdown", @@ -117,6 +116,9 @@ func TestCommitWindowMetrics_EveryCloseReasonHasItsLabel(t *testing.T) { windowFinalizeReasonApplyDue: "apply_due", windowFinalizeReasonPathConflict: "path_conflict", windowFinalizeReasonFootprintFallback: "footprint_fallback", + windowFinalizeReasonOtherTarget: "other_target", + windowFinalizeReasonUnprovenFootprint: "unproven_footprint", + windowFinalizeReasonSingleWindow: "single_window", windowFinalizeReasonUnspecified: "unspecified", windowFinalizeReason("made-up"): "unspecified", } { diff --git a/internal/git/window_admission.go b/internal/git/window_admission.go index 02b23e23a..312993c73 100644 --- a/internal/git/window_admission.go +++ b/internal/git/window_admission.go @@ -14,12 +14,14 @@ import ( // Otherwise the windows it cannot sit beside close first, oldest first, so their commits land before // its own: // -// - every other window, with close reason identity_change, when the write is of another GitTarget, -// when its footprint or theirs cannot be proven, or once the worker fell back to one window; +// - every other window, with close reason other_target, when the write is of another GitTarget; +// - every other window, with close reason single_window, once the worker fell back to one window; +// - a window whose footprint, or the write's, cannot be proven, with close reason unproven_footprint; // - the windows whose footprint overlaps the write's, with close reason path_conflict. // // Before a write is admitted beside others, every open window is proven against the current revision -// (FootprintReproved); windows whose new proofs overlap close first, with path_conflict. +// (FootprintReproved); windows whose new proofs overlap close first, with path_conflict when they share +// a proven path and unproven_footprint when a proof is unknown. // // The decisions have names in the log lines, and the reference model reads them: WindowOpened, // WriteJoinedWindow, FootprintReproved, WindowClosed (with its reason), FootprintChecked and @@ -45,9 +47,9 @@ func (l *branchWorkerEventLoop) admitWrite(event Event) *footprint { if len(others) == 0 { return l.extendedFootprint(own, event) } - if why := l.serialAdmission(event, others); why != "" { + if reason, why := l.serialAdmission(event, others); why != "" { for _, other := range others { - l.closeBeforeWrite(other, event, windowFinalizeReasonIdentityChange, why) + l.closeBeforeWrite(other, event, reason, why) } return l.extendedFootprint(own, event) } @@ -62,10 +64,10 @@ func (l *branchWorkerEventLoop) admitWrite(event Event) *footprint { for _, other := range l.windows.others(own) { switch { case !write.known(): - l.closeBeforeWrite(other, event, windowFinalizeReasonIdentityChange, + l.closeBeforeWrite(other, event, windowFinalizeReasonUnprovenFootprint, "the write's footprint is "+write.String()) case !other.footprint.known(): - l.closeBeforeWrite(other, event, windowFinalizeReasonIdentityChange, + l.closeBeforeWrite(other, event, windowFinalizeReasonUnprovenFootprint, "the window's footprint is "+other.footprint.String()) case other.footprint.overlaps(write): l.closeBeforeWrite(other, event, windowFinalizeReasonPathConflict, @@ -80,16 +82,16 @@ func (l *branchWorkerEventLoop) admitWrite(event Event) *footprint { } // serialAdmission says why a write cannot be admitted beside other windows whatever their -// footprints, or "". -func (l *branchWorkerEventLoop) serialAdmission(event Event, others []*openWindow) string { +// footprints, and the close reason that gives them; "" when it can be. +func (l *branchWorkerEventLoop) serialAdmission(event Event, others []*openWindow) (windowFinalizeReason, string) { switch { case l.singleWindow: - return "the worker holds one window at a time" + return windowFinalizeReasonSingleWindow, "the worker holds one window at a time" case others[0].GitTarget != event.GitTargetName || others[0].GitTargetNamespace != event.GitTargetNamespace: // Every open window is of one GitTarget: per-target encryption and bootstrap stay serial. - return "the write is of another GitTarget" + return windowFinalizeReasonOtherTarget, "the write is of another GitTarget" default: - return "" + return "", "" } } @@ -130,33 +132,59 @@ func (l *branchWorkerEventLoop) reprove(window *openWindow, rev footprintRevisio } // closeConflictingWindows closes, oldest first, every open window whose footprint overlaps another -// open window's, once more than one is open. +// open window's, once more than one is open. A window that shares a proven path with another closes +// with path_conflict; one that overlaps only because a footprint is no longer proven, as after a +// GitTarget change, closes with unproven_footprint. func (l *branchWorkerEventLoop) closeConflictingWindows() { open := l.windows.all() if len(open) <= 1 { return } - involved := map[*openWindow]bool{} + involved := map[*openWindow]windowFinalizeReason{} for i, a := range open { for _, b := range open[i+1:] { - if a.footprint.overlaps(*b.footprint) { - involved[a], involved[b] = true, true + if reason, overlap := overlapCloseReason(*a.footprint, *b.footprint); overlap { + involved[a] = strongerOverlapReason(involved[a], reason) + involved[b] = strongerOverlapReason(involved[b], reason) } } } for _, window := range open { - if !involved[window] { + reason, ok := involved[window] + if !ok { continue } l.w.Log.Info("Commit window footprint overlaps another open window's; finalizing it", "window", window.seq, "branch", l.w.Branch, "windowAuthor", window.Author, - "footprint", window.footprint.String()) - l.finalizeWindow(window, windowFinalizeReasonPathConflict) + "footprint", window.footprint.String(), + "reason", string(reason)) + l.finalizeWindow(window, reason) } } +// overlapCloseReason says whether two footprints overlap, and the close reason that gives: path_conflict +// when both are proven and share a path, unproven_footprint when either is unknown. +func overlapCloseReason(a, b footprint) (windowFinalizeReason, bool) { + if !a.overlaps(b) { + return "", false + } + if a.known() && b.known() { + return windowFinalizeReasonPathConflict, true + } + return windowFinalizeReasonUnprovenFootprint, true +} + +// strongerOverlapReason is the reason a window overlapping several others closes with: path_conflict +// once any of them shares a proven path with it. +func strongerOverlapReason(current, next windowFinalizeReason) windowFinalizeReason { + if current == windowFinalizeReasonPathConflict { + return current + } + return next +} + // closeBeforeWrite closes a window the write cannot be admitted beside. func (l *branchWorkerEventLoop) closeBeforeWrite( window *openWindow, event Event, reason windowFinalizeReason, why string, diff --git a/internal/git/window_admission_test.go b/internal/git/window_admission_test.go index 482c6662f..21d207d5c 100644 --- a/internal/git/window_admission_test.go +++ b/internal/git/window_admission_test.go @@ -101,6 +101,120 @@ func TestWindowAdmission_AWriteToAFileAnotherWindowHoldsClosesThatWindowFirst(t ) } +// A request whose window a write outside it closes early is told why on its result, by the close +// reason git_commit_windows_total counts that window under; one whose window closes on its own timer is +// told nothing, since it was not cut short. +func TestWindowAdmission_ARequestWhoseWindowAnotherWriteClosedIsToldWhy(t *testing.T) { + shared := echoDocument("s1", "a") + "---\n" + echoDocument("s2", "b") + for _, tc := range []struct { + name string + files map[string]string + // before runs before alice's window opens. + before func(*echoFixture) + // other is the write outside alice's window. + other func(*echoFixture) + // closeOnItsOwn runs out alice's window's timer after the other write. + closeOnItsOwn bool + want string + }{ + { + name: "another author writes a file the window holds", + other: func(f *echoFixture) { f.writeBy("carol", "x", "x3") }, + want: WindowClosedEarlyPathConflict, + }, + { + name: "another author writes a file that cannot be proven apart", + files: map[string]string{echoTarget + "/default/configmaps/shared.yaml": shared}, + other: func(f *echoFixture) { f.writeBy("carol", "s1", "c") }, + want: WindowClosedEarlyUnprovenFootprint, + }, + { + name: "a write of another GitTarget on the branch", + before: bootstrapTeamB, + other: func(f *echoFixture) { f.writeWindow(teamBEvent("carol", "b2")) }, + want: WindowClosedEarlyOtherTarget, + }, + { + name: "another author writes while the worker holds one window", + before: func(f *echoFixture) { f.loop.singleWindow = true }, + other: func(f *echoFixture) { f.writeBy("carol", "z", "z2") }, + want: WindowClosedEarlySingleWindow, + }, + { + name: "another author writes a file of their own", + other: func(f *echoFixture) { f.writeBy("carol", "z", "z2") }, + closeOnItsOwn: true, + }, + } { + t.Run(tc.name, func(t *testing.T) { + f := newAdmissionFixture(t, "admission-closed-early", tc.files) + if tc.before != nil { + tc.before(f) + } + f.writeBy("alice", "x", "x2") + serviceAttach(f.loop, attachReq("alice", time.Hour)) + alice := f.loop.windows.all() + require.Len(t, alice, 1) + require.NotNil(t, alice[0].pendingCR, "the request is attached to alice's window") + + tc.other(f) + if tc.closeOnItsOwn { + require.Len(t, f.loop.windows.all(), 2, "disjoint windows stay open side by side") + alice[0].timers.maxAt = time.Now().Add(-time.Millisecond) + f.loop.closeOrArmWindow() + f.loop.endWake(0) + } + assert.Equal(t, []string{"carol"}, authorsOf(f.loop.windows.all()), "alice's window is closed") + f.loop.pushPending() + + result, ok := outcome(t, f.worker) + require.True(t, ok, "the request is resolved once its commit is pushed") + require.NoError(t, result.Err) + assert.Equal(t, FinalizeCommitted, result.Outcome) + assert.Equal(t, tc.want, result.WindowClosedEarly) + }) + } +} + +// The reasons a request is told its window closed early are the values FinalizeResult.WindowClosedEarly +// documents, each under its close_reason label. +func TestWindowFinalizeReason_ClosedEarlyByAnotherWrite(t *testing.T) { + var early []string + for _, reason := range []windowFinalizeReason{ + windowFinalizeReasonUnspecified, windowFinalizeReasonIdleTimeout, windowFinalizeReasonMaxDuration, + windowFinalizeReasonAttachNext, windowFinalizeReasonResyncBeforeApply, windowFinalizeReasonBufferLimit, + windowFinalizeReasonShutdown, windowFinalizeReasonForeignCommit, windowFinalizeReasonApplyDue, + windowFinalizeReasonPathConflict, windowFinalizeReasonFootprintFallback, windowFinalizeReasonOtherTarget, + windowFinalizeReasonUnprovenFootprint, windowFinalizeReasonSingleWindow, + } { + if reason.closedEarlyByAnotherWrite() { + early = append(early, reason.metricLabel()) + } + } + assert.ElementsMatch(t, []string{ + WindowClosedEarlyPathConflict, WindowClosedEarlyUnprovenFootprint, WindowClosedEarlyOtherTarget, + WindowClosedEarlySingleWindow, WindowClosedEarlyFootprintFallback, + }, early) +} + +// bootstrapTeamB adds GitTarget team-b to the fixture's branch and commits its first write at once, so +// its folder is bootstrapped and later writes there are live ones. +func bootstrapTeamB(f *echoFixture) { + createGitTargetWithPruneMode(f.t, f.worker, "team-b", "team-b", configv1alpha3.PruneOnEvent) + window := f.loop.defaultWindow + f.loop.defaultWindow = commitWindowDefaults{} + f.writeWindow(teamBEvent("carol", "b1")) + f.loop.defaultWindow = window +} + +// teamBEvent is an update by author of a ConfigMap of GitTarget team-b. +func teamBEvent(author, value string) Event { + event := configMapTargetEvent("b", author, "team-b") + event.Operation = string(itypes.OperationUpdate) + event.Object.Object["data"] = map[string]interface{}{"key": value} + return event +} + func TestWindowAdmission_AWriteThatCannotBeProvenStaysSerial(t *testing.T) { shared := echoDocument("s1", "a") + "---\n" + echoDocument("s2", "b") f := newAdmissionFixture(t, "admission-unproven", @@ -279,24 +393,14 @@ func TestWindowAdmission_ShutdownDecidesTheWritesAlreadyQueued(t *testing.T) { func TestWindowAdmission_AWriteOfAnotherGitTargetClosesTheOpenWindows(t *testing.T) { f := newAdmissionFixture(t, "admission-other-target", nil) reader := captureInfo(f.worker) - createGitTargetWithPruneMode(t, f.worker, "team-b", "team-b", configv1alpha3.PruneOnEvent) - other := func(author, value string) Event { - event := configMapTargetEvent("b", author, "team-b") - event.Operation = string(itypes.OperationUpdate) - event.Object.Object["data"] = map[string]interface{}{"key": value} - return event - } - window := f.loop.defaultWindow - f.loop.defaultWindow = commitWindowDefaults{} - f.writeWindow(other("carol", "b1")) // team-b's folder is bootstrapped by its first commit + bootstrapTeamB(f) require.Empty(t, f.loop.windows.all()) - f.loop.defaultWindow = window f.writeBy("alice", "x", "x2") - f.writeWindow(other("bob", "b2")) + f.writeWindow(teamBEvent("bob", "b2")) assert.Equal(t, []string{"bob"}, authorsOf(f.loop.windows.all())) - assert.Len(t, reader.matching(`"msg"="Finalizing open commit window" "reason"="author-or-target-change" `+ + assert.Len(t, reader.matching(`"msg"="Finalizing open commit window" "reason"="other-target" `+ `"windowAuthor"="alice"`), 1, "per-target encryption and bootstrap stay serial") } @@ -581,7 +685,9 @@ func TestFootprint_OverlapUnionAndOutside(t *testing.T) { // index of the old spec was reused, and they stayed open side by side. func TestWindowAdmission_AGitTargetChangeProvesTheOpenWindowsAgain(t *testing.T) { f := newAdmissionFixture(t, "admission-generation", nil) + reader := captureInfo(f.worker) f.writeBy("alice", "x", "x2") + serviceAttach(f.loop, attachReq("alice", time.Hour)) f.writeBy("bob", "z", "z2") require.Equal(t, []string{"alice", "bob"}, authorsOf(f.loop.windows.all())) @@ -594,6 +700,15 @@ func TestWindowAdmission_AGitTargetChangeProvesTheOpenWindowsAgain(t *testing.T) assert.Equal(t, []string{"carol"}, authorsOf(f.loop.windows.all()), "proven again under the new spec, the open windows are unknown, and close before carol's write") + for _, author := range []string{"alice", "bob"} { + assert.Len(t, reader.matching(`"msg"="Finalizing open commit window" "reason"="unproven-footprint" `+ + `"windowAuthor"="`+author+`"`), 1, "%s's window shares no proven file: it is unproven", author) + } + f.loop.pushPending() + result, ok := outcome(t, f.worker) + require.True(t, ok) + assert.Equal(t, WindowClosedEarlyUnprovenFootprint, result.WindowClosedEarly, + "alice's save is not told another author touched its file") } // TestWindowAdmission_AResetProvesTheOpenWindowsAgain pins the resets in a footprint's revision. A push diff --git a/internal/git/window_model_test.go b/internal/git/window_model_test.go index 60156fa5f..a06cd2e5a 100644 --- a/internal/git/window_model_test.go +++ b/internal/git/window_model_test.go @@ -526,7 +526,7 @@ func (m *windowModel) admit(author, obj string) *modelFootprint { for _, other := range m.others(own) { switch { case write.unknown || other.footprint.unknown: - m.close(other, windowFinalizeReasonIdentityChange) + m.close(other, windowFinalizeReasonUnprovenFootprint) case write.overlaps(*other.footprint): m.close(other, windowFinalizeReasonPathConflict) } @@ -545,18 +545,24 @@ func (m *windowModel) reprove() { f := m.proveWindow(w) w.footprint = &f } - involved := map[*modelWindow]bool{} + involved := map[*modelWindow]windowFinalizeReason{} for i, a := range m.windows { for _, b := range m.windows[i+1:] { - if a.footprint.overlaps(*b.footprint) { - involved[a], involved[b] = true, true + if !a.footprint.overlaps(*b.footprint) { + continue + } + reason := windowFinalizeReasonUnprovenFootprint + if !a.footprint.unknown && !b.footprint.unknown { + reason = windowFinalizeReasonPathConflict } + involved[a] = strongerOverlapReason(involved[a], reason) + involved[b] = strongerOverlapReason(involved[b], reason) } } for _, w := range slices.Clone(m.windows) { - if involved[w] { + if reason, ok := involved[w]; ok { m.reached(reachReproof) - m.close(w, windowFinalizeReasonPathConflict) + m.close(w, reason) } } } diff --git a/internal/telemetry/exporter.go b/internal/telemetry/exporter.go index 345296fe5..2dd1ead2e 100644 --- a/internal/telemetry/exporter.go +++ b/internal/telemetry/exporter.go @@ -254,9 +254,9 @@ var ( GitWritesDroppedTotal metric.Int64Counter // GitCommitWindowsTotal counts closed commit windows, labelled by {gittarget_namespace, // gittarget_name, close_reason, timer_source}. close_reason says what ended the window - // (idle_timeout, max_duration, attach_next, identity_change, path_conflict, buffer_limit, - // resync_before_apply, shutdown, foreign_commit for a Git host's push notice, apply_due for - // the flush before an apply); timer_source says whose timers were in effect: the GitTarget's, + // (idle_timeout, max_duration, attach_next, path_conflict, unproven_footprint, other_target, + // single_window, footprint_fallback, buffer_limit, resync_before_apply, shutdown, foreign_commit + // for a Git host's push notice, apply_due for the flush before an apply); timer_source says whose timers were in effect: the GitTarget's, // or a CommitRequest's that attached and replaced them. Every window is counted exactly once, at // the start of its finalize, so a window that then produces no diff or fails to commit is counted // too. A push replay rebuilds commits and closes no window, and a CommitEmpty record has none.