diff --git a/docs/ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md b/docs/ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md index 1e007b8498..ac7848db3e 100644 --- a/docs/ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md +++ b/docs/ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md @@ -284,3 +284,20 @@ their own discovery and are unaffected. Forgejo has no Jira poll target. - Starvation beyond the top M stays documented and unmitigated: the filter neither widens nor narrows the window, and the clearance bound above applies only to candidates inside it. + +## Amendments + +### 2026-11-25: A checkpoint that is not a timestamp is treated as unset (#9766) + +Decision item 1 sends a checkpoint that cannot be parsed to processing, +where "the existing per-issue error path reports it as today". That path +fails the issue on every pick and never saves a new checkpoint, so the +issue is never processed again, and when it is the only active candidate +every quiet cycle ends in the all-failed error. The driver now treats a +stored value that is not a timestamp as unset, as it already treats one +dated in the future: the issue stays active, gets one first-poll look +bounded by the backfill window, and that look saves a valid checkpoint. +Processing logs a WARNING naming the issue without the stored value, and +the filter's one line per cycle names such candidates. A failed read is +still an error. Replay stays bounded by one backfill window, the same as +deleting or forward-dating the checkpoint today. diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 017c56cd76..2d2b94be62 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1715,7 +1715,7 @@ 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 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: +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, not a timestamp, 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. 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. @@ -1727,7 +1727,7 @@ The poller uses Jira entity properties for distributed lock coordination and che 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 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`. +> **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), one that is not a timestamp is ignored too (logged as `WARNING: lastCheck for is not a timestamp; treating as unset`, without the stored value), and in both cases the issue gets one look bounded by the backfill window, which saves a valid `lastCheck`; 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: diff --git a/internal/jirapoll/lock.go b/internal/jirapoll/lock.go index 9a855f7515..4b701226f9 100644 --- a/internal/jirapoll/lock.go +++ b/internal/jirapoll/lock.go @@ -194,6 +194,8 @@ func (p *Poller) readLastCheck(ctx context.Context, issueKey string) (time.Time, 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)) + case clampInvalid: + log.Printf("WARNING: lastCheck for %s is not a timestamp; treating as unset", issueKey) } return lc.value, nil } @@ -202,9 +204,10 @@ func (p *Poller) readLastCheck(ctx context.Context, issueKey string) (time.Time, 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 + clampNone lastCheckClamp = iota + clampFuture // stored beyond clock skew ahead; treated as unset + clampFloor // stored before the backfill window; floored to its start + clampInvalid // stored value is not a timestamp; treated as unset ) // storedLastCheck is a lastCheck as loadLastCheck read it. @@ -232,16 +235,22 @@ func (p *Poller) loadLastCheck(ctx context.Context, issueKey string) (storedLast return storedLastCheck{}, nil } + // A value that is not a timestamp is treated as unset, like a future + // one below: the issue gets one first-poll look bounded by the backfill + // window and the next checkpoint advance overwrites it. Returning an + // error instead would fail the issue on every pick and never save a + // valid value (#9766). raw stays empty so the attacker-writable value + // is never logged. var ts string if err := json.Unmarshal(raw, &ts); err != nil { - return storedLastCheck{}, fmt.Errorf("unmarshal lastCheck: %w", err) + return storedLastCheck{clamp: clampInvalid}, nil } // 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 storedLastCheck{}, fmt.Errorf("parse lastCheck: %w", err) + return storedLastCheck{clamp: clampInvalid}, nil } // lastCheck lives in an issue entity property writable by anyone with diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 6d165769fc..0fc9d35d4c 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -553,6 +553,8 @@ func (p *Poller) hasNewActivity(ctx context.Context, issue jira.Issue, clamped * switch lc.clamp { case clampFuture: clamped.future = append(clamped.future, issue.Key) + case clampInvalid: + clamped.invalid = append(clamped.invalid, 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. @@ -577,9 +579,10 @@ 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 + 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 + invalid []string // stored value not a timestamp, treated as unset } // log writes one line for the cycle when any lastCheck was clamped. The @@ -599,6 +602,9 @@ func (r clampReport) log() { if len(r.future) > 0 { parts = append(parts, "lastCheck in the future, treated as unset: "+strings.Join(r.future, ", ")) } + if len(r.invalid) > 0 { + parts = append(parts, "lastCheck not a timestamp, treated as unset: "+strings.Join(r.invalid, ", ")) + } if len(parts) == 0 { return } diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index b7e3cdffb7..d21eca132f 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -342,23 +342,74 @@ func TestRunFirstLookOldActivityThenIdle(t *testing.T) { } } -// 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) { +// A garbage lastCheck is treated as unset (#9766): the issue stays active +// (an editor must not be able to hide an issue by writing garbage), gets +// one first-poll look that saves a valid lastCheck, and is idle next cycle. +// Neither warning prints the stored value. The cases cover both ways a +// stored value can fail: JSON that is not a string, and a string that is +// not a timestamp. +func TestRunGarbageLastCheckTreatedAsUnset(t *testing.T) { + for _, tc := range []struct { + name string + stored string + }{ + {name: "a string that is not a time", stored: `"garbage-time"`}, + {name: "JSON that is not a string", stored: `{"garbage":1}`}, + {name: "not JSON", stored: `garbage, not JSON`}, + } { + t.Run(tc.name, func(t *testing.T) { + now := time.Now().Truncate(time.Second) + updated := now.Add(-time.Hour) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, now.Add(-48*time.Hour), updated)} + mc.properties["PROJ-1"] = map[string]json.RawMessage{lastCheckPropertyKey("acme", "platform"): json.RawMessage(tc.stored)} + for n := 2; n <= 4; n++ { + mc.searchResult = append(mc.searchResult, idleTestIssue(n, now.Add(-48*time.Hour), updated)) + setLastCheck(mc, fmt.Sprintf("PROJ-%d", n), "acme", "platform", updated) + } + + logs := captureLog(t) + if err := idleTestPoller(mc, t).Run(context.Background()); err != nil { + t.Fatalf("cycle 1: %v", err) + } + if lc := storedLastCheckAt(t, mc, "PROJ-1"); !lc.Equal(updated) { + t.Fatalf("lastCheck after cycle 1 = %v, want the issue's updated %v saved over the garbage", lc, updated) + } + for _, want := range []string{ + "lastCheck not a timestamp, treated as unset: PROJ-1", + "WARNING: lastCheck for PROJ-1 is not a timestamp; treating as unset", + } { + if !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + } + if strings.Contains(logs.String(), "garbage") { + t.Errorf("log prints the stored value:\n%s", logs) + } + + 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 cycle whose every selected issue fails ends in an error. Here the one +// active issue's lastCheck cannot be read. +func TestRunAllSelectedIssuesFailedFailsCycle(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)) - } + mc.propertyGetErr[lastCheckPropertyKey("acme", "platform")] = fmt.Errorf("503 service unavailable") 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) + t.Fatalf("Run() error = %v, want the all-failed guard", err) } if len(p.dispatches) != 0 { t.Errorf("dispatched %d, want 0", len(p.dispatches)) @@ -386,6 +437,7 @@ func TestFilterLockedActivityDecision(t *testing.T) { {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 but not a time, updated 3 days ago", stored: json.RawMessage(`"yesterday"`), updated: now.Add(-72 * 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},