diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 59c9f5f30a..5ec8e8316f 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -2190,4 +2190,17 @@ field. The poller itself treats an issue served without a labels array as unlabeled — `state.labels` becomes an empty list — so neither shape an issue arrives in loses events; the unit tests serve each shape directly. +**`jiramock` updated change:** an issue added with `AddIssue` now starts +with `updated` equal to `created`, instead of the time of the call. +`AddCommentFromActorAt` and `AddLabelChangeAt` (and so `AddComment`, +`AddCommentFromActor` and `AddLabelChange`) move it forward to the activity +time, never back; entity property calls leave it alone, as Jira does. +`SetIssueLabels` leaves it alone too and adds no changelog entry, unlike a +label edit in Jira, so use `AddLabelChange` when a label change should count +as activity. The Jira poller skips an issue whose `updated` is not after its +`lastCheck`, so the mock must serve it the way Jira does. This is +deliberately not treated as a breaking change: no function or signature +changed, and a scenario that adds activity after creating the issue sees +`updated` move with it. + Bump the pinned version when behaviour step vocabulary or `pkg/behaviourtest` APIs change. diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 124421ba35..aeb4c97143 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1714,14 +1714,19 @@ matches it. Use `labels: allowlist` if that group is broader than you want. ## Poll coordination -The poller uses Jira entity properties for distributed lock coordination and checkpoint tracking, following a write-then-verify protocol. Each cycle randomly selects up to N (default 5) issues from the candidate set for processing, spreading load across cycles. Two properties are stored on each processed issue: +The poller uses Jira entity properties for distributed lock coordination and checkpoint tracking, following a write-then-verify protocol. Each cycle first drops the candidates with no new activity, then randomly selects up to N (default 5) of the rest for processing, spreading load across cycles. A candidate has new activity when its `updated` time is after its `lastCheck`, clamped as described below; a candidate with no usable `lastCheck` (missing, unreadable, or more than two minutes in the future) or no usable `updated` time counts as new. Two properties are stored on each processed issue: - **Lock** (`fullsend.poll.{owner}.{repo}.lock`) — prevents concurrent pollers from *detecting changes on* the same issue simultaneously. The lock covers the change-detection window only: it is released when an issue finishes processing, before the dispatch records are written and consumed by the downstream dispatch step, and it is not renewed while an issue is being processed — a cycle that stalls longer than the stale threshold (15 minutes) can have its lock reclaimed by a concurrent poller, which may produce duplicate dispatches. Lock ownership through dispatch scheduling is part of the same tracked follow-up as dispatch confirmation. -- **Last check** (`fullsend.poll.{owner}.{repo}.lastCheck`) — tracks the timestamp of the most recent processed change. Only changes newer than this timestamp trigger agent dispatch. +- **Last check** (`fullsend.poll.{owner}.{repo}.lastCheck`) — tracks the timestamp of the most recent processed change. Only changes newer than this timestamp trigger agent dispatch. After each look at an issue it also advances to the issue's `updated` time when that is later, so an issue with nothing new since is skipped the next cycle. + If `updated` is less than 10 seconds before the look, the checkpoint stops + 10 seconds before the look (the safety margin), so the issue stays active. + The first look that starts 10 or more seconds after `updated`, normally the + next one, can dispatch a change inside the margin again and then moves the + checkpoint to `updated`; after that the issue is skipped. These properties are namespaced per target repo, so multiple repos can poll the same Jira project without interference. GitLab targets use a separate `fullsend.poll.gitlab.*` namespace that also includes the GitLab instance (see [GitLab runtime](#gitlab-runtime)). The properties are visible in Jira's issue properties API but do not appear in the issue UI. -> **Security note — coordination state is tamperable by any project editor.** Writing an issue entity property requires only Jira's **Edit Issues** permission, which is typically far broader than the project roles this driver maps to `write`. That means anyone who can edit a polled issue can write its `lastCheck` and lock properties. The driver treats both as untrusted: a `lastCheck` dated in the future is ignored (it would otherwise suppress all detection on the issue), and one rewound before the backfill window is clamped to the window's start, so a rewind can replay at most one backfill window of history rather than the whole issue — but within that window it can still re-surface old comments. Per-issue dispatch is capped to bound the blast radius. Even so, **treat Edit-Issues on a polled project as part of the trust boundary**: prefer scoping the poll to a project whose editors you trust, and remember that the authorization gate keys on the *comment's* Jira role, so who can edit issues (and comments) matters as much as who holds `write`. +> **Security note — coordination state is tamperable by any project editor.** Writing an issue entity property requires only Jira's **Edit Issues** permission, which is typically far broader than the project roles this driver maps to `write`. That means anyone who can edit a polled issue can write its `lastCheck` and lock properties. The driver treats both as untrusted: a `lastCheck` dated more than two minutes in the future is ignored (it would otherwise suppress all detection on the issue), and one rewound before the backfill window is clamped to the window's start, so a rewind can replay at most one backfill window of history rather than the whole issue — but within that window it can still re-surface old comments. Per-issue dispatch is capped to bound the blast radius. Even so, **treat Edit-Issues on a polled project as part of the trust boundary**: prefer scoping the poll to a project whose editors you trust, and remember that the authorization gate keys on the *comment's* Jira role, so who can edit issues (and comments) matters as much as who holds `write`. Three edge cases of checkpoint tracking are worth knowing: @@ -1733,9 +1738,14 @@ Three edge cases of checkpoint tracking are worth knowing: is a security control (it prevents a rewound `lastCheck` from replaying an issue's entire history), but it cannot distinguish a malicious rewind from a legitimate long stop. Any Jira activity between the true checkpoint and the - clamped value is silently skipped. The cycle succeeds, the only evidence is - a `WARNING: lastCheck for ("") predates the backfill window; clamping to ` - line in the run log — treat this as an alert, not noise. Because detection + clamped value is silently skipped. The cycle succeeds, and the only evidence + is in the run log: an issue that is selected logs + `WARNING: lastCheck for ("") predates the backfill window; clamping to `, + and an issue that is skipped, because its `updated` time is more than a second + after its `lastCheck` but still older than the window, is named in one + `WARNING: activity filter: …` line per cycle that contains the same phrase + `predates the backfill window`. Activity on such an issue may have been + missed. Treat either line as an alert, not noise. Because detection is checkpoint-based, ordinary cron jitter and occasional skipped ticks are harmless (schedule accuracy affects latency, not correctness); the guarantee simply ends at 24 hours. A realistic trigger: **GitHub disables scheduled @@ -1748,11 +1758,11 @@ Three edge cases of checkpoint tracking are worth knowing: independently of GitHub Actions avoids the auto-disable risk. - **Comment edits count as new activity, and are attributed to the editor.** The poller filters comments on the later of their created and updated timestamps, so editing a comment (for example, adding a slash command to an old comment) is detected on the next cycle. Jira bumps a comment's updated timestamp on modifications other than body edits too (such as visibility changes), and any such bump counts as activity. The flip side: modifying a comment whose slash command was already dispatched makes it look new again and can re-dispatch it. An edit-detected comment is attributed to the account that last modified it (Jira's `updateAuthor`), not the original author — so a user who edits someone else's comment to inject a command is authorized on *their own* role, not the original author's. -Because each cron run is a fresh process, per-cycle Jira API cost is worth sizing for: a cycle loads the project's role structure (a role-list call plus one detail call per role) only when some selected issue has an event that needs project-role resolution (no `jira` entry, `labels: project_roles`, or a slash command when the `jira` entry sets no lists), then, in such a cycle, makes one additional call for each distinct actor below the highest role priority the first time they're seen that cycle, to check their group memberships (cached per actor for the rest of the cycle, but not across cron runs). Cost scales with the number of distinct commenting actors per cycle rather than the size of the groups backing a role. +Because each cron run is a fresh process, per-cycle Jira API cost is worth sizing for: a cycle loads the project's role structure (a role-list call plus one detail call per role) only when some selected issue has an event that needs project-role resolution (no `jira` entry, `labels: project_roles`, or a slash command when the `jira` entry sets no lists), then, in such a cycle, makes one additional call for each distinct actor below the highest role priority the first time they're seen that cycle, to check their group memberships (cached per actor for the rest of the cycle, but not across cron runs). Cost scales with the number of distinct commenting actors per cycle rather than the size of the groups backing a role. The activity filter adds one property read per unlocked candidate (at most M per cycle); a candidate with nothing new costs no lock write, no comment or changelog listing and no `lastCheck` write. Two more scaling limits: -- **Issues beyond the top M candidates can be starved.** Each cycle's JQL search returns at most M (default 50) candidates, ordered by `updated DESC`. If a project has more than M issues with in-scope activity at once, whichever issues aren't in that top-M window this cycle are simply never selected — there's no rotation across cycles to eventually reach them. This is expected to self-resolve for most projects (an issue with new activity moves toward the front of `updated DESC` on its own), but a project that consistently has more than M simultaneously-active issues will have some starved indefinitely. Narrow the default `--jql` (e.g. scope to a label or a subset of issue types) if this applies to you. +- **Issues beyond the top M candidates can be starved.** Each cycle's JQL search returns at most M (default 50) candidates, ordered by `updated DESC`. If a project has more than M issues with in-scope activity at once, whichever issues aren't in that top-M window this cycle are simply never selected — there's no rotation across cycles to eventually reach them. Issues with nothing new still take rows of the top M, because the activity filter runs on the rows the search returned. This is expected to self-resolve for most projects (an issue with new activity moves toward the front of `updated DESC` on its own), but a project that consistently has more than M simultaneously-active issues will have some starved indefinitely. Narrow the default `--jql` (e.g. scope to a label or a subset of issue types) if this applies to you. - **Comments are re-listed in full, oldest-first, every cycle.** The Jira REST API has no way to filter comments server-side by date, so `ListComments` always paginates from the start of an issue's comment history; the poller then filters client-side by timestamp. For issues with very long comment histories, this means re-fetching (and re-decoding) old comments every cycle just to discard them. Listings are capped at 10,000 entries per issue; an issue beyond that cap has its newest activity invisible to the poller (a WARNING is logged when the cap is hit). Each API response is bounded to 10MB, but the accumulated per-issue comment history is bounded only by the page cap — a per-issue byte budget is a tracked follow-up; against real Jira Cloud (which caps individual comments) the realistic worst case is tens of MB per issue. - **Sustained Jira errors can stall a cycle.** Each Jira call retries up to 5 times with exponential backoff, honoring `Retry-After` (capped at 5 minutes). Under a sustained 429 or outage a single cycle can therefore run long; the workflow's concurrency group queues subsequent cron runs rather than stacking them, and a failed cycle simply retries from its checkpoints on the next run. @@ -1825,7 +1835,7 @@ However, more pollers against the same Jira project means more API calls per cyc | `Jira polling is disabled` and no dispatches | `tracker.jira.poll.enabled` is not `true` | Set `tracker.jira.poll.enabled: true` | | Duplicate dispatches | `lastCheck` was cleared or missing | The poller treats a missing `lastCheck` as "never polled" and processes all recent changes. This is self-correcting — the next cycle advances `lastCheck` past the duplicates | | Old comment or label change on a newly polled issue never dispatches | Activity predates the first-poll backfill window | On an issue's first poll, activity older than the 24-hour backfill window is permanently skipped (the checkpoint advances past it). To pick up older activity, scope the initial `tracker.jira.poll.query` to recently updated issues and widen it gradually, or have someone re-trigger by commenting again | -| Activity during a long outage or disabled workflow is missing after resume | Poller gap exceeded the 24-hour backfill window | The same 24-hour window that bounds a first poll also bounds resumption — any `lastCheck` older than 24 hours is clamped forward. Check the run log for `predates the backfill window` — if present, events in the gap are permanently lost. Have affected users re-trigger by commenting again. See [Poll coordination](#poll-coordination) | +| Activity during a long outage or disabled workflow is missing after resume | Poller gap exceeded the 24-hour backfill window | The same 24-hour window that bounds a first poll also bounds resumption — any `lastCheck` older than 24 hours is clamped forward. Check the run log for `predates the backfill window` — if present, events in the gap may have been permanently lost. Have affected users re-trigger by commenting again. See [Poll coordination](#poll-coordination) | | GitLab Jira dispatch fails with `does not accept Jira work items` | The project's scaffold predates Jira dispatch | Rerun `fullsend repos install` for the project and merge the scaffold update. See [GitLab runtime](#gitlab-runtime) | | `WARNING: skipping event … for issue …: normalized event: …` in the poll log | The poller could not map the Jira event to a valid normalized event (for example a non-numeric issue id, or an author with neither an `accountId` nor a `name`) | The event is never dispatched: the checkpoint advances past it (for a GitLab target, once the issue's other dispatches succeed; until then each retry logs the warning again, see [Failures](#failures)) — unless *every* event of the cycle was dropped (failed validation or failed matching), in which case the poll fails and no checkpoint advances (see the next two rows). For an author with neither `accountId` nor `name`, a comment from another account maps cleanly and re-triggers. A non-numeric issue id belongs to the issue, so no new activity on it maps; report it to fullsend with the log line, which names the raw id Jira sent (an id the Jira UI does not show). An issue served without a `labels` field is treated as unlabeled, not skipped | | The poll fails with `all N events this cycle failed normalized-event validation` | Every event of the cycle was dropped for failing normalized-event validation — either a systemic cause (a Jira response-shape change, or an adapter gap) or the cycle's one event being bad: the guard counts events, not issues, so a single bad event in a one-event cycle is "every event" | No checkpoint was advanced, so the events are retried next cycle — and, while the dropped events are the cycle's only activity, every cycle: the red runs repeat until the events age past the first-poll backfill floor (24h by default) or another selected issue produces a valid event. Read the per-event `WARNING: skipping event …` lines above the error for the cause; if they name one cause for every issue, the Jira response shape may have changed — report it to fullsend with the log lines | diff --git a/internal/forge/jira/client.go b/internal/forge/jira/client.go index 9465ab0394..43491ab817 100644 --- a/internal/forge/jira/client.go +++ b/internal/forge/jira/client.go @@ -555,10 +555,14 @@ const maxSearchPages = 200 // // This endpoint is eventually consistent: Atlassian documents that recent // updates might not be immediately visible in results. For the poller that -// only means an issue can appear (or re-sort under ORDER BY updated) a -// cycle late — per-issue checkpoints come from the strongly-consistent -// direct comment/changelog GETs, never from search results, so no events -// are lost. Do not "fix" ordering assumptions by trusting search freshness. +// means an issue can appear, re-sort under ORDER BY updated, or show a +// stale updated value a cycle late. The poller skips an issue whose row's +// updated is not after its checkpoint (ADR 0160), so a stale row only +// delays the issue to a later cycle. A look raises the checkpoint to the +// row's updated value only after the direct comment/changelog GETs, and +// relies on them being at least as fresh as the row; if they lag it, an +// entry can be skipped. Do not "fix" ordering assumptions by trusting +// search freshness. func (c *LiveClient) SearchIssues(ctx context.Context, jql string, limit int) ([]Issue, error) { var all []Issue var nextPageToken string diff --git a/internal/jirapoll/discover.go b/internal/jirapoll/discover.go index a6f01eb231..02303f1df7 100644 --- a/internal/jirapoll/discover.go +++ b/internal/jirapoll/discover.go @@ -226,6 +226,15 @@ func (p *Poller) detectChanges(ctx context.Context, issue jira.Issue, lastCheck } } + // The checkpoint also reaches the issue's own updated value from the + // search row (ADR 0160, Decision item 3). Jira stamps updated a + // little after the newest entry; without this an issue whose updated + // is after every entry would pass the activity filter every cycle. + // The safety-margin cap below still applies. + if updated, err := parseJiraTimestamp(issue.Fields.Updated); err == nil && updated.After(maxSeen) { + maxSeen = updated + } + if safeCeiling := fetchStart.Add(-changeDetectionSafetyMargin); maxSeen.After(safeCeiling) { maxSeen = safeCeiling } diff --git a/internal/jirapoll/lock.go b/internal/jirapoll/lock.go index c5d0f9f421..9a855f7515 100644 --- a/internal/jirapoll/lock.go +++ b/internal/jirapoll/lock.go @@ -182,31 +182,66 @@ func (p *Poller) releaseLock(ctx context.Context, issueKey, expectedID string) e return p.client.DeleteEntityProperty(ctx, issueKey, propKey) } -// readLastCheck reads the lastCheck timestamp for an issue. +// readLastCheck reads the lastCheck timestamp for an issue, clamped as +// loadLastCheck describes, and logs a WARNING when it clamps. func (p *Poller) readLastCheck(ctx context.Context, issueKey string) (time.Time, error) { + lc, err := p.loadLastCheck(ctx, issueKey) + if err != nil { + return time.Time{}, err + } + switch lc.clamp { + case clampFuture: + log.Printf("WARNING: lastCheck for %s is in the future (%q); treating as unset", issueKey, lc.raw) + case clampFloor: + log.Printf("WARNING: lastCheck for %s (%q) predates the backfill window; clamping to %s", issueKey, lc.raw, lc.value.UTC().Format(time.RFC3339)) + } + return lc.value, nil +} + +// lastCheckClamp says how loadLastCheck changed a stored lastCheck. +type lastCheckClamp int + +const ( + clampNone lastCheckClamp = iota + clampFuture // stored beyond clock skew ahead; treated as unset + clampFloor // stored before the backfill window; floored to its start +) + +// storedLastCheck is a lastCheck as loadLastCheck read it. +type storedLastCheck struct { + value time.Time // after the clamps; zero when unset + stored time.Time // as stored; zero when unset + raw string // as stored, for quoted logging + clamp lastCheckClamp // how value differs from stored +} + +// loadLastCheck reads and clamps the lastCheck timestamp for an issue +// without logging, so a caller that reads every candidate's lastCheck can +// report the clamps once per cycle instead of once per issue. +func (p *Poller) loadLastCheck(ctx context.Context, issueKey string) (storedLastCheck, error) { propKey := p.lastCheckKey() raw, err := p.client.GetEntityProperty(ctx, issueKey, propKey) if err != nil { if errors.Is(err, forge.ErrNotFound) { - return time.Time{}, nil // first poll for this issue + return storedLastCheck{}, nil // first poll for this issue } - return time.Time{}, fmt.Errorf("get lastCheck property: %w", err) + return storedLastCheck{}, fmt.Errorf("get lastCheck property: %w", err) } if len(raw) == 0 { - return time.Time{}, nil + return storedLastCheck{}, nil } var ts string if err := json.Unmarshal(raw, &ts); err != nil { - return time.Time{}, fmt.Errorf("unmarshal lastCheck: %w", err) + return storedLastCheck{}, fmt.Errorf("unmarshal lastCheck: %w", err) } // RFC3339Nano also accepts fraction-less RFC3339 strings, so this // single parse covers values stored before the Nano switch too. t, err := time.Parse(time.RFC3339Nano, ts) if err != nil { - return time.Time{}, fmt.Errorf("parse lastCheck: %w", err) + return storedLastCheck{}, fmt.Errorf("parse lastCheck: %w", err) } // lastCheck lives in an issue entity property writable by anyone with @@ -222,17 +257,17 @@ func (p *Poller) readLastCheck(ctx context.Context, issueKey string) (time.Time, // old privileged slash commands under their authors' roles. Floor // it at now-window so a rewind can replay at most one window, the // same bound a genuine first poll already permits. + lc := storedLastCheck{value: t, stored: t, raw: ts} now := time.Now() const clockSkew = 2 * time.Minute if t.After(now.Add(clockSkew)) { - log.Printf("WARNING: lastCheck for %s is in the future (%q); treating as unset", issueKey, ts) - return time.Time{}, nil + lc.value, lc.clamp = time.Time{}, clampFuture + return lc, nil } if floor := now.Add(-p.opts.FirstPollBackfillWindow); t.Before(floor) { - log.Printf("WARNING: lastCheck for %s (%q) predates the backfill window; clamping to %s", issueKey, ts, floor.UTC().Format(time.RFC3339)) - return floor, nil + lc.value, lc.clamp = floor, clampFloor } - return t, nil + return lc, nil } // advanceLastCheck updates the lastCheck timestamp for an issue. diff --git a/internal/jirapoll/nomatch.go b/internal/jirapoll/nomatch.go index 845250f042..4f9adcc9bf 100644 --- a/internal/jirapoll/nomatch.go +++ b/internal/jirapoll/nomatch.go @@ -66,8 +66,8 @@ func looksLikeRequest(ne *normevent.Event) bool { // nothing was dispatched (#9503). It names each unmatched event (bounded by // maxNoMatchEvents), the agents the matcher considered, and what to check. // It writes nothing when the cycle dispatched work, when no event was -// evaluated (the selected issues had no new activity), or when the matcher -// drops every event on purpose. +// evaluated (the selected issues changed, but by nothing the poller reads +// as an event), or when the matcher drops every event on purpose. func (p *Poller) warnNoMatch(selected int) { if selected == 0 || len(p.dispatches) > 0 || len(p.unmatched) == 0 { return diff --git a/internal/jirapoll/nomatch_test.go b/internal/jirapoll/nomatch_test.go index fefc2494f3..bb391b23ac 100644 --- a/internal/jirapoll/nomatch_test.go +++ b/internal/jirapoll/nomatch_test.go @@ -159,11 +159,12 @@ func TestRun_NoMatchWarningSkipped(t *testing.T) { t.Run("no events on the selected issue", func(t *testing.T) { out := captureAnnotations(t) captureLog(t) - // lastCheck is newer than all of the issue's activity, so the - // cycle selects the issue but evaluates no event. + // The issue changed a minute after its lastCheck, so the activity + // filter keeps it and the cycle selects it, but it has no comment + // or label change to evaluate. mc := noMatchClient("/fs-code") mc.comments = map[string][]jira.Comment{} - setLastCheck(mc, "PROJ-123", "acme", "platform", time.Now().Truncate(time.Second)) + setLastCheck(mc, "PROJ-123", "acme", "platform", time.Now().Truncate(time.Second).Add(-time.Minute)) p := newTestPoller(mc, &reportingMatcher{}, Options{ TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", @@ -173,6 +174,9 @@ func TestRun_NoMatchWarningSkipped(t *testing.T) { if err := p.Run(context.Background()); err != nil { t.Fatalf("Run() error: %v", err) } + if c := mc.listCommentsCalls["PROJ-123"]; c != 1 { + t.Errorf("PROJ-123 looked at %d times, want 1", c) + } if out.Len() != 0 { t.Errorf("expected no annotation, got %q", out.String()) } diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 32c2b70f53..6d165769fc 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -141,14 +141,16 @@ func (p *Poller) Run(ctx context.Context) error { return fmt.Errorf("search candidates: %w", err) } - // Step 2: Filter locked issues, clean up stale locks. - unlocked, err := p.filterLocked(ctx, candidates) + // Step 2: Filter locked issues, clean up stale locks, and drop the + // issues with nothing new since their lastCheck (ADR 0160), so an + // already-handled issue does not take a slot from a fresh request. + active, unlocked, err := p.filterLocked(ctx, candidates) if err != nil { return fmt.Errorf("filter locked: %w", err) } - // Step 3: Randomly select min(N, len(unlocked)) candidates. - selected := selectRandom(unlocked, p.opts.N) + // Step 3: Randomly select min(N, len(active)) candidates. + selected := selectRandom(active, p.opts.N) // The project role rosters (GET /project/{key}/role, which Jira Cloud // serves only with the Administer Projects permission) are not loaded @@ -293,8 +295,8 @@ func (p *Poller) Run(ctx context.Context) error { } } - log.Printf("poll complete: %d candidates, %d unlocked, %d selected, %d dispatches", - len(candidates), len(unlocked), len(selected), len(p.dispatches)) + log.Printf("poll complete: %d candidates, %d unlocked, %d active, %d selected, %d dispatches", + len(candidates), unlocked, len(active), len(selected), len(p.dispatches)) p.warnNoMatch(len(selected)) if dispatchErrors > 0 { return fmt.Errorf("failed to dispatch records for %d issue(s); their lastCheck was not advanced, so they are retried next cycle: %w", dispatchErrors, firstDispatchErr) @@ -484,14 +486,18 @@ func uniqueIssues(issues []jira.Issue) []jira.Issue { return unique } -// filterLocked removes locked issues and cleans up stale locks. If every -// candidate is dropped by a failing lock-property read or a failing -// stale-lock release (e.g. broken auth, or read-only credentials that -// cannot write entity properties), it returns an error instead of silently -// reporting zero unlocked issues, which would otherwise be -// indistinguishable from a genuinely quiet Jira project. -func (p *Poller) filterLocked(ctx context.Context, issues []jira.Issue) ([]jira.Issue, error) { - var unlocked []jira.Issue +// filterLocked removes locked issues, cleans up stale locks, and keeps +// only the unlocked issues with new activity (see hasNewActivity). It +// returns those, with the number of unlocked issues. If every candidate is +// dropped by a failing lock-property read or a failing stale-lock release +// (e.g. broken auth, or read-only credentials that cannot write entity +// properties), it returns an error instead of silently reporting zero +// unlocked issues, which would otherwise be indistinguishable from a +// genuinely quiet Jira project. Issues with nothing new are not errors. +func (p *Poller) filterLocked(ctx context.Context, issues []jira.Issue) ([]jira.Issue, int, error) { + var active []jira.Issue + var unlocked int + var clamped clampReport var readErrors, releaseErrors int for _, issue := range issues { lock, err := p.readLock(ctx, issue.Key) @@ -512,12 +518,95 @@ func (p *Poller) filterLocked(ctx context.Context, issues []jira.Issue) ([]jira. continue } } - unlocked = append(unlocked, issue) + unlocked++ + if p.hasNewActivity(ctx, issue, &clamped) { + active = append(active, issue) + } } if len(issues) > 0 && readErrors+releaseErrors == len(issues) { - return nil, fmt.Errorf("all %d candidates dropped by lock errors (%d reads, %d stale-lock releases failed)", len(issues), readErrors, releaseErrors) + return nil, 0, fmt.Errorf("all %d candidates dropped by lock errors (%d reads, %d stale-lock releases failed)", len(issues), readErrors, releaseErrors) + } + clamped.log() + return active, unlocked, nil +} + +// hasNewActivity reports whether issue has activity after its lastCheck: +// its updated value from the search row is after its lastCheck, clamped +// exactly as processIssue's read clamps it (ADR 0160, Decision item 1). +// So a lastCheck older than the backfill window, clamped to the window's +// start, leaves the issue idle unless updated is inside the window. ADR +// 0160's Option B and Consequences say a floored lastCheck makes the issue +// active; Decision item 1 governs here, and #9956 tracks the correction. +// It fails open: an issue whose lastCheck cannot be read or parsed, has no +// usable lastCheck, or has no usable updated value is active, so neither a +// broken read nor an editor writing garbage can hide an issue. A read +// error is not reported here; processIssue reports it if the issue is +// picked. A clamped lastCheck is added to clamped instead of logged, so a +// quiet project logs one line per cycle rather than one per idle issue. +func (p *Poller) hasNewActivity(ctx context.Context, issue jira.Issue, clamped *clampReport) bool { + lc, err := p.loadLastCheck(ctx, issue.Key) + if err != nil { + return true + } + updated, updatedErr := parseJiraTimestamp(issue.Fields.Updated) + active := lc.value.IsZero() || updatedErr != nil || updated.After(lc.value) + switch lc.clamp { + case clampFuture: + clamped.future = append(clamped.future, issue.Key) + case clampFloor: + // Idle with activity after the stored value: that activity is + // itself older than the backfill window, so it is not replayed. + // Jira stamps updated a little after the newest entry, and a + // lastCheck saved before ADR 0160 sits at that entry, so a gap + // within gapTolerance is not reported. + if !active && updated.Sub(lc.stored) > gapTolerance { + clamped.gap = append(clamped.gap, issue.Key) + } else { + clamped.old = append(clamped.old, issue.Key) + } + } + return active +} + +// gapTolerance is how far updated may be after a lastCheck older than +// the backfill window before the activity filter reports that activity +// may have been missed. It covers the offset between the newest entry and +// the updated value Jira stamps for it. +const gapTolerance = time.Second + +// clampReport collects the candidates whose lastCheck the activity filter +// clamped in one cycle. +type clampReport struct { + gap []string // stored before the window, activity after it (beyond gapTolerance) but also before the window + old []string // stored before the window, nothing lost + future []string // stored more than two minutes ahead of now, treated as unset +} + +// log writes one line for the cycle when any lastCheck was clamped. The +// line is a WARNING, and carries the phrase the guide tells operators to +// grep for after an outage, only when activity may have been missed in +// the gap: a lastCheck older than the window is the normal state of an +// issue last handled more than a window ago. Issue keys come from the +// search; stored values are attacker-writable and are not printed. +func (r clampReport) log() { + var parts []string + if len(r.gap) > 0 { + parts = append(parts, "lastCheck predates the backfill window and activity after it may have been missed, because that activity is older than the window too: "+strings.Join(r.gap, ", ")) + } + if len(r.old) > 0 { + parts = append(parts, "lastCheck older than the backfill window, clamped to its start: "+strings.Join(r.old, ", ")) + } + if len(r.future) > 0 { + parts = append(parts, "lastCheck in the future, treated as unset: "+strings.Join(r.future, ", ")) + } + if len(parts) == 0 { + return + } + prefix := "activity filter: " + if len(r.gap) > 0 { + prefix = "WARNING: " + prefix } - return unlocked, nil + log.Print(prefix + strings.Join(parts, "; ")) } // selectRandom randomly selects min(n, len(items)) items. diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go new file mode 100644 index 0000000000..b7e3cdffb7 --- /dev/null +++ b/internal/jirapoll/poller_idle_test.go @@ -0,0 +1,613 @@ +package jirapoll + +import ( + "context" + "encoding/json" + "fmt" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/fullsend-ai/fullsend/internal/forge/jira" +) + +// Tests for ADR 0160: the poller skips candidates with nothing new since +// their lastCheck before the random pick, and a look advances lastCheck to +// at least the issue's updated value. + +// idleTestIssue is a search row for key with the given created and updated +// times. An empty updated time leaves the field empty. +func idleTestIssue(n int, created, updated time.Time) jira.Issue { + issue := jira.Issue{ + ID: fmt.Sprintf("%d", 10000+n), + Key: fmt.Sprintf("PROJ-%d", n), + Fields: jira.IssueFields{ + Labels: []string{}, + Reporter: jira.User{AccountID: "reporter-id"}, + Created: created.Format(jiraTimeLayout), + }, + } + if !updated.IsZero() { + issue.Fields.Updated = updated.Format(jiraTimeLayout) + } + return issue +} + +// addTriageComment adds a /fs-triage comment at t from a Developers member. +func addTriageComment(mc *mockClient, key, id string, t time.Time) { + mc.roleMembership = map[string]string{"dev-account": "Developers"} + mc.comments[key] = append(mc.comments[key], jira.Comment{ + ID: id, + Body: "/fs-triage", + Created: t.Format(jiraTimeLayout), + Author: jira.User{AccountID: "dev-account", AccountType: "atlassian"}, + }) +} + +func idleTestPoller(mc *mockClient, t *testing.T) *Poller { + return newTestPoller(mc, &stubMatcher{agents: []string{"triage"}}, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + }) +} + +// storedLastCheckAt returns PROJ-n's stored lastCheck, zero if unset. +func storedLastCheckAt(t *testing.T, mc *mockClient, key string) time.Time { + t.Helper() + raw, ok := mc.properties[key][lastCheckPropertyKey("acme", "platform")] + if !ok { + return time.Time{} + } + var ts string + if err := json.Unmarshal(raw, &ts); err != nil { + t.Fatalf("stored lastCheck for %s: %v", key, err) + } + got, err := time.Parse(time.RFC3339Nano, ts) + if err != nil { + t.Fatalf("stored lastCheck for %s: %v", key, err) + } + return got +} + +func dispatchedKeys(p *Poller) []string { + var keys []string + for _, d := range p.dispatches { + keys = append(keys, d.StatusNumber) + } + return keys +} + +// An idle candidate is dropped before the pick and costs no lock write, no +// listing and no lastCheck write; the cycle line carries the active count. +func TestRunSkipsIdleCandidates(t *testing.T) { + logs := captureLog(t) + now := time.Now().Truncate(time.Second) + mc := newMockClient() + for n := 1; n <= 10; n++ { + key := fmt.Sprintf("PROJ-%d", n) + setLastCheck(mc, key, "acme", "platform", now.Add(-30*time.Minute)) + if n <= 3 { + mc.searchResult = append(mc.searchResult, idleTestIssue(n, now.Add(-48*time.Hour), now.Add(-time.Minute))) + addTriageComment(mc, key, fmt.Sprintf("%d", 500+n), now.Add(-5*time.Minute)) + continue + } + // Idle: updated at or before lastCheck. An old comment is listed + // if the issue is looked at. + mc.searchResult = append(mc.searchResult, idleTestIssue(n, now.Add(-48*time.Hour), now.Add(-30*time.Minute-time.Duration(n)*time.Second))) + addTriageComment(mc, key, fmt.Sprintf("%d", 500+n), now.Add(-40*time.Minute)) + } + // One idle issue's updated equals its lastCheck exactly. + mc.searchResult[3].Fields.Updated = now.Add(-30 * time.Minute).Format(jiraTimeLayout) + + p := idleTestPoller(mc, t) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + + if got := dispatchedKeys(p); !sameSet(got, []string{"10001", "10002", "10003"}) { + t.Errorf("dispatched for %v, want the three active issues", got) + } + for n := 4; n <= 10; n++ { + key := fmt.Sprintf("PROJ-%d", n) + if c := mc.listCommentsCalls[key] + mc.listChangelogCalls[key] + mc.propertySetCalls[key] + mc.propertyDeleteCalls[key]; c != 0 { + t.Errorf("idle %s: comments %d, changelog %d, property writes %d, deletes %d; want all zero", + key, mc.listCommentsCalls[key], mc.listChangelogCalls[key], mc.propertySetCalls[key], mc.propertyDeleteCalls[key]) + } + } + if want := "poll complete: 10 candidates, 10 unlocked, 3 active, 3 selected, 3 dispatches"; !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs.String()) + } +} + +func sameSet(a, b []string) bool { + if len(a) != len(b) { + return false + } + seen := make(map[string]int) + for _, s := range a { + seen[s]++ + } + for _, s := range b { + seen[s]-- + } + for _, v := range seen { + if v != 0 { + return false + } + } + return true +} + +// A candidate that holds a live lock is dropped before its lastCheck is +// read. +func TestFilterLockedDoesNotReadLockedLastCheck(t *testing.T) { + now := time.Now().Truncate(time.Second) + mc := newMockClient() + p := idleTestPoller(mc, t) + locked := idleTestIssue(1, now.Add(-48*time.Hour), now.Add(-time.Minute)) + free := idleTestIssue(2, now.Add(-48*time.Hour), now.Add(-time.Minute)) + if err := mc.SetEntityProperty(context.Background(), locked.Key, p.lockKey(), LockValue{ID: "other-cycle", TS: now.UTC().Format(time.RFC3339), Phase: "pending"}); err != nil { + t.Fatal(err) + } + setLastCheck(mc, locked.Key, "acme", "platform", now.Add(-30*time.Minute)) + setLastCheck(mc, free.Key, "acme", "platform", now.Add(-30*time.Minute)) + + var reads []string + mc.getPropertyHook = func(issueKey, propKey string) { reads = append(reads, issueKey+" "+propKey) } + + active, unlocked, err := p.filterLocked(context.Background(), []jira.Issue{locked, free}) + if err != nil { + t.Fatalf("filterLocked() error: %v", err) + } + if unlocked != 1 || len(active) != 1 || active[0].Key != free.Key { + t.Fatalf("filterLocked() = %d active %+v, %d unlocked; want only %s", len(active), active, unlocked, free.Key) + } + for _, r := range reads { + if r == locked.Key+" "+p.lastCheckKey() { + t.Errorf("read the lastCheck of the locked candidate %s", locked.Key) + } + } + if !slices.Contains(reads, free.Key+" "+p.lastCheckKey()) { + t.Errorf("did not read the lastCheck of %s; reads: %v", free.Key, reads) + } +} + +// Clamped lastCheck values are reported in one line per cycle, not one +// WARNING per idle issue. The line is an alert only when an issue's +// activity after its lastCheck is itself older than the backfill window. +func TestRunLogsOneClampLinePerCycle(t *testing.T) { + now := time.Now().Truncate(time.Second) + seed := func(mc *mockClient) { + for n := 1; n <= 2; n++ { + mc.searchResult = append(mc.searchResult, idleTestIssue(n, now.Add(-100*time.Hour), now.Add(-73*time.Hour))) + setLastCheck(mc, fmt.Sprintf("PROJ-%d", n), "acme", "platform", now.Add(-72*time.Hour)) + } + mc.searchResult = append(mc.searchResult, idleTestIssue(3, now.Add(-100*time.Hour), now.Add(-time.Hour))) + setLastCheck(mc, "PROJ-3", "acme", "platform", now.Add(48*time.Hour)) + } + markerLines := func(logs string) []string { + var out []string + for _, line := range strings.Split(logs, "\n") { + if strings.Contains(line, "activity filter:") { + out = append(out, line) + } + } + return out + } + + t.Run("no activity lost", func(t *testing.T) { + logs := captureLog(t) + mc := newMockClient() + seed(mc) + // Active although its lastCheck predates the window: it is about + // to be looked at, so nothing is lost and the line is no alert. + mc.searchResult = append(mc.searchResult, idleTestIssue(5, now.Add(-100*time.Hour), now.Add(-time.Hour))) + setLastCheck(mc, "PROJ-5", "acme", "platform", time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)) + // Idle, with updated a few ms after a lastCheck older than the + // window: the offset Jira stamps after the newest entry, which a + // lastCheck saved before ADR 0160 sits below. Nothing was missed. + mc.searchResult = append(mc.searchResult, idleTestIssue(6, now.Add(-100*time.Hour), now.Add(-50*time.Hour+5*time.Millisecond))) + setLastCheck(mc, "PROJ-6", "acme", "platform", now.Add(-50*time.Hour)) + // Idle, with updated exactly 1 s after such a lastCheck: the edge of + // gapTolerance, which still counts as nothing missed. + mc.searchResult = append(mc.searchResult, idleTestIssue(8, now.Add(-100*time.Hour), now.Add(-50*time.Hour+time.Second))) + setLastCheck(mc, "PROJ-8", "acme", "platform", now.Add(-50*time.Hour)) + if err := idleTestPoller(mc, t).Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + lines := markerLines(logs.String()) + if len(lines) != 1 { + t.Fatalf("got %d activity filter lines, want 1:\n%s", len(lines), logs.String()) + } + for _, key := range []string{"PROJ-1", "PROJ-2", "PROJ-3", "PROJ-5", "PROJ-6", "PROJ-8"} { + if !strings.Contains(lines[0], key) { + t.Errorf("activity filter line lacks %s: %s", key, lines[0]) + } + } + if strings.Contains(lines[0], "WARNING:") || strings.Contains(lines[0], "predates the backfill window") { + t.Errorf("no activity was lost, but the activity filter line is an alert: %s", lines[0]) + } + // The only backfill alert is the unchanged per-issue WARNING from + // the look at the active PROJ-5. + if c, own := strings.Count(logs.String(), "predates the backfill window"), strings.Count(logs.String(), `lastCheck for PROJ-5 ("2020-01-01T00:00:00Z") predates the backfill window`); c != 1 || own != 1 { + t.Errorf("want exactly one backfill alert, the per-issue line for PROJ-5; got %d:\n%s", c, logs.String()) + } + for _, key := range []string{"PROJ-1", "PROJ-2"} { + if strings.Contains(logs.String(), "lastCheck for "+key) { + t.Errorf("idle %s logged a per-issue lastCheck WARNING:\n%s", key, logs.String()) + } + } + if c := strings.Count(logs.String(), "lastCheck for PROJ-3 is in the future"); c != 1 { + t.Errorf("per-issue future WARNING for the picked PROJ-3 logged %d times, want 1", c) + } + }) + + t.Run("activity lost in the gap", func(t *testing.T) { + logs := captureLog(t) + mc := newMockClient() + seed(mc) + mc.searchResult = append(mc.searchResult, idleTestIssue(4, now.Add(-100*time.Hour), now.Add(-30*time.Hour))) + setLastCheck(mc, "PROJ-4", "acme", "platform", now.Add(-40*time.Hour)) + // Just past the 1 s tolerance. + mc.searchResult = append(mc.searchResult, idleTestIssue(7, now.Add(-100*time.Hour), now.Add(-50*time.Hour+2*time.Second))) + setLastCheck(mc, "PROJ-7", "acme", "platform", now.Add(-50*time.Hour)) + if err := idleTestPoller(mc, t).Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + lines := markerLines(logs.String()) + if len(lines) != 1 { + t.Fatalf("got %d activity filter lines, want 1:\n%s", len(lines), logs.String()) + } + line := lines[0] + if !strings.Contains(line, "WARNING: activity filter:") || !strings.Contains(line, "predates the backfill window") { + t.Errorf("activity filter line is not an alert: %s", line) + } + first := strings.Index(line, "PROJ-4") + for _, key := range []string{"PROJ-1", "PROJ-2", "PROJ-3"} { + if i := strings.Index(line, key); i < 0 || first < 0 || i < first { + t.Errorf("want PROJ-4 named before %s: %s", key, line) + } + } + if i := strings.Index(line, "PROJ-7"); i < 0 || i > strings.Index(line, "PROJ-1") { + t.Errorf("want PROJ-7 in the alert group, before PROJ-1: %s", line) + } + if strings.Contains(logs.String(), "lastCheck for PROJ-4") { + t.Errorf("idle PROJ-4 logged a per-issue WARNING:\n%s", logs.String()) + } + }) +} + +// A change inside detectChanges' 10-second margin is handed off, stays +// active (lastCheck is held below it) and is handed off again next cycle: +// today's accepted duplicate, not a loss. +func TestRunInMarginChangeStaysActive(t *testing.T) { + now := time.Now().Truncate(time.Second) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, now.Add(-48*time.Hour), now.Add(-2*time.Second))} + setLastCheck(mc, "PROJ-1", "acme", "platform", now.Add(-20*time.Minute)) + addTriageComment(mc, "PROJ-1", "501", now.Add(-2*time.Second)) + // The comment is 2 s before now, inside detectChanges' 10 s safety + // margin, so cycle 1 must start within about 8 s of now for the + // checkpoint to land below it. The in-memory mock needs milliseconds. + + p := idleTestPoller(mc, t) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("cycle 1: %v", err) + } + if len(p.dispatches) != 1 { + t.Fatalf("cycle 1 dispatched %d, want 1", len(p.dispatches)) + } + if lc := storedLastCheckAt(t, mc, "PROJ-1"); !lc.Before(now.Add(-2 * time.Second)) { + t.Errorf("lastCheck %v not below the in-margin comment", lc) + } + + p = idleTestPoller(mc, t) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("cycle 2: %v", err) + } + if len(p.dispatches) != 1 { + t.Errorf("cycle 2 dispatched %d, want the same comment again", len(p.dispatches)) + } +} + +// A first look at an issue whose activity is all older than the backfill +// window hands off nothing, saves a lastCheck, and the next cycle skips it. +func TestRunFirstLookOldActivityThenIdle(t *testing.T) { + old := time.Now().Add(-48 * time.Hour).Truncate(time.Second) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, old, old)} + addTriageComment(mc, "PROJ-1", "501", old) + + p := idleTestPoller(mc, t) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("cycle 1: %v", err) + } + if len(p.dispatches) != 0 { + t.Errorf("cycle 1 dispatched %d, want 0", len(p.dispatches)) + } + if storedLastCheckAt(t, mc, "PROJ-1").IsZero() { + t.Fatal("cycle 1 saved no lastCheck") + } + + before := mc.listCommentsCalls["PROJ-1"] + if err := idleTestPoller(mc, t).Run(context.Background()); err != nil { + t.Fatalf("cycle 2: %v", err) + } + if mc.listCommentsCalls["PROJ-1"] != before { + t.Error("cycle 2 looked at an issue with nothing new") + } +} + +// A garbage lastCheck keeps its issue active (an editor must not be able to +// hide an issue by writing garbage). Alone in the active set it fails every +// cycle at the all-failed guard, which is unchanged. +func TestRunGarbageLastCheckAloneFailsCycle(t *testing.T) { + now := time.Now().Truncate(time.Second) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, now.Add(-48*time.Hour), now.Add(-time.Hour))} + mc.properties["PROJ-1"] = map[string]json.RawMessage{lastCheckPropertyKey("acme", "platform"): json.RawMessage(`"not-a-time"`)} + for n := 2; n <= 4; n++ { + mc.searchResult = append(mc.searchResult, idleTestIssue(n, now.Add(-48*time.Hour), now.Add(-time.Hour))) + setLastCheck(mc, fmt.Sprintf("PROJ-%d", n), "acme", "platform", now.Add(-time.Hour)) + } + + p := idleTestPoller(mc, t) + err := p.Run(context.Background()) + if err == nil || !strings.Contains(err.Error(), "all 1 selected issues failed to process") { + t.Fatalf("Run() error = %v, want the all-failed guard for the one garbage issue", err) + } + if len(p.dispatches) != 0 { + t.Errorf("dispatched %d, want 0", len(p.dispatches)) + } +} + +// Every row of the activity filter's decision table (ADR 0160, Decision +// item 1): only an issue whose usable lastCheck is at or after its updated +// value is dropped; every error and unset case keeps the issue. +func TestFilterLockedActivityDecision(t *testing.T) { + now := time.Now().Truncate(time.Second) + key := lastCheckPropertyKey("acme", "platform") + stamp := func(t time.Time) json.RawMessage { + raw, _ := json.Marshal(t.UTC().Format(time.RFC3339Nano)) + return raw + } + elsewhere := time.FixedZone("UTC-5", -5*3600) + cases := []struct { + name string + stored json.RawMessage // nil: no property + readErr bool + updated string + active bool + }{ + {name: "read fails", readErr: true, updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: true}, + {name: "not JSON", stored: json.RawMessage(`not json`), updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: true}, + {name: "JSON but not a time", stored: json.RawMessage(`"yesterday"`), updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: true}, + {name: "JSON number", stored: json.RawMessage(`42`), updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: true}, + {name: "missing", updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: true}, + {name: "empty", stored: json.RawMessage{}, updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: true}, + {name: "missing, updated empty", updated: "", active: true}, + {name: "48 h ahead", stored: stamp(now.Add(48 * time.Hour)), updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: true}, + {name: "1 min ahead", stored: stamp(now.Add(time.Minute)), updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: false}, + {name: "set, updated empty", stored: stamp(now.Add(-time.Hour)), updated: "", active: true}, + {name: "set, updated unparseable", stored: stamp(now.Add(-time.Hour)), updated: "last tuesday", active: true}, + {name: "set, updated after", stored: stamp(now.Add(-time.Hour)), updated: now.Add(-time.Minute).Format(jiraTimeLayout), active: true}, + {name: "set, updated equal in another format", stored: stamp(now.Add(-time.Hour)), updated: now.Add(-time.Hour).In(elsewhere).Format(jiraTimeLayout), active: false}, + {name: "set, updated before", stored: stamp(now.Add(-time.Hour)), updated: now.Add(-2 * time.Hour).Format(jiraTimeLayout), active: false}, + {name: "2020, updated 1 h ago", stored: stamp(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)), updated: now.Add(-time.Hour).Format(jiraTimeLayout), active: true}, + {name: "2020, updated 3 days ago", stored: stamp(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)), updated: now.Add(-72 * time.Hour).Format(jiraTimeLayout), active: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mc := newMockClient() + if tc.readErr { + mc.propertyGetErr[key] = fmt.Errorf("503 service unavailable") + } + if tc.stored != nil { + mc.properties["PROJ-1"] = map[string]json.RawMessage{key: tc.stored} + } + issue := jira.Issue{ID: "10001", Key: "PROJ-1", Fields: jira.IssueFields{Updated: tc.updated}} + active, unlocked, err := idleTestPoller(mc, t).filterLocked(context.Background(), []jira.Issue{issue}) + if err != nil { + t.Fatalf("filterLocked() error: %v", err) + } + if unlocked != 1 { + t.Errorf("unlocked = %d, want 1", unlocked) + } + if got := len(active) == 1; got != tc.active { + t.Errorf("active = %v, want %v", got, tc.active) + } + }) + } +} + +// A GitLab-target poller compares updated with its own lastCheck key, not +// the GitHub-style one. +func TestFilterLockedGitLabTargetReadsItsOwnKey(t *testing.T) { + now := time.Now().Truncate(time.Second) + opts := Options{ + TargetRepo: "group/project", + TargetForge: TargetForgeGitLab, + GitLabURL: "https://gitlab.example.com", + JiraBaseURL: "https://acme.atlassian.net", + JiraProjects: []string{"PROJ"}, + } + issue := idleTestIssue(1, now.Add(-48*time.Hour), now.Add(-time.Hour)) + + mc := newMockClient() + p := newTestPoller(mc, nil, opts) + if err := p.advanceLastCheck(context.Background(), issue.Key, now.Add(-time.Hour)); err != nil { + t.Fatal(err) + } + if active, _, err := p.filterLocked(context.Background(), []jira.Issue{issue}); err != nil || len(active) != 0 { + t.Errorf("lastCheck equal to updated under the GitLab key: active %v, err %v; want idle", active, err) + } + + mc = newMockClient() + setLastCheck(mc, issue.Key, "group", "project", now.Add(-time.Hour)) + if active, _, err := newTestPoller(mc, nil, opts).filterLocked(context.Background(), []jira.Issue{issue}); err != nil || len(active) != 1 { + t.Errorf("lastCheck only under the GitHub-style key: active %v, err %v; want active", active, err) + } +} + +// runCycle runs one cycle on mc and returns the poller. +func runCycle(t *testing.T, mc *mockClient, name string) *Poller { + t.Helper() + p := idleTestPoller(mc, t) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("%s: Run() error: %v", name, err) + } + return p +} + +// After a look, lastCheck reaches the issue's updated value even when that +// is after the newest comment, so the next cycle skips the issue. +func TestRunLastCheckReachesUpdated(t *testing.T) { + now := time.Now().Truncate(time.Second) + updated := now.Add(-time.Minute) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, now.Add(-48*time.Hour), updated)} + setLastCheck(mc, "PROJ-1", "acme", "platform", now.Add(-20*time.Minute)) + addTriageComment(mc, "PROJ-1", "501", now.Add(-10*time.Minute)) + + if p := runCycle(t, mc, "cycle 1"); len(p.dispatches) != 1 { + t.Fatalf("cycle 1 dispatched %d, want 1", len(p.dispatches)) + } + if lc := storedLastCheckAt(t, mc, "PROJ-1"); !lc.Equal(updated) { + t.Errorf("lastCheck after cycle 1 = %v, want updated %v", lc, updated) + } + listed := mc.listCommentsCalls["PROJ-1"] + if p := runCycle(t, mc, "cycle 2"); len(p.dispatches) != 0 { + t.Errorf("cycle 2 dispatched %d, want 0", len(p.dispatches)) + } + if mc.listCommentsCalls["PROJ-1"] != listed { + t.Error("cycle 2 listed comments of an issue with nothing new") + } +} + +// Jira can stamp updated after every comment and changelog entry. One look +// finds nothing, moves lastCheck to updated, and the issue goes quiet. +func TestRunUpdatedWithoutEntryLooksOnce(t *testing.T) { + now := time.Now().Truncate(time.Second) + updated := now.Add(-time.Minute) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, now.Add(-48*time.Hour), updated)} + setLastCheck(mc, "PROJ-1", "acme", "platform", now.Add(-20*time.Minute)) + addTriageComment(mc, "PROJ-1", "501", now.Add(-30*time.Minute)) + + if p := runCycle(t, mc, "cycle 1"); len(p.dispatches) != 0 { + t.Errorf("cycle 1 dispatched %d, want 0", len(p.dispatches)) + } + if mc.listCommentsCalls["PROJ-1"] != 1 { + t.Errorf("cycle 1 listed comments %d times, want 1", mc.listCommentsCalls["PROJ-1"]) + } + if lc := storedLastCheckAt(t, mc, "PROJ-1"); !lc.Equal(updated) { + t.Errorf("lastCheck after cycle 1 = %v, want updated %v", lc, updated) + } + runCycle(t, mc, "cycle 2") + if mc.listCommentsCalls["PROJ-1"] != 1 { + t.Error("cycle 2 looked at an issue with nothing new") + } +} + +// The search row can be older than the listings. The entry is handed off +// on the look that finds it; the row then catches up a few milliseconds +// past the entry, which costs one more look with no hand-off, and then the +// issue is idle. +func TestRunSearchRowOlderThanListing(t *testing.T) { + now := time.Now().Truncate(time.Second) + commentAt := now.Add(-5 * time.Minute) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, now.Add(-48*time.Hour), now.Add(-15*time.Minute))} + setLastCheck(mc, "PROJ-1", "acme", "platform", now.Add(-20*time.Minute)) + addTriageComment(mc, "PROJ-1", "501", commentAt) + + if p := runCycle(t, mc, "cycle 1"); len(p.dispatches) != 1 { + t.Fatalf("cycle 1 dispatched %d, want 1", len(p.dispatches)) + } + if lc := storedLastCheckAt(t, mc, "PROJ-1"); !lc.Equal(commentAt) { + t.Errorf("lastCheck after cycle 1 = %v, want the comment's time %v", lc, commentAt) + } + + mc.searchResult[0].Fields.Updated = commentAt.Add(3 * time.Millisecond).Format(jiraTimeLayout) + if p := runCycle(t, mc, "cycle 2"); len(p.dispatches) != 0 { + t.Errorf("cycle 2 dispatched %d, want 0", len(p.dispatches)) + } + if mc.listCommentsCalls["PROJ-1"] != 2 { + t.Errorf("comment listings after cycle 2 = %d, want 2", mc.listCommentsCalls["PROJ-1"]) + } + runCycle(t, mc, "cycle 3") + if mc.listCommentsCalls["PROJ-1"] != 2 { + t.Error("cycle 3 looked at an issue with nothing new") + } +} + +// A search row can lag a new comment (the search is eventually +// consistent). The filter then skips the issue, but the comment is not +// lost: it is handed off once the row catches up. +func TestRunStaleSearchRowDelaysButDoesNotLose(t *testing.T) { + now := time.Now().Truncate(time.Second) + lastCheck := now.Add(-20 * time.Minute) + commentAt := now.Add(-5 * time.Minute) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, now.Add(-48*time.Hour), lastCheck)} + setLastCheck(mc, "PROJ-1", "acme", "platform", lastCheck) + addTriageComment(mc, "PROJ-1", "501", commentAt) + + if p := runCycle(t, mc, "cycle 1"); len(p.dispatches) != 0 || mc.listCommentsCalls["PROJ-1"] != 0 { + t.Fatalf("cycle 1 on a stale row: dispatched %d, listed %d; want the issue skipped", len(p.dispatches), mc.listCommentsCalls["PROJ-1"]) + } + + mc.searchResult[0].Fields.Updated = commentAt.Add(3 * time.Millisecond).Format(jiraTimeLayout) + if p := runCycle(t, mc, "cycle 2"); len(p.dispatches) != 1 { + t.Errorf("cycle 2 after the row caught up dispatched %d, want the comment once", len(p.dispatches)) + } +} + +// detectChanges raises maxSeen to the search row's updated value when that +// is later, never lowers it, ignores an unparseable value, and still caps +// the result below fetch start. +func TestDetectChangesMaxSeenReachesUpdated(t *testing.T) { + now := time.Now().Truncate(time.Second) + lastCheck := now.Add(-time.Hour) + commentAt := now.Add(-10 * time.Minute) + cases := []struct { + name string + updated string + want time.Time // zero: capped below fetch start + }{ + {name: "after", updated: now.Add(-time.Minute).Format(jiraTimeLayout), want: now.Add(-time.Minute)}, + {name: "before", updated: now.Add(-20 * time.Minute).Format(jiraTimeLayout), want: commentAt}, + {name: "equal", updated: commentAt.Format(jiraTimeLayout), want: commentAt}, + {name: "unparseable", updated: "soon", want: commentAt}, + {name: "empty", updated: "", want: commentAt}, + {name: "inside the margin", updated: now.Add(time.Second).Format(jiraTimeLayout)}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + mc := newMockClient() + addTriageComment(mc, "PROJ-1", "501", commentAt) + p := idleTestPoller(mc, t) + issue := jira.Issue{ID: "10001", Key: "PROJ-1", Fields: jira.IssueFields{Created: now.Add(-48 * time.Hour).Format(jiraTimeLayout), Updated: tc.updated}} + res, err := p.detectChanges(context.Background(), issue, lastCheck) + if err != nil { + t.Fatalf("detectChanges() error: %v", err) + } + if tc.want.IsZero() { + // Raised past the comment to updated, then capped at + // fetch start minus the 10 s margin. This holds while the + // fetch starts within about 5 s of now. + if res.maxSeen.Before(now.Add(-10*time.Second)) || !res.maxSeen.Before(now.Add(-5*time.Second)) { + t.Errorf("maxSeen = %v, want raised to updated and capped 10 s below fetch start (now %v)", res.maxSeen, now) + } + return + } + if !res.maxSeen.Equal(tc.want) { + t.Errorf("maxSeen = %v, want %v", res.maxSeen, tc.want) + } + }) + } +} diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index b73b971eae..3e16ccc1fa 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -66,6 +66,14 @@ type mockClient struct { roleActorsCalls int // GetProjectRoleActors call count userGroupsCalls map[string]int // accountID -> GetUserGroups call count + // Per-issue call counts, so a test can show an issue cost nothing. + // Writes and deletes are counted because a lock is written and then + // deleted, which the end state cannot show. + listCommentsCalls map[string]int // issueKey -> ListComments calls + listChangelogCalls map[string]int // issueKey -> ListChangelog calls + propertySetCalls map[string]int // issueKey -> SetEntityProperty calls + propertyDeleteCalls map[string]int // issueKey -> DeleteEntityProperty calls + // getPropertyHook, if set, runs after each GetEntityProperty call // captures its return value, and before that value is returned. Used // to simulate a concurrent writer changing the stored property @@ -87,6 +95,11 @@ func newMockClient() *mockClient { statuses: make(map[string]jira.Status), statusErr: make(map[string]error), myselfUser: &jira.User{AccountID: "poller-service-account", AccountType: "atlassian", Active: true}, + + listCommentsCalls: make(map[string]int), + listChangelogCalls: make(map[string]int), + propertySetCalls: make(map[string]int), + propertyDeleteCalls: make(map[string]int), } } @@ -122,6 +135,9 @@ func (m *mockClient) GetIssue(_ context.Context, key string) (*jira.Issue, error } func (m *mockClient) ListComments(_ context.Context, key string) ([]jira.Comment, error) { + m.mu.Lock() + m.listCommentsCalls[key]++ + m.mu.Unlock() if err, ok := m.commentErr[key]; ok && err != nil { return nil, err } @@ -129,6 +145,9 @@ func (m *mockClient) ListComments(_ context.Context, key string) ([]jira.Comment } func (m *mockClient) ListChangelog(_ context.Context, key string) ([]jira.ChangelogEntry, error) { + m.mu.Lock() + m.listChangelogCalls[key]++ + m.mu.Unlock() if err, ok := m.changelogErr[key]; ok && err != nil { return nil, err } @@ -160,6 +179,7 @@ func (m *mockClient) GetEntityProperty(_ context.Context, issueKey, propKey stri func (m *mockClient) SetEntityProperty(_ context.Context, issueKey, propKey string, value any) error { m.mu.Lock() defer m.mu.Unlock() + m.propertySetCalls[issueKey]++ if err, ok := m.propertySetErr[propKey]; ok && err != nil { return err @@ -178,6 +198,7 @@ func (m *mockClient) SetEntityProperty(_ context.Context, issueKey, propKey stri func (m *mockClient) DeleteEntityProperty(_ context.Context, issueKey, propKey string) error { m.mu.Lock() defer m.mu.Unlock() + m.propertyDeleteCalls[issueKey]++ if props, ok := m.properties[issueKey]; ok { delete(props, propKey) @@ -1641,7 +1662,7 @@ func TestFilterLockedStaleCleanupPreservesConcurrentFreshLock(t *testing.T) { } } - if _, err := p.filterLocked(context.Background(), []jira.Issue{{Key: "PROJ-123"}}); err != nil { + if _, _, err := p.filterLocked(context.Background(), []jira.Issue{{Key: "PROJ-123"}}); err != nil { t.Fatalf("filterLocked() error: %v", err) } @@ -1671,12 +1692,12 @@ func TestFilterLockedErrorsWhenAllLockReadsFail(t *testing.T) { p := newTestPoller(mc, nil, Options{TargetRepo: "acme/platform"}) issues := []jira.Issue{{Key: "PROJ-1"}, {Key: "PROJ-2"}} - unlocked, err := p.filterLocked(context.Background(), issues) + active, unlocked, err := p.filterLocked(context.Background(), issues) if err == nil { t.Fatal("filterLocked() error = nil, want error when every lock read fails") } - if len(unlocked) != 0 { - t.Errorf("unlocked = %v, want empty", unlocked) + if len(active) != 0 || unlocked != 0 { + t.Errorf("active = %v, unlocked = %d, want none", active, unlocked) } } diff --git a/pkg/behaviourtest/drivers/jiramock/server.go b/pkg/behaviourtest/drivers/jiramock/server.go index 6d90fba09d..c438af3f34 100644 --- a/pkg/behaviourtest/drivers/jiramock/server.go +++ b/pkg/behaviourtest/drivers/jiramock/server.go @@ -30,8 +30,13 @@ type State struct { userGroups map[string][]string // accountID → group IDs, backing GET /user/groups } +// jiraTimeLayout is the timestamp format Jira Cloud serves. +const jiraTimeLayout = "2006-01-02T15:04:05.000-0700" + // AddIssue inserts an issue with the given key and labels. A synthetic -// numeric ID and timestamp are assigned automatically. An issue without +// numeric ID and creation time are assigned automatically, and updated +// starts equal to created; the activity helpers move it forward as Jira +// does, while entity property calls leave it alone. An issue without // labels is served with an empty list, as Jira Cloud was observed serving it // (checked 2026-11-01). func (s *State) AddIssue(key string, labels []string) { @@ -44,6 +49,7 @@ func (s *State) AddIssue(key string, labels []string) { s.nextID++ id := strconv.Itoa(s.nextID + 10000) + created := time.Now().Add(-1 * time.Hour).Format(jiraTimeLayout) s.issues[key] = &jira.Issue{ ID: id, @@ -61,8 +67,8 @@ func (s *State) AddIssue(key string, labels []string) { AccountType: "atlassian", Active: true, }, - Created: time.Now().Add(-1 * time.Hour).Format("2006-01-02T15:04:05.000-0700"), - Updated: time.Now().Format("2006-01-02T15:04:05.000-0700"), + Created: created, + Updated: created, }, } } @@ -102,7 +108,10 @@ func (s *State) AddCommentFromActorAt(issueKey, body, accountID, displayName str defer s.mu.Unlock() id := strconv.Itoa(len(s.comments[issueKey]) + 1) - now := at.Format("2006-01-02T15:04:05.000-0700") + now := at.Format(jiraTimeLayout) + if issue, ok := s.issues[issueKey]; ok { + touch(issue, at) + } s.comments[issueKey] = append(s.comments[issueKey], jira.Comment{ ID: id, @@ -192,7 +201,8 @@ func (s *State) AddLabelChangeAt(issueKey, label string, at time.Time) { toLabels := strings.Join(issue.Fields.Labels, " ") id := strconv.Itoa(len(s.changelog[issueKey]) + 1) - now := at.Format("2006-01-02T15:04:05.000-0700") + now := at.Format(jiraTimeLayout) + touch(issue, at) s.changelog[issueKey] = append(s.changelog[issueKey], jira.ChangelogEntry{ ID: id, @@ -213,6 +223,15 @@ func (s *State) AddLabelChangeAt(issueKey, label string, at time.Time) { }) } +// touch moves the issue's updated value forward to at, never back. The +// caller holds s.mu. +func touch(issue *jira.Issue, at time.Time) { + if cur, err := time.Parse(jiraTimeLayout, issue.Fields.Updated); err == nil && !at.After(cur) { + return + } + issue.Fields.Updated = at.Format(jiraTimeLayout) +} + // NewServer creates a mock Jira REST API server and returns the httptest // server and its backing state. The caller should defer srv.Close(). func NewServer() (*httptest.Server, *State) { @@ -440,7 +459,13 @@ func handleIssueRoute(w http.ResponseWriter, r *http.Request, s *State, parts [] func handleGetIssue(w http.ResponseWriter, s *State, key string) { s.mu.Lock() - issue, ok := s.issues[key] + var issue jira.Issue + stored, ok := s.issues[key] + if ok { + // Copy under the lock, as handleSearch does: the State helpers + // write the stored issue's fields. + issue = *stored + } s.mu.Unlock() if !ok { diff --git a/pkg/behaviourtest/drivers/jiramock/server_test.go b/pkg/behaviourtest/drivers/jiramock/server_test.go index 179a226325..5fb8c7298a 100644 --- a/pkg/behaviourtest/drivers/jiramock/server_test.go +++ b/pkg/behaviourtest/drivers/jiramock/server_test.go @@ -104,14 +104,14 @@ func TestTimestampedActivityHelpers(t *testing.T) { require.NoError(t, err) require.Len(t, comments, 1) assert.Equal(t, "dev-001", comments[0].Author.AccountID) - created, err := time.Parse("2006-01-02T15:04:05.000-0700", comments[0].Created) + created, err := time.Parse(jiraTimeLayout, comments[0].Created) require.NoError(t, err) assert.True(t, created.Equal(at), "comment created = %s, want %s", created, at) entries, err := client.ListChangelog(ctx, "PROJ-1") require.NoError(t, err) require.Len(t, entries, 1) - changed, err := time.Parse("2006-01-02T15:04:05.000-0700", entries[0].Created) + changed, err := time.Parse(jiraTimeLayout, entries[0].Created) require.NoError(t, err) assert.True(t, changed.Equal(at.Add(time.Minute)), "changelog created = %s", changed) } @@ -262,6 +262,43 @@ func TestConcurrentAccess(t *testing.T) { } } +// A GET of an issue runs alongside the helpers that write its fields +// (here updated, via comments) without a data race under -race. +func TestGetIssueConcurrentWithActivity(t *testing.T) { + t.Parallel() + srv, state := NewServer() + defer srv.Close() + + client, err := jira.New("test-token", jira.WithBaseURL(srv.URL)) + require.NoError(t, err) + ctx := context.Background() + state.AddIssue("PROJ-1", nil) + + // The writer runs until every GET has returned, so the two overlap. + stop := make(chan struct{}) + writerDone := make(chan struct{}) + go func() { + defer close(writerDone) + for { + select { + case <-stop: + return + default: + state.AddComment("PROJ-1", "comment") + time.Sleep(time.Millisecond) + } + } + }() + defer func() { + close(stop) + <-writerDone + }() + for range 50 { + _, err := client.GetIssue(ctx, "PROJ-1") + require.NoError(t, err) + } +} + // SetIssueLabels replaces the issue's label list without a changelog // entry, and Labels reads it back: the transport-bounds scenarios place a // large label state at issue creation this way instead of one @@ -294,3 +331,56 @@ func TestSetIssueLabels(t *testing.T) { require.Len(t, labels, 31) require.Equal(t, "ready-to-code", labels[len(labels)-1]) } + +// The served updated value follows the issue's activity forward, as Jira's +// does, and entity property writes leave it alone (ADR 0160 relies on +// both). +func TestUpdatedFollowsActivity(t *testing.T) { + t.Parallel() + srv, state := NewServer() + defer srv.Close() + + client, err := jira.New("test-token", jira.WithBaseURL(srv.URL)) + require.NoError(t, err) + ctx := context.Background() + + served := func() (created, updated time.Time) { + t.Helper() + issues, err := client.SearchIssues(ctx, "project = PROJ", 0) + require.NoError(t, err) + require.Len(t, issues, 1) + created, err = time.Parse(jiraTimeLayout, issues[0].Fields.Created) + require.NoError(t, err) + updated, err = time.Parse(jiraTimeLayout, issues[0].Fields.Updated) + require.NoError(t, err) + return created, updated + } + + state.AddIssue("PROJ-1", nil) + created, updated := served() + assert.True(t, updated.Equal(created), "a new issue's updated = %s, want its created %s", updated, created) + + t1 := time.Now().Add(-30 * time.Minute).Truncate(time.Millisecond) + t2 := t1.Add(5 * time.Minute) + t0 := t1.Add(-time.Minute) + + state.AddCommentFromActorAt("PROJ-1", "first", "dev-001", "Dev", t1) + _, updated = served() + assert.True(t, updated.Equal(t1), "after a comment, updated = %s, want %s", updated, t1) + + state.AddLabelChangeAt("PROJ-1", "ready-to-code", t2) + _, updated = served() + assert.True(t, updated.Equal(t2), "after a label change, updated = %s, want %s", updated, t2) + + state.AddCommentFromActorAt("PROJ-1", "older", "dev-001", "Dev", t0) + _, updated = served() + assert.True(t, updated.Equal(t2), "an older comment moved updated back to %s", updated) + + // A comment for an issue the mock does not hold is still accepted. + state.AddCommentFromActorAt("PROJ-404", "orphan", "dev-001", "Dev", time.Now()) + + require.NoError(t, client.SetEntityProperty(ctx, "PROJ-1", "fullsend.poll.o.r.lastCheck", time.Now().UTC().Format(time.RFC3339Nano))) + require.NoError(t, client.DeleteEntityProperty(ctx, "PROJ-1", "fullsend.poll.o.r.lastCheck")) + _, updated = served() + assert.True(t, updated.Equal(t2), "property calls moved updated to %s", updated) +}