From 527843f113cb5066be4947aa5fa2bf4d246b0b7c Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 25 Nov 2026 02:43:28 +0200 Subject: [PATCH 01/37] fix(jirapoll): treat an unparseable lastCheck as unset A lastCheck entity property that is not a timestamp made loadLastCheck return an error, so processIssue failed the issue on every pick and never saved a valid value. The activity filter keeps such an issue active, so when it was the only active candidate every quiet cycle ended in "all 1 selected issues failed to process". Treat a value that is not a JSON string holding an RFC 3339 timestamp as unset, as a future value already is. The issue gets one first-poll look bounded by the backfill window, which saves a valid lastCheck. Processing logs a WARNING naming the issue without the stored value, and the filter's per-cycle line names such candidates. A failed read is still an error. Amend ADR 0160 Decision item 1, which said the per-issue error path reports such a value, and update the Jira guide's security note. Fixes #9766 Signed-off-by: guy oron --- ...ts-only-on-candidates-with-new-activity.md | 17 ++++++++ docs/guides/user/jira-integration.md | 4 +- internal/jirapoll/lock.go | 19 ++++++--- internal/jirapoll/poller.go | 12 ++++-- internal/jirapoll/poller_idle_test.go | 39 ++++++++++++++----- 5 files changed, 71 insertions(+), 20 deletions(-) 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 8e2ba89d4c..7b4229da5e 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 @@ -277,3 +277,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 667bd45ed7..c37ae91fc3 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1435,14 +1435,14 @@ 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 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 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. 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 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 62231d5d0f..1e53e85212 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -480,6 +480,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. @@ -504,9 +506,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 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 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 @@ -526,6 +529,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 2d2f18d04b..4d27940e83 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -335,10 +335,11 @@ 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. +func TestRunGarbageLastCheckTreatedAsUnset(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))} @@ -348,13 +349,31 @@ func TestRunGarbageLastCheckAloneFailsCycle(t *testing.T) { 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) + logs := captureLog(t) + if err := idleTestPoller(mc, t).Run(context.Background()); err != nil { + t.Fatalf("cycle 1: %v", err) } - if len(p.dispatches) != 0 { - t.Errorf("dispatched %d, want 0", len(p.dispatches)) + if storedLastCheckAt(t, mc, "PROJ-1").IsZero() { + t.Fatal("cycle 1 saved no lastCheck over the garbage") + } + 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(), "not-a-time") { + 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") } } From e0d366320bc26f05c23d7873e697c83386f26e93 Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 25 Nov 2026 09:22:15 +0200 Subject: [PATCH 02/37] feat(jirapoll)!: remove the per-issue lock and check write access first Implements ADR 0085 Decision item 1. The managed GitHub workflow and the managed GitLab schedule run one poll cycle at a time per repository, so the lock never coordinated anything there. - The driver neither reads nor writes the lock property and ignores locks left by earlier versions. filterLocked becomes filterActive, the activity filter alone. attemptLock, releaseLock, readLock, isLockStale, LockValue, Options.StaleThreshold and the jitter sleep go. - Before reading an issue's comments and history, processIssue writes a writeCheck entity property to confirm the credential can write, as the lock write did. An issue that fails yields no records and the driver warns and goes on; a cycle in which every selected issue fails ends in the existing all-failed error. Idle candidates still cost no write. - The "poll complete" line drops its unlocked count. - The Jira guide, architecture overview and custom poller example describe the one-cycle-per-repository rule; the example gains a concurrency group. BREAKING CHANGE: the jira-poll driver no longer locks issues. A scheduler other than the managed GitHub workflow or GitLab schedule must keep two poll cycles for one repository from overlapping, for example with a GitHub Actions concurrency group; overlapping cycles dispatch the same requests twice. Lock properties left by earlier versions are ignored and can be deleted. Signed-off-by: guy oron --- docs/architecture.md | 14 +- docs/guides/user/custom-poller-example.md | 5 + docs/guides/user/jira-integration.md | 30 +- internal/jirapoll/gitlab_target_test.go | 18 +- internal/jirapoll/lock.go | 175 ++--------- internal/jirapoll/poller.go | 140 +++------ internal/jirapoll/poller_idle_test.go | 57 +--- internal/jirapoll/poller_test.go | 364 ++++++---------------- internal/jirapoll/types.go | 12 - 9 files changed, 194 insertions(+), 621 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 66d9bcb657..c4b74c44ad 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -544,10 +544,11 @@ The existing design principle is that [the repo is the coordinator](problems/age ([guide](guides/user/chaining-follow-up-workflows.md), [ADR 0124](ADRs/0124-criteria-for-adding-a-built-in-agent-role.md)). - Per-repo **polling** complements webhook dispatch: `fullsend poll` uses poll - input drivers to discover work from remote systems (Jira first), coordinates - via source-native write-then-verify locks, and feeds the same dispatch pipeline - as webhooks ([ADR 0063](ADRs/0063-polling-based-work-discovery.md)). Initial - scope is per-repo mode only. + input drivers to discover work from remote systems (Jira first), runs one + cycle at a time per repository with no per-issue lock (ADR 0085), and feeds + the same dispatch pipeline as webhooks + ([ADR 0063](ADRs/0063-polling-based-work-discovery.md)). Initial scope is + per-repo mode only. - Jira poll candidate selection spends per-cycle slots only on candidates whose Jira `updated` is newer than their per-repository checkpoint, picks at random among them, and reads the per-cycle caps (N, default 5, and M, @@ -729,8 +730,9 @@ The existing design principle is that [the repo is the coordinator](problems/age remains open. - Is GitHub's event system sufficient for forge-native duplicate protection, or do we need additional coordination beyond label/state conventions and agent - idempotency? (Jira polling per ADR 0063 uses entity-property locks and runner - lock refresh; ADR 0098 does not resolve this question.) + idempotency? (Jira polling relies on one poll cycle at a time per repository + and no longer locks issues, per ADR 0085; ADR 0098 does not resolve this + question.) - How does work assignment interact with the backlog/priority agent described in [agent-architecture.md](problems/agent-architecture.md)? - How should explicit cancellation, retry, and reassignment interact with the automatic event-coalescing policy in diff --git a/docs/guides/user/custom-poller-example.md b/docs/guides/user/custom-poller-example.md index e9928aa76e..049ca04d0f 100644 --- a/docs/guides/user/custom-poller-example.md +++ b/docs/guides/user/custom-poller-example.md @@ -32,6 +32,11 @@ permissions: jobs: poll: runs-on: ubuntu-24.04 + # The jira-poll driver keeps no per-issue lock: two overlapping cycles + # for one repository dispatch the same requests twice, so queue them. + concurrency: + group: ${{ github.workflow }}-poll + cancel-in-progress: false outputs: matrix: ${{ steps.dispatch.outputs.matrix }} steps: diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 667bd45ed7..65ef5f60a2 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -43,8 +43,8 @@ Connect fullsend to a Jira project so that Jira issue activity — comments, lab 2. **Grant it the minimum Jira permissions** in the target project, usually through the **Developers** project role. The poller needs Browse Projects, Edit Issues, Add Comments, and Edit Own Comments to operate on - issues and write the entity properties it uses for lock and checkpoint - coordination. Then choose how Jira users are authorized: + issues and write the entity properties it uses for its write-access + check and checkpoint. Then choose how Jira users are authorized: - **Recommended:** list who may trigger agents under a `jira` provider in `.fullsend/config.yaml`. The poller account then also needs the Browse users and groups global permission, but only if the lists name @@ -990,7 +990,7 @@ reuse fullsend's harness infrastructure the same way. See [Custom Poller Example](custom-poller-example.md) for more details on this pattern. -**The poll job's concurrency group (`cancel-in-progress: false`)** makes overlapping poll cycles queue rather than cancel each other. It is the primary defense against concurrent runs: only one poll cycle for this workflow runs at a time in the common case, including manually triggered runs. The poller's own Jira entity-property locking is a secondary guard for cases outside that group: it re-checks for a live lock immediately before writing, narrowing the race to the jitter window between that check and the write, but Jira entity properties have no compare-and-swap, so a lock created in that narrow window can still be clobbered by a genuinely concurrent poller. Treat the GHA concurrency group as the real safety mechanism, not the lock. +**The poll job's concurrency group (`cancel-in-progress: false`)** makes overlapping poll cycles queue rather than cancel each other, so only one poll cycle for this workflow runs at a time, including manually triggered runs. The poller relies on it: it keeps no per-issue lock, so two overlapping cycles for one repository dispatch the same requests twice. A scheduler other than the managed workflow or the managed GitLab schedule must itself keep cycles for one repository from overlapping. ### Custom JQL @@ -1177,7 +1177,7 @@ then only the `[…truncated]` marker — and ran it shortened. A one-line command up to about 3,000 ASCII characters now runs whole, and a longer one is refused instead of dispatched. -GitLab targets keep their lock and checkpoint properties in their own +GitLab targets keep their checkpoint and write-check properties in their own namespace, `fullsend.poll.gitlab.{instance}.{group path}.{project}.*`, where `{instance}` is the host and any path prefix of `--gitlab-url`. A GitLab project never shares Jira coordination state with a GitHub repository of the @@ -1435,14 +1435,14 @@ 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 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 checkpoint tracking. It keeps no per-issue lock: it relies on one poll cycle at a time per target repository (see [Scheduled workflow](#scheduled-workflow)). 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 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. +- **Write check** (`fullsend.poll.{owner}.{repo}.writeCheck`) — written before the poller reads an issue's comments and history, to confirm the credential can write to the issue and so commit its `lastCheck`; nothing reads it. An issue that fails the check is skipped with `WARNING: processing : check write access to : ...`, and a cycle in which every selected issue fails ends in an error, so a credential that cannot write shows as a failed run. Earlier versions kept a lock at `fullsend.poll.{owner}.{repo}.lock`; the poller no longer reads, writes or removes it. - **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. 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` property. The driver treats it 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`. Three edge cases of checkpoint tracking are worth knowing: @@ -1474,7 +1474,7 @@ 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. 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. +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 candidate (at most M per cycle); a candidate with nothing new costs no property write, no comment or changelog listing and no `lastCheck` write. Each selected issue costs one property write for the write-access check. Two more scaling limits: @@ -1493,32 +1493,32 @@ The `--target-repo` flag passed to `fullsend poll` (defaulting to `${{ github.repository }}`; an `owner/repo` slug, and one that contains `..` is refused) controls two things: -1. **Entity property namespace.** Lock and checkpoint properties are keyed as `fullsend.poll.{owner}.{repo}.*`, so repos `acme/frontend` and `acme/backend` polling the same Jira project write to separate property keys on each issue and never interfere with each other. +1. **Entity property namespace.** Checkpoint and write-check properties are keyed as `fullsend.poll.{owner}.{repo}.*`, so repos `acme/frontend` and `acme/backend` polling the same Jira project write to separate property keys on each issue and never interfere with each other. 2. **GHA concurrency group.** The workflow's `concurrency.group` is scoped to the workflow file, which lives in the repo — so each repo's poll cycles queue independently. This means each repo discovers and dispatches changes on its own schedule, with its own credentials and its own `tracker.jira.poll.query` filter. There is no shared state between repos. -### How entity property locks namespace across repos +### How entity properties namespace across repos The poller stores two properties per issue, both namespaced by the target repo's `{owner}/{repo}` slug: | Property | Key pattern | |---|---| -| Lock | `fullsend.poll.{owner}.{repo}.lock` | +| Write check | `fullsend.poll.{owner}.{repo}.writeCheck` | | Checkpoint | `fullsend.poll.{owner}.{repo}.lastCheck` | When `acme/frontend` and `acme/backend` both poll issue `PROJ-42`: -- `acme/frontend` reads and writes `fullsend.poll.acme.frontend.lock` and `fullsend.poll.acme.frontend.lastCheck`. -- `acme/backend` reads and writes `fullsend.poll.acme.backend.lock` and `fullsend.poll.acme.backend.lastCheck`. +- `acme/frontend` writes `fullsend.poll.acme.frontend.writeCheck` and reads and writes `fullsend.poll.acme.frontend.lastCheck`. +- `acme/backend` writes `fullsend.poll.acme.backend.writeCheck` and reads and writes `fullsend.poll.acme.backend.lastCheck`. -The two repos lock independently, checkpoint independently, and can process the same Jira comment — each dispatching to its own agent workflows. This is intentional: the same `/fs-triage` comment on a Jira issue may be relevant to multiple repos if their harness triggers match. +The two repos checkpoint independently and can process the same Jira comment — each dispatching to its own agent workflows. This is intentional: the same `/fs-triage` comment on a Jira issue may be relevant to multiple repos if their harness triggers match. ### 50-candidate cap with multiple repos Each repo's poller runs its own JQL query and gets its own top-M (default 50) candidate window. The cap is per-poller, not global — three repos polling the same project each see up to 50 candidates per cycle, not 50 shared across all three. -However, more pollers against the same Jira project means more API calls per cycle. Each poller independently reads entity properties for lock filtering, fetches changelogs, and paginates comments. For large multi-repo deployments, consider: +However, more pollers against the same Jira project means more API calls per cycle. Each poller independently reads an entity property per candidate for the activity filter, fetches changelogs, and paginates comments. For large multi-repo deployments, consider: - **Narrowing `tracker.jira.poll.query` per repo** to reduce candidate overlap. Use Jira Components or labels to segment the project (see the recommendation above), then scope each repo's query — e.g., `component = Frontend` or `labels = frontend` — so it skips issues that belong to other repos. - **Staggering cron schedules** so pollers from different repos don't hit the Jira API simultaneously. For example, offset each repo's schedule by one or two minutes. diff --git a/internal/jirapoll/gitlab_target_test.go b/internal/jirapoll/gitlab_target_test.go index 6af1406c16..60812b8c3f 100644 --- a/internal/jirapoll/gitlab_target_test.go +++ b/internal/jirapoll/gitlab_target_test.go @@ -261,28 +261,28 @@ func TestRunGitLabTarget_LabelsBoundBeforeTriggerMatch(t *testing.T) { func TestPropertyKeys_GitLabTargetNamespace(t *testing.T) { github := New(nil, nil, Options{TargetRepo: "group/project"}) gitlab := New(nil, nil, Options{TargetRepo: "group/project", TargetForge: TargetForgeGitLab, GitLabURL: "https://gitlab.com"}) - if github.lockKey() != "fullsend.poll.group.project.lock" || github.lastCheckKey() != "fullsend.poll.group.project.lastCheck" { - t.Errorf("GitHub keys changed: %q, %q", github.lockKey(), github.lastCheckKey()) + if github.writeCheckKey() != "fullsend.poll.group.project.writeCheck" || github.lastCheckKey() != "fullsend.poll.group.project.lastCheck" { + t.Errorf("GitHub keys changed: %q, %q", github.writeCheckKey(), github.lastCheckKey()) } - if gitlab.lockKey() == github.lockKey() || gitlab.lastCheckKey() == github.lastCheckKey() { + if gitlab.writeCheckKey() == github.writeCheckKey() || gitlab.lastCheckKey() == github.lastCheckKey() { t.Error("GitLab and GitHub targets with the same path share coordination keys") } - if got := gitlab.lockKey(); got != "fullsend.poll.gitlab.gitlab%2Ecom.group.project.lock" { - t.Errorf("GitLab lock key = %q", got) + if got := gitlab.writeCheckKey(); got != "fullsend.poll.gitlab.gitlab%2Ecom.group.project.writeCheck" { + t.Errorf("GitLab write-check key = %q", got) } selfManaged := New(nil, nil, Options{TargetRepo: "group/project", TargetForge: TargetForgeGitLab, GitLabURL: "https://GitLab.Example.com/gitlab/"}) if got := selfManaged.lastCheckKey(); got != "fullsend.poll.gitlab.gitlab%2Eexample%2Ecom/gitlab.group.project.lastCheck" { t.Errorf("self-managed lastCheck key = %q, want the lowercased host and path prefix", got) } - if selfManaged.lockKey() == gitlab.lockKey() { - t.Error("the same project path on two GitLab instances shares a lock key") + if selfManaged.writeCheckKey() == gitlab.writeCheckKey() { + t.Error("the same project path on two GitLab instances shares a write-check key") } nested := New(nil, nil, Options{TargetRepo: "a.b/c", TargetForge: TargetForgeGitLab, GitLabURL: "https://gitlab.com"}) dotted := New(nil, nil, Options{TargetRepo: "a/b.c", TargetForge: TargetForgeGitLab, GitLabURL: "https://gitlab.com"}) - if nested.lockKey() == dotted.lockKey() { - t.Errorf("dotted GitLab paths collide on %q", nested.lockKey()) + if nested.writeCheckKey() == dotted.writeCheckKey() { + t.Errorf("dotted GitLab paths collide on %q", nested.writeCheckKey()) } } diff --git a/internal/jirapoll/lock.go b/internal/jirapoll/lock.go index 9a855f7515..e87e307cfe 100644 --- a/internal/jirapoll/lock.go +++ b/internal/jirapoll/lock.go @@ -11,22 +11,23 @@ import ( "time" "github.com/fullsend-ai/fullsend/internal/forge" - "github.com/fullsend-ai/fullsend/internal/randutil" ) // escapeKeySegment escapes dots in an owner/repo segment so the // dot-delimited property key can't be forged by two different target // repos. Without it, "a.b/c" and "a/b.c" both collapse to -// fullsend.poll.a.b.c.*, silently sharing a lock and checkpoint namespace +// fullsend.poll.a.b.c.*, silently sharing a checkpoint namespace // (a cross-repo event-loss bug). Dot-free segments (the common case, // including every GitHub owner) are unchanged. func escapeKeySegment(s string) string { return strings.ReplaceAll(s, ".", "%2E") } -// lockPropertyKey returns the entity property key for locks. -func lockPropertyKey(owner, repo string) string { - return fmt.Sprintf("fullsend.poll.%s.%s.lock", escapeKeySegment(owner), escapeKeySegment(repo)) +// writeCheckPropertyKey returns the entity property key the write-access +// check writes. Earlier versions kept a lock at the ".lock" key of the same +// namespace; the driver no longer reads or writes it (ADR 0085). +func writeCheckPropertyKey(owner, repo string) string { + return fmt.Sprintf("fullsend.poll.%s.%s.writeCheck", escapeKeySegment(owner), escapeKeySegment(repo)) } // lastCheckPropertyKey returns the entity property key for lastCheck. @@ -37,7 +38,7 @@ func lastCheckPropertyKey(owner, repo string) string { // gitlabPropertyKeyPrefix returns the entity property key prefix for a // GitLab target. It adds a "gitlab" segment and the instance (host plus any // path prefix of a self-managed URL) ahead of the project path, so a GitLab -// project never shares lock or checkpoint state with a GitHub repository, +// project never shares checkpoint state with a GitHub repository, // or with a project of the same path on another GitLab instance. Every // segment has its dots escaped, so these keys always have four segments // between "fullsend.poll." and the suffix, while GitHub keys have two. @@ -56,14 +57,26 @@ func gitlabInstanceSegment(gitlabURL string) string { return strings.ToLower(u.Host) + strings.TrimRight(u.Path, "/") } -// lockKey returns the lock entity property key for the poller's target. -// GitHub targets keep the original fullsend.poll.{owner}.{repo} namespace. -func (p *Poller) lockKey() string { +// writeCheckKey returns the write-check entity property key for the +// poller's target. GitHub targets keep the original +// fullsend.poll.{owner}.{repo} namespace. +func (p *Poller) writeCheckKey() string { owner, repo := splitOwnerRepo(p.opts.TargetRepo) if p.opts.TargetForge == TargetForgeGitLab { - return gitlabPropertyKeyPrefix(gitlabInstanceSegment(p.opts.GitLabURL), owner, repo) + ".lock" + return gitlabPropertyKeyPrefix(gitlabInstanceSegment(p.opts.GitLabURL), owner, repo) + ".writeCheck" } - return lockPropertyKey(owner, repo) + return writeCheckPropertyKey(owner, repo) +} + +// checkWriteAccess confirms the poller can write to an issue before it reads +// the issue's comments and history, as the lock write used to (ADR 0085, +// Decision item 1). Without it, a credential that can read but not write +// would dispatch an issue's requests and then fail to commit its +// checkpoint, so every cycle would dispatch them again. It writes the check +// time to the write-check property, which nothing reads; entity property +// writes do not move the issue's updated value. +func (p *Poller) checkWriteAccess(ctx context.Context, issueKey string) error { + return p.client.SetEntityProperty(ctx, issueKey, p.writeCheckKey(), time.Now().UTC().Format(time.RFC3339)) } // lastCheckKey returns the lastCheck entity property key for the poller's @@ -85,103 +98,6 @@ func splitOwnerRepo(slug string) (string, string) { return slug[:idx], slug[idx+1:] } -// attemptLock tries to acquire a lock on the issue using write-then-verify. -// Returns true if the lock was acquired successfully. -func (p *Poller) attemptLock(ctx context.Context, issueKey, lockID string) (bool, error) { - propKey := p.lockKey() - - // Re-check for a live lock immediately before writing. filterLocked's - // read of this issue can be tens of seconds stale by the time we reach - // here (earlier candidates in the same cycle still being processed, - // role-membership fetches), so without this check a late arriver would - // overwrite an active holder's lock outright and both pollers would - // proceed to dispatch. This is not a compare-and-swap — Jira entity - // properties don't support one — so a lock written in the gap between - // this read and our SetEntityProperty below can still be clobbered; - // that narrower race is the one write-then-verify below is meant to - // catch via the jitter/re-read. - existing, err := p.readLock(ctx, issueKey) - if err != nil { - return false, fmt.Errorf("check existing lock: %w", err) - } - if existing != nil && !isLockStale(*existing, p.opts.StaleThreshold) { - return false, nil - } - - lock := LockValue{ - ID: lockID, - TS: time.Now().UTC().Format(time.RFC3339), - Phase: "pending", - } - - if err := p.client.SetEntityProperty(ctx, issueKey, propKey, lock); err != nil { - return false, fmt.Errorf("set lock property: %w", err) - } - - // Jitter sleep: 500-1500ms to allow concurrent pollers to write. - jitter := time.Duration(500+randutil.IntN(1000)) * time.Millisecond - p.sleepFn(ctx, jitter) - - // Re-read and verify our UUID still holds. - raw, err := p.client.GetEntityProperty(ctx, issueKey, propKey) - if err != nil { - // The write succeeded but verification failed. Best-effort release - // the lock we just wrote so a transient read error doesn't leak it - // until the stale-lock threshold expires. - if releaseErr := p.releaseLock(ctx, issueKey, lockID); releaseErr != nil { - log.Printf("WARNING: releasing lock on %s after verify failure: %v", issueKey, releaseErr) - } - return false, fmt.Errorf("verify lock: %w", err) - } - if len(raw) == 0 { - return false, nil - } - - var current LockValue - if err := json.Unmarshal(raw, ¤t); err != nil { - // Same anomaly class as the read-error path above: our write - // succeeded, so a corrupt read-back must not leak the lock until - // the stale threshold expires. releaseLock compares the lock ID - // before deleting, so this is safe even if the content isn't ours. - if releaseErr := p.releaseLock(ctx, issueKey, lockID); releaseErr != nil { - log.Printf("WARNING: releasing lock on %s after unmarshal failure: %v", issueKey, releaseErr) - } - return false, fmt.Errorf("unmarshal lock: %w", err) - } - - return current.ID == lockID, nil -} - -// releaseLock removes the lock from the issue. When expectedID is non-empty, -// the lock is only deleted if its ID still matches, preventing a slow poller -// from deleting a lock that a faster concurrent poller has already replaced. -func (p *Poller) releaseLock(ctx context.Context, issueKey, expectedID string) error { - propKey := p.lockKey() - - if expectedID != "" { - raw, err := p.client.GetEntityProperty(ctx, issueKey, propKey) - if err != nil { - if errors.Is(err, forge.ErrNotFound) { - return nil // already gone - } - return fmt.Errorf("read lock before release: %w", err) - } - var current LockValue - if err := json.Unmarshal(raw, ¤t); err != nil { - return fmt.Errorf("unmarshal lock before release: %w", err) - } - if current.ID != expectedID { - // current.ID comes from an attacker-writable entity property; - // log it quoted so a crafted id with newlines can't forge - // audit-log lines. - log.Printf("lock on %s owned by %q, not %q; skipping release", issueKey, current.ID, expectedID) - return nil - } - } - - return p.client.DeleteEntityProperty(ctx, issueKey, propKey) -} - // 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) { @@ -274,46 +190,3 @@ func (p *Poller) loadLastCheck(ctx context.Context, issueKey string) (storedLast func (p *Poller) advanceLastCheck(ctx context.Context, issueKey string, t time.Time) error { return p.client.SetEntityProperty(ctx, issueKey, p.lastCheckKey(), t.UTC().Format(time.RFC3339Nano)) } - -// isLockStale checks if a lock has exceeded the stale threshold. The lock -// timestamp is attacker-writable (issue entity property), so both a -// corrupt/unparseable value and one dated in the future are treated as -// stale (reclaimable): otherwise a future-dated ts gives time.Since a -// negative value that never exceeds the threshold, permanently wedging the -// issue with no way to recover but manual deletion. -func isLockStale(lock LockValue, threshold time.Duration) bool { - t, err := time.Parse(time.RFC3339, lock.TS) - if err != nil { - return true - } - age := time.Since(t) - // A small negative age is normal clock skew from a peer that just - // wrote the lock; only a ts more than one threshold ahead of now is - // treated as corrupt/tampered and reclaimable. - if age < -threshold { - return true - } - return age > threshold -} - -// readLock reads the lock value for an issue. Returns nil if no lock exists. -func (p *Poller) readLock(ctx context.Context, issueKey string) (*LockValue, error) { - propKey := p.lockKey() - - raw, err := p.client.GetEntityProperty(ctx, issueKey, propKey) - if err != nil { - if errors.Is(err, forge.ErrNotFound) { - return nil, nil // no lock property yet - } - return nil, fmt.Errorf("get lock property: %w", err) - } - if len(raw) == 0 { - return nil, nil - } - - var lock LockValue - if err := json.Unmarshal(raw, &lock); err != nil { - return nil, fmt.Errorf("unmarshal lock: %w", err) - } - return &lock, nil -} diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 62231d5d0f..b383c428c4 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -1,6 +1,7 @@ // Package jirapoll implements a polling-based input driver for Jira, // converting issue comments, label changes, and status transitions into -// NormalizedEvents per ADR 0063's write-then-verify coordination protocol. +// NormalizedEvents per ADR 0063, with one poller per target repository and +// no per-issue lock (ADR 0085). package jirapoll import ( @@ -18,8 +19,6 @@ import ( "github.com/fullsend-ai/fullsend/internal/forge/jira" "github.com/fullsend-ai/fullsend/internal/normevent" "github.com/fullsend-ai/fullsend/internal/randutil" - - "github.com/google/uuid" ) // EventMatcher evaluates a normalized event against harness CEL triggers @@ -61,28 +60,16 @@ type Poller struct { matcher EventMatcher opts Options dispatches []DispatchRecord - sleepFn func(context.Context, time.Duration) // overridable for testing - roleMembership map[string]string // accountID → Jira project role name - roleGroups map[string][]string // Jira role name → group IDs for per-actor resolution - roleGroupsChecked map[string]bool // accountID → group membership already fetched this cycle - rolesLoaded bool // project role roster loaded (or skipped for a missing project key) this cycle - userGroups map[string][]jira.UserGroupInfo // accountID → GetUserGroups result, cached per cycle - statusCategoryCache map[string]string // status name → statusCategory key, reset each cycle - selfAccountID string // authenticated Jira account from GetMyself; used to classify self-authored events as bot - eventsSeen int // events converted this cycle - eventsInvalid int // events skipped this cycle because they failed validation - eventsMatchErrors int // events dropped this cycle because matcher.Match errored -} - -// ctxSleep sleeps for d or until ctx is cancelled, whichever comes first, -// so a cancelled poll (e.g. a killed CI job) doesn't block on lock jitter. -func ctxSleep(ctx context.Context, d time.Duration) { - t := time.NewTimer(d) - defer t.Stop() - select { - case <-t.C: - case <-ctx.Done(): - } + roleMembership map[string]string // accountID → Jira project role name + roleGroups map[string][]string // Jira role name → group IDs for per-actor resolution + roleGroupsChecked map[string]bool // accountID → group membership already fetched this cycle + rolesLoaded bool // project role roster loaded (or skipped for a missing project key) this cycle + userGroups map[string][]jira.UserGroupInfo // accountID → GetUserGroups result, cached per cycle + statusCategoryCache map[string]string // status name → statusCategory key, reset each cycle + selfAccountID string // authenticated Jira account from GetMyself; used to classify self-authored events as bot + eventsSeen int // events converted this cycle + eventsInvalid int // events skipped this cycle because they failed validation + eventsMatchErrors int // events dropped this cycle because matcher.Match errored } // New creates a Jira Poller with the given options. @@ -93,9 +80,6 @@ func New(client JiraClient, matcher EventMatcher, opts Options) *Poller { if opts.N == 0 { opts.N = 5 } - if opts.StaleThreshold == 0 { - opts.StaleThreshold = 900 * time.Second - } if opts.FirstPollBackfillWindow == 0 { opts.FirstPollBackfillWindow = 24 * time.Hour } @@ -103,13 +87,13 @@ func New(client JiraClient, matcher EventMatcher, opts Options) *Poller { client: client, matcher: matcher, opts: opts, - sleepFn: ctxSleep, } } -// Run executes a single poll cycle per ADR 0063. +// Run executes a single poll cycle per ADR 0063. The caller must keep two +// cycles for one target repository from overlapping: with no lock, they +// would dispatch the same requests twice (ADR 0085, Decision item 1). func (p *Poller) Run(ctx context.Context) error { - cycleID := uuid.New().String() p.dispatches = nil p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors = 0, 0, 0 p.statusCategoryCache = make(map[string]string) @@ -119,7 +103,7 @@ func (p *Poller) Run(ctx context.Context) error { p.rolesLoaded = false p.userGroups = make(map[string][]jira.UserGroupInfo) - // Auth preflight: verify credentials before any discovery, lock, or + // Auth preflight: verify credentials before any discovery or // checkpoint operations. Without this, bad credentials cause Jira to // treat the request as unauthenticated and return empty results — // indistinguishable from a genuinely quiet project. @@ -143,13 +127,10 @@ func (p *Poller) Run(ctx context.Context) error { return fmt.Errorf("search candidates: %w", err) } - // 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 2: 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 := p.filterActive(ctx, candidates) // Step 3: Randomly select min(N, len(active)) candidates. selected := selectRandom(active, p.opts.N) @@ -175,7 +156,7 @@ func (p *Poller) Run(ctx context.Context) error { var processErrors int for _, issue := range selected { start := len(p.dispatches) - checkpoint, err := p.processIssue(ctx, issue, cycleID) + checkpoint, err := p.processIssue(ctx, issue) if err != nil { var rle *roleLoadError if errors.As(err, &rle) { @@ -296,8 +277,8 @@ func (p *Poller) Run(ctx context.Context) error { } } - log.Printf("poll complete: %d candidates, %d unlocked, %d active, %d selected, %d dispatches", - len(candidates), unlocked, len(active), len(selected), len(p.dispatches)) + log.Printf("poll complete: %d candidates, %d active, %d selected, %d dispatches", + len(candidates), len(active), len(selected), len(p.dispatches)) 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) } @@ -417,48 +398,20 @@ func (p *Poller) searchCandidates(ctx context.Context) ([]jira.Issue, error) { return p.client.SearchIssues(ctx, jql, p.opts.M) } -// 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) { +// filterActive keeps the candidates with new activity (see hasNewActivity) +// and logs the cycle's clamped lastCheck values once. It neither reads nor +// writes lock properties, including those left by earlier versions +// (ADR 0085, Decision item 1). +func (p *Poller) filterActive(ctx context.Context, issues []jira.Issue) []jira.Issue { 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) - if err != nil { - log.Printf("WARNING: reading lock for %s: %v (skipping)", issue.Key, err) - readErrors++ - continue - } - if lock != nil { - if isLockStale(*lock, p.opts.StaleThreshold) { - log.Printf("cleaning stale lock on %s (age > %s)", issue.Key, p.opts.StaleThreshold) - if err := p.releaseLock(ctx, issue.Key, lock.ID); err != nil { - log.Printf("WARNING: cleaning stale lock for %s: %v", issue.Key, err) - releaseErrors++ - continue - } - } else { - continue - } - } - unlocked++ if p.hasNewActivity(ctx, issue, &clamped) { active = append(active, issue) } } - if len(issues) > 0 && readErrors+releaseErrors == len(issues) { - 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 + return active } // hasNewActivity reports whether issue has activity after its lastCheck: @@ -547,34 +500,17 @@ func selectRandom(items []jira.Issue, n int) []jira.Issue { return items[:n] } -// processIssue acquires the lock, detects changes, converts, routes, and -// dispatches. It returns the checkpoint value the caller should advance +// processIssue confirms write access, detects changes, converts, routes, +// and dispatches. It returns the checkpoint value the caller should advance // lastCheck to once the dispatch file has been durably written (zero if // there is nothing to advance) — it does not commit the checkpoint itself. -func (p *Poller) processIssue(ctx context.Context, issue jira.Issue, cycleID string) (time.Time, error) { - // Attempt lock. - acquired, err := p.attemptLock(ctx, issue.Key, cycleID) - if err != nil { - return time.Time{}, fmt.Errorf("lock %s: %w", issue.Key, err) - } - if !acquired { - log.Printf("lock contention on %s, skipping", issue.Key) - return time.Time{}, nil - } - // KNOWN LIMITATION: the lock covers the change-detection window only. - // It is released here at the end of processIssue — before writeDispatches - // runs and before the downstream dispatch step consumes the records — so - // it does not provide the through-dispatch-scheduling ownership ADR 0063 - // describes; that handoff is part of the same tracked follow-up as the - // lastCheck dispatch-confirmation note below. The lock is also never - // renewed while an issue is processed: a cycle stalled longer than - // StaleThreshold can have its lock reclaimed as stale by a concurrent - // poller, which may duplicate dispatches for the same activity. - defer func() { - if err := p.releaseLock(ctx, issue.Key, cycleID); err != nil { - log.Printf("WARNING: releasing lock for %s: %v", issue.Key, err) - } - }() +func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (time.Time, error) { + // Confirm write access before reading the issue's comments and history + // (ADR 0085, Decision item 1). A failure yields no records: Run warns + // and goes on, and a cycle in which every issue fails ends in an error. + if err := p.checkWriteAccess(ctx, issue.Key); err != nil { + return time.Time{}, fmt.Errorf("check write access to %s: %w", issue.Key, err) + } // Read lastCheck. lastCheck, err := p.readLastCheck(ctx, issue.Key) diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index 2d2f18d04b..b38ba0ee70 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "path/filepath" - "slices" "strings" "testing" "time" @@ -81,8 +80,8 @@ func dispatchedKeys(p *Poller) []string { 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. +// An idle candidate is dropped before the pick and costs no property 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) @@ -118,7 +117,7 @@ func TestRunSkipsIdleCandidates(t *testing.T) { 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) { + if want := "poll complete: 10 candidates, 3 active, 3 selected, 3 dispatches"; !strings.Contains(logs.String(), want) { t.Errorf("log lacks %q:\n%s", want, logs.String()) } } @@ -142,40 +141,6 @@ func sameSet(a, b []string) bool { 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. @@ -403,13 +368,7 @@ func TestFilterLockedActivityDecision(t *testing.T) { 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) - } + active := idleTestPoller(mc, t).filterActive(context.Background(), []jira.Issue{issue}) if got := len(active) == 1; got != tc.active { t.Errorf("active = %v, want %v", got, tc.active) } @@ -435,14 +394,14 @@ func TestFilterLockedGitLabTargetReadsItsOwnKey(t *testing.T) { 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) + if active := p.filterActive(context.Background(), []jira.Issue{issue}); len(active) != 0 { + t.Errorf("lastCheck equal to updated under the GitLab key: active %v; want idle", active) } 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) + if active := newTestPoller(mc, nil, opts).filterActive(context.Background(), []jira.Issue{issue}); len(active) != 1 { + t.Errorf("lastCheck only under the GitHub-style key: active %v; want active", active) } } diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index e9c8055918..5e8f90470d 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -18,11 +18,9 @@ import ( "github.com/fullsend-ai/fullsend/internal/normevent" ) -// newTestPoller creates a Poller with a no-op sleep for fast tests. +// newTestPoller creates a Poller for tests. func newTestPoller(client JiraClient, matcher EventMatcher, opts Options) *Poller { - p := New(client, matcher, opts) - p.sleepFn = func(_ context.Context, _ time.Duration) {} // skip jitter in tests - return p + return New(client, matcher, opts) } // mockClient implements JiraClient with configurable return values. @@ -305,9 +303,6 @@ func TestNew(t *testing.T) { if p.opts.N != 5 { t.Errorf("N = %d, want default 5", p.opts.N) } - if p.opts.StaleThreshold != 900*time.Second { - t.Errorf("StaleThreshold = %v, want default 900s", p.opts.StaleThreshold) - } } func TestRunEmptyPoll(t *testing.T) { @@ -737,7 +732,7 @@ func TestProcessIssue_CheckpointNeverRegresses(t *testing.T) { Created: now.Add(-1 * time.Hour).Format("2006-01-02T15:04:05.000-0700"), }, } - checkpoint, err := p.processIssue(context.Background(), issue, "cycle-1") + checkpoint, err := p.processIssue(context.Background(), issue) if err != nil { t.Fatalf("processIssue() error: %v", err) } @@ -1040,33 +1035,17 @@ func TestReadLastCheck_ClampsUntrustedValues(t *testing.T) { } } -// TestIsLockStale_FutureTimestampIsStale: a future-dated lock (clock skew -// beyond tolerance or a tampered value) must be reclaimable, not treated -// as forever-fresh. -func TestIsLockStale_FutureTimestampIsStale(t *testing.T) { - threshold := 900 * time.Second - future := LockValue{ID: "x", TS: time.Now().Add(72 * time.Hour).UTC().Format(time.RFC3339)} - if !isLockStale(future, threshold) { - t.Error("a far-future lock timestamp must be treated as stale/reclaimable") - } - // A small future skew (within threshold) is not stale. - skew := LockValue{ID: "x", TS: time.Now().Add(30 * time.Second).UTC().Format(time.RFC3339)} - if isLockStale(skew, threshold) { - t.Error("a small clock-skew-sized future offset must not be treated as stale") - } -} - // TestPropertyKey_DottedSlugsDoNotCollide: distinct target repos with dots // must not collapse to the same lock/lastCheck property key. func TestPropertyKey_DottedSlugsDoNotCollide(t *testing.T) { o1, r1 := splitOwnerRepo("a.b/c") o2, r2 := splitOwnerRepo("a/b.c") - if lockPropertyKey(o1, r1) == lockPropertyKey(o2, r2) { - t.Errorf("dotted slugs a.b/c and a/b.c collide on lock key %q", lockPropertyKey(o1, r1)) + if writeCheckPropertyKey(o1, r1) == writeCheckPropertyKey(o2, r2) { + t.Errorf("dotted slugs a.b/c and a/b.c collide on write-check key %q", writeCheckPropertyKey(o1, r1)) } // Common dot-free slug keeps the readable, documented format. - if got := lockPropertyKey(splitOwnerRepo("acme/platform")); got != "fullsend.poll.acme.platform.lock" { - t.Errorf("dot-free key = %q, want the documented fullsend.poll.acme.platform.lock", got) + if got := writeCheckPropertyKey(splitOwnerRepo("acme/platform")); got != "fullsend.poll.acme.platform.writeCheck" { + t.Errorf("dot-free key = %q, want the documented fullsend.poll.acme.platform.writeCheck", got) } } @@ -1101,7 +1080,7 @@ func TestProcessIssue_CapsEventsPerIssue(t *testing.T) { Reporter: jira.User{AccountID: "reporter-id"}, Created: now.Add(-2 * time.Hour).Format("2006-01-02T15:04:05.000-0700"), }, - }, "cycle-1"); err != nil { + }); err != nil { // seed a lastCheck so it's not a first poll _ = lastCheck t.Fatalf("processIssue() error: %v", err) @@ -1461,44 +1440,10 @@ func TestRunHumanFollowupAlongsideSelfAuthored(t *testing.T) { } } -// TestAttemptLock_LiveLockRejectedWithoutWriting is a regression test: -// attemptLock previously wrote its own lock unconditionally before ever -// checking for an existing one, so a poller reaching attemptLock well after -// filterLocked's read (e.g. behind other candidates in the same cycle) -// could overwrite an active holder's lock outright and both would proceed -// to dispatch. attemptLock must now check for a live lock first and bail -// out without writing. -func TestAttemptLock_LiveLockRejectedWithoutWriting(t *testing.T) { - mc := newMockClient() - holder := LockValue{ID: "holder-cycle", TS: time.Now().UTC().Format(time.RFC3339), Phase: "pending"} - holderJSON, _ := json.Marshal(holder) - mc.properties["PROJ-123"] = map[string]json.RawMessage{ - "fullsend.poll.acme.platform.lock": holderJSON, - } - - p := newTestPoller(mc, nil, Options{TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net"}) - - acquired, err := p.attemptLock(context.Background(), "PROJ-123", "late-arriver-cycle") - if err != nil { - t.Fatalf("attemptLock() error: %v", err) - } - if acquired { - t.Error("expected attemptLock to reject a live lock held by another cycle") - } - - // The holder's lock must be untouched — attemptLock must not have - // written over it before checking. - raw := mc.properties["PROJ-123"]["fullsend.poll.acme.platform.lock"] - var current LockValue - if err := json.Unmarshal(raw, ¤t); err != nil { - t.Fatalf("unmarshal stored lock: %v", err) - } - if current.ID != "holder-cycle" { - t.Errorf("expected the original holder's lock (ID %q) to remain, got ID %q", "holder-cycle", current.ID) - } -} - -func TestRunLockContention(t *testing.T) { +// A lock property left by an earlier version is neither read, honoured nor +// removed (ADR 0085, Decision item 1): the issue is processed, and the +// write-access check writes its own property. +func TestRunIgnoresLegacyLock(t *testing.T) { now := time.Now().Truncate(time.Second) mc := newMockClient() mc.searchResult = []jira.Issue{ @@ -1514,191 +1459,105 @@ func TestRunLockContention(t *testing.T) { }, } - lockPropKey := lockPropertyKey("acme", "platform") - lockVal := LockValue{ - ID: "other-poller-uuid", - TS: now.Format(time.RFC3339), - Phase: "running", - } - lockData, _ := json.Marshal(lockVal) - mc.properties["PROJ-123"] = map[string]json.RawMessage{ - lockPropKey: lockData, - } - - dir := t.TempDir() - outputPath := filepath.Join(dir, "dispatches.json") + const legacyLockKey = "fullsend.poll.acme.platform.lock" + legacyLock := json.RawMessage(`{"id":"other-poller-uuid","ts":"` + now.Format(time.RFC3339) + `","phase":"running"}`) + mc.properties["PROJ-123"] = map[string]json.RawMessage{legacyLockKey: legacyLock} router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ", - OutputPath: outputPath, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), }) if err := p.Run(context.Background()); err != nil { t.Fatalf("Run() error: %v", err) } - - data, err := os.ReadFile(outputPath) - if err != nil { - t.Fatalf("read output: %v", err) - } - if string(data) != "[]\n" { - t.Errorf("expected empty dispatches (locked), got %q", string(data)) - } -} - -func TestRunStaleLock(t *testing.T) { - now := time.Now().Truncate(time.Second) - mc := newMockClient() - mc.roleMembership = map[string]string{ - "user1": "Developers", - } - mc.searchResult = []jira.Issue{ - { - ID: "10042", - Key: "PROJ-123", - Fields: jira.IssueFields{ - Labels: []string{"bug"}, - Reporter: jira.User{AccountID: "reporter-id", AccountType: "atlassian"}, - Created: now.Add(-1 * time.Hour).Format("2006-01-02T15:04:05.000-0700"), - Updated: now.Format("2006-01-02T15:04:05.000-0700"), - }, - }, - } - - lockPropKey := lockPropertyKey("acme", "platform") - lockVal := LockValue{ - ID: "old-poller-uuid", - TS: now.Add(-2 * time.Hour).Format(time.RFC3339), - Phase: "running", - } - lockData, _ := json.Marshal(lockVal) - mc.properties["PROJ-123"] = map[string]json.RawMessage{ - lockPropKey: lockData, - } - - mc.comments["PROJ-123"] = []jira.Comment{ - { - ID: "50001", - Body: "/fs-triage handle this", - Created: now.Format("2006-01-02T15:04:05.000-0700"), - Author: jira.User{ - AccountID: "user1", - AccountType: "atlassian", - }, - }, - } - - dir := t.TempDir() - outputPath := filepath.Join(dir, "dispatches.json") - - router := &stubMatcher{agents: []string{"triage"}} - p := newTestPoller(mc, router, Options{ - TargetRepo: "acme/platform", - JiraBaseURL: "https://acme.atlassian.net", - JiraProject: "PROJ", - OutputPath: outputPath, - StaleThreshold: 15 * time.Minute, - }) - - if err := p.Run(context.Background()); err != nil { - t.Fatalf("Run() error: %v", err) + if len(p.dispatches) != 1 { + t.Errorf("dispatched %d, want 1: a legacy lock must not hold the issue back", len(p.dispatches)) } - - data, err := os.ReadFile(outputPath) - if err != nil { - t.Fatalf("read output: %v", err) + if got := string(mc.properties["PROJ-123"][legacyLockKey]); got != string(legacyLock) { + t.Errorf("legacy lock = %s, want it untouched", got) } - var dispatches []DispatchRecord - if err := json.Unmarshal(data, &dispatches); err != nil { - t.Fatalf("unmarshal: %v", err) + if mc.propertyDeleteCalls["PROJ-123"] != 0 { + t.Errorf("deleted %d properties, want 0", mc.propertyDeleteCalls["PROJ-123"]) } - - if len(dispatches) == 0 { - t.Error("expected dispatches after stale lock cleanup") + if _, ok := mc.properties["PROJ-123"][writeCheckPropertyKey("acme", "platform")]; !ok { + t.Error("the write-access check wrote no property") } } -// TestFilterLockedStaleCleanupPreservesConcurrentFreshLock guards against a -// regression where stale-lock cleanup released the lock property -// unconditionally (expectedID == "") instead of using the stale lock's own -// ID, so a fresh lock written by a different poller in the race window -// between the read and the release got deleted without any ownership check. -func TestFilterLockedStaleCleanupPreservesConcurrentFreshLock(t *testing.T) { - mc := newMockClient() - p := newTestPoller(mc, nil, Options{ - TargetRepo: "acme/platform", - StaleThreshold: 15 * time.Minute, - }) +// writeDeniedClient fails every entity property write on the issues in deny, +// as Jira does for a credential that can read an issue but not edit it. +type writeDeniedClient struct { + *mockClient + deny map[string]bool +} - propKey := lockPropertyKey("acme", "platform") - staleLock := LockValue{ - ID: "stale-poller-uuid", - TS: time.Now().Add(-1 * time.Hour).Format(time.RFC3339), - Phase: "running", +func (c writeDeniedClient) SetEntityProperty(ctx context.Context, issueKey, propKey string, value any) error { + if c.deny[issueKey] { + return fmt.Errorf("403 forbidden") } - staleData, err := json.Marshal(staleLock) - if err != nil { - t.Fatalf("marshal stale lock: %v", err) - } - mc.properties["PROJ-123"] = map[string]json.RawMessage{propKey: staleData} + return c.mockClient.SetEntityProperty(ctx, issueKey, propKey, value) +} - // Simulate a different poller acquiring a fresh lock on the same issue - // in the window between this poller's stale-lock read and its release. - freshLock := LockValue{ - ID: "fresh-poller-uuid", - TS: time.Now().UTC().Format(time.RFC3339), - Phase: "pending", - } - freshData, err := json.Marshal(freshLock) - if err != nil { - t.Fatalf("marshal fresh lock: %v", err) - } - mc.getPropertyHook = func(issueKey, key string) { - if issueKey == "PROJ-123" && key == propKey { - mc.properties["PROJ-123"][propKey] = freshData +// An issue that fails the write-access check yields no records and its +// comments and history are not read; the other issues are processed. A +// cycle in which every issue fails ends in an error (ADR 0085, Decision +// item 1). +func TestRunWriteAccessCheck(t *testing.T) { + now := time.Now().Truncate(time.Second) + newMC := func() *mockClient { + mc := newMockClient() + for n := 1; n <= 2; n++ { + key := fmt.Sprintf("PROJ-%d", n) + mc.searchResult = append(mc.searchResult, idleTestIssue(n, now.Add(-48*time.Hour), now.Add(-time.Minute))) + addTriageComment(mc, key, fmt.Sprintf("50%d", n), now.Add(-time.Minute)) } + return mc + } + poller := func(c JiraClient) *Poller { + return newTestPoller(c, &stubMatcher{agents: []string{"triage"}}, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProject: "PROJ", + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + }) } - if _, _, err := p.filterLocked(context.Background(), []jira.Issue{{Key: "PROJ-123"}}); err != nil { - t.Fatalf("filterLocked() error: %v", err) - } - - raw, ok := mc.properties["PROJ-123"][propKey] - if !ok { - t.Fatal("expected fresh lock to survive stale-lock cleanup, but property was deleted") - } - var current LockValue - if err := json.Unmarshal(raw, ¤t); err != nil { - t.Fatalf("unmarshal current lock: %v", err) - } - if current.ID != freshLock.ID { - t.Errorf("expected surviving lock ID %q, got %q", freshLock.ID, current.ID) - } -} - -// TestFilterLockedErrorsWhenAllLockReadsFail guards against a regression -// where a lock-property read error was treated the same as "locked" and -// silently skipped, so a persistent auth/config problem that makes every -// read fail produced an empty (rather than error) result — indistinguishable -// from a genuinely quiet Jira project. -func TestFilterLockedErrorsWhenAllLockReadsFail(t *testing.T) { - mc := newMockClient() - propKey := lockPropertyKey("acme", "platform") - mc.propertyGetErr[propKey] = fmt.Errorf("403 forbidden") - - p := newTestPoller(mc, nil, Options{TargetRepo: "acme/platform"}) + t.Run("one issue denied", func(t *testing.T) { + logs := captureLog(t) + mc := newMC() + p := poller(writeDeniedClient{mc, map[string]bool{"PROJ-1": true}}) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if len(p.dispatches) != 1 { + t.Errorf("dispatched %d, want 1 (PROJ-2 only)", len(p.dispatches)) + } + if c := mc.listCommentsCalls["PROJ-1"] + mc.listChangelogCalls["PROJ-1"]; c != 0 { + t.Errorf("read PROJ-1's comments or history %d times after its write check failed", c) + } + if mc.listCommentsCalls["PROJ-2"] == 0 { + t.Error("PROJ-2 was not read") + } + if want := "WARNING: processing PROJ-1: check write access to PROJ-1"; !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + }) - issues := []jira.Issue{{Key: "PROJ-1"}, {Key: "PROJ-2"}} - 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(active) != 0 || unlocked != 0 { - t.Errorf("active = %v, unlocked = %d, want none", active, unlocked) - } + t.Run("every issue denied", func(t *testing.T) { + mc := newMC() + p := poller(writeDeniedClient{mc, map[string]bool{"PROJ-1": true, "PROJ-2": true}}) + err := p.Run(context.Background()) + if err == nil || !strings.Contains(err.Error(), "all 2 selected issues failed to process") { + 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)) + } + }) } // TestSearchCandidatesQuotesProjectKey checks that the default JQL quotes @@ -1875,41 +1734,6 @@ func TestRunMultipleEvents(t *testing.T) { } } -func TestIsLockStale(t *testing.T) { - threshold := 15 * time.Minute - - tests := []struct { - name string - lock LockValue - want bool - }{ - { - name: "fresh lock", - lock: LockValue{ID: "uuid", TS: time.Now().Format(time.RFC3339)}, - want: false, - }, - { - name: "stale lock", - lock: LockValue{ID: "uuid", TS: time.Now().Add(-1 * time.Hour).Format(time.RFC3339)}, - want: true, - }, - { - name: "unparseable timestamp", - lock: LockValue{ID: "uuid", TS: "garbage"}, - want: true, - }, - } - - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - got := isLockStale(tc.lock, threshold) - if got != tc.want { - t.Errorf("isLockStale() = %v, want %v", got, tc.want) - } - }) - } -} - func TestSelectRandom(t *testing.T) { issues := make([]jira.Issue, 10) for i := range issues { @@ -2602,20 +2426,6 @@ func setLastCheck(mc *mockClient, issueKey, owner, repo string, t time.Time) { mc.properties[issueKey][propKey] = ts } -func TestReadLock_NotFound(t *testing.T) { - mc := newMockClient() - p := New(mc, nil, Options{TargetRepo: "acme/platform"}) - - // No properties set — mock returns forge.ErrNotFound. - lock, err := p.readLock(context.Background(), "PROJ-123") - if err != nil { - t.Fatalf("readLock() should return nil error for missing property, got: %v", err) - } - if lock != nil { - t.Errorf("readLock() = %+v, want nil (unlocked)", lock) - } -} - func TestReadLastCheck_NotFound(t *testing.T) { mc := newMockClient() p := New(mc, nil, Options{TargetRepo: "acme/platform"}) diff --git a/internal/jirapoll/types.go b/internal/jirapoll/types.go index 61b1cdda92..b0a0418f53 100644 --- a/internal/jirapoll/types.go +++ b/internal/jirapoll/types.go @@ -65,7 +65,6 @@ type Options struct { OutputPath string // Path to write dispatch records JSON M int // Max candidate issues per cycle (default: 50) N int // Max issues to process per cycle (default: 5) - StaleThreshold time.Duration // Lock stale threshold (default: 900s) FirstPollBackfillWindow time.Duration // How far back to backfill comments/changelog on an issue's first poll (default: 24h) // Authorization holds the jira authorization provider from @@ -167,14 +166,3 @@ func (e JiraEvent) Key() string { } return fmt.Sprintf("%s-%s-%d", e.Type, e.IssueKey, e.UpdatedAt.Unix()) } - -// LockValue is stored in the Jira entity property for coordination. -type LockValue struct { - ID string `json:"id"` // Poll cycle UUID - TS string `json:"ts"` // RFC3339 timestamp - // Phase is reserved for the two-phase (pending → running) lock handoff - // described by ADR 0063. Today it is always written as "pending" and - // never read: lock ownership through dispatch scheduling is a tracked - // follow-up (see the KNOWN LIMITATION notes in processIssue). - Phase string `json:"phase"` // "pending" or "running" -} From c060643c9efa3473080fe01744c33380a398d0bf Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 25 Nov 2026 09:37:43 +0200 Subject: [PATCH 03/37] refactor(jirapoll): return an issue's records with its checkpoint as one unit processIssue appended its dispatch records straight to the cycle's list, and Run sliced them back out by index to pair them with the issue's checkpoint. processIssue now returns a pendingCheckpoint that holds both, and Run adds the records and the checkpoint to the cycle together. No behaviour changes. The per-cycle and per-issue limits of ADR 0085 Decision item 3 need this: an issue that does not fit in the room left must be left out whole, records and checkpoint, for the next cycle. Signed-off-by: guy oron --- internal/jirapoll/poller.go | 52 +++++++++++++++------------ internal/jirapoll/poller_idle_test.go | 22 ++++++++++++ internal/jirapoll/poller_test.go | 17 ++++----- 3 files changed, 60 insertions(+), 31 deletions(-) diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index b383c428c4..9520fe2a6e 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -147,7 +147,9 @@ func (p *Poller) Run(ctx context.Context) error { // Step 4: Process each selected issue. Checkpoint advances are not // committed to Jira here — detectChanges/routing only compute the // candidate checkpoint per issue; processIssue returns it (zero if - // there's nothing to advance) and Step 6 below commits it only after + // there's nothing to advance) together with the issue's records, this + // loop adds the two to the cycle as one unit, and Step 6 below commits + // the checkpoint only after // Step 5's dispatch-file write has durably succeeded. Committing here // instead would mean a local write failure permanently loses every // event this cycle found: the checkpoint would already be past them in @@ -155,8 +157,7 @@ func (p *Poller) Run(ctx context.Context) error { var pending []pendingCheckpoint var processErrors int for _, issue := range selected { - start := len(p.dispatches) - checkpoint, err := p.processIssue(ctx, issue) + pc, err := p.processIssue(ctx, issue) if err != nil { var rle *roleLoadError if errors.As(err, &rle) { @@ -166,7 +167,8 @@ func (p *Poller) Run(ctx context.Context) error { processErrors++ continue } - pending = append(pending, pendingCheckpoint{issueKey: issue.Key, t: checkpoint, records: p.dispatches[start:len(p.dispatches):len(p.dispatches)]}) + p.dispatches = append(p.dispatches, pc.records...) + pending = append(pending, pc) } if processErrors > 0 && processErrors == len(selected) { return fmt.Errorf("all %d selected issues failed to process", processErrors) @@ -288,9 +290,10 @@ func (p *Poller) Run(ctx context.Context) error { return nil } -// pendingCheckpoint holds a computed lastCheck value for an issue, deferred -// until the dispatch file write succeeds (see Run), together with the -// dispatch records the issue produced this cycle. A zero t means there is +// pendingCheckpoint is what one look at an issue produced: its dispatch +// records and the lastCheck value to commit once the dispatch file write +// succeeds (see Run). Run takes or leaves it whole, so an issue's records +// never go out without its checkpoint or in part. A zero t means there is // no checkpoint to advance. type pendingCheckpoint struct { issueKey string @@ -500,27 +503,30 @@ func selectRandom(items []jira.Issue, n int) []jira.Issue { return items[:n] } -// processIssue confirms write access, detects changes, converts, routes, -// and dispatches. It returns the checkpoint value the caller should advance -// lastCheck to once the dispatch file has been durably written (zero if -// there is nothing to advance) — it does not commit the checkpoint itself. -func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (time.Time, error) { +// processIssue confirms write access, detects changes, converts and +// matches. It returns the issue's dispatch records with the checkpoint value +// the caller should advance lastCheck to once the dispatch file has been +// durably written (zero if there is nothing to advance). It neither adds the +// records to the cycle nor commits the checkpoint: the caller takes the +// result whole or not at all. +func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (pendingCheckpoint, error) { + pc := pendingCheckpoint{issueKey: issue.Key} // Confirm write access before reading the issue's comments and history // (ADR 0085, Decision item 1). A failure yields no records: Run warns // and goes on, and a cycle in which every issue fails ends in an error. if err := p.checkWriteAccess(ctx, issue.Key); err != nil { - return time.Time{}, fmt.Errorf("check write access to %s: %w", issue.Key, err) + return pendingCheckpoint{}, fmt.Errorf("check write access to %s: %w", issue.Key, err) } // Read lastCheck. lastCheck, err := p.readLastCheck(ctx, issue.Key) if err != nil { - return time.Time{}, fmt.Errorf("read lastCheck for %s: %w", issue.Key, err) + return pendingCheckpoint{}, fmt.Errorf("read lastCheck for %s: %w", issue.Key, err) } // Detect changes. result, err := p.detectChanges(ctx, issue, lastCheck) if err != nil { - return time.Time{}, fmt.Errorf("detect changes for %s: %w", issue.Key, err) + return pendingCheckpoint{}, fmt.Errorf("detect changes for %s: %w", issue.Key, err) } // The checkpoint is result.maxSeen and nothing else. maxSeen already @@ -534,9 +540,9 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (time.Time, // lastCheck, skip the advance entirely (return zero) rather than // regressing the checkpoint; the next cycle re-detects the same // in-margin activity — a harmless, self-correcting duplicate. - checkpoint := result.maxSeen - if !checkpoint.After(lastCheck) { - checkpoint = time.Time{} + pc.t = result.maxSeen + if !pc.t.After(lastCheck) { + pc.t = time.Time{} } if len(result.events) == 0 { @@ -544,7 +550,7 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (time.Time, // with unsupported fields; the checkpoint (zero if nothing was // seen at all) still needs to advance past them so the poller // does not re-scan the same updates every cycle. - return checkpoint, nil + return pc, nil } // Deduplicate. @@ -587,9 +593,9 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (time.Time, if err := p.resolveEventRoles(ctx, events); err != nil { var rle *roleLoadError if errors.As(err, &rle) { - return time.Time{}, err + return pendingCheckpoint{}, err } - return time.Time{}, fmt.Errorf("resolve actor roles for %s: %w", issue.Key, err) + return pendingCheckpoint{}, fmt.Errorf("resolve actor roles for %s: %w", issue.Key, err) } // Convert, match harness triggers, dispatch. An event that fails @@ -637,11 +643,11 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (time.Time, p.eventsMatchErrors++ continue } - p.dispatches = append(p.dispatches, records...) + pc.records = append(pc.records, records...) } } - return checkpoint, nil + return pc, nil } // deduplicate removes duplicate events based on their Key(). diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index b38ba0ee70..f33f7e3954 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -563,3 +563,25 @@ func TestDetectChangesMaxSeenReachesUpdated(t *testing.T) { }) } } + +// processIssue hands back an issue's records together with its checkpoint +// and adds nothing to the cycle itself, so Run takes or leaves an issue's +// records as one unit. +func TestProcessIssueReturnsRecordsAsOneUnit(t *testing.T) { + now := time.Now().Truncate(time.Second) + mc := newMockClient() + addTriageComment(mc, "PROJ-1", "501", now.Add(-2*time.Minute)) + addTriageComment(mc, "PROJ-1", "502", now.Add(-time.Minute)) + p := idleTestPoller(mc, t) + + pc, err := p.processIssue(context.Background(), idleTestIssue(1, now.Add(-48*time.Hour), now.Add(-time.Minute))) + if err != nil { + t.Fatalf("processIssue() error: %v", err) + } + if len(p.dispatches) != 0 { + t.Errorf("processIssue added %d records to the cycle, want 0", len(p.dispatches)) + } + if pc.issueKey != "PROJ-1" || pc.t.IsZero() || len(pc.records) != 2 { + t.Errorf("processIssue() = key %q, checkpoint %v, %d records; want PROJ-1, a checkpoint and both comments' records", pc.issueKey, pc.t, len(pc.records)) + } +} diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index 5e8f90470d..db80bd1f7b 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -732,17 +732,17 @@ func TestProcessIssue_CheckpointNeverRegresses(t *testing.T) { Created: now.Add(-1 * time.Hour).Format("2006-01-02T15:04:05.000-0700"), }, } - checkpoint, err := p.processIssue(context.Background(), issue) + pc, err := p.processIssue(context.Background(), issue) if err != nil { t.Fatalf("processIssue() error: %v", err) } // The clamp puts maxSeen ~10s before now, which is before the stored // lastCheck — the returned checkpoint must be zero (skip advance), not // an earlier-than-stored value. - if !checkpoint.IsZero() && checkpoint.Before(storedLastCheck) { - t.Errorf("checkpoint %v regresses behind stored lastCheck %v; expected zero (skip)", checkpoint, storedLastCheck) + if !pc.t.IsZero() && pc.t.Before(storedLastCheck) { + t.Errorf("checkpoint %v regresses behind stored lastCheck %v; expected zero (skip)", pc.t, storedLastCheck) } - if len(p.dispatches) == 0 { + if len(pc.records) == 0 { t.Error("expected the comment after lastCheck to still dispatch") } } @@ -1072,7 +1072,7 @@ func TestProcessIssue_CapsEventsPerIssue(t *testing.T) { JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ", }) - if _, err := p.processIssue(context.Background(), jira.Issue{ + pc, err := p.processIssue(context.Background(), jira.Issue{ ID: "10042", Key: "PROJ-123", Fields: jira.IssueFields{ @@ -1080,13 +1080,14 @@ func TestProcessIssue_CapsEventsPerIssue(t *testing.T) { Reporter: jira.User{AccountID: "reporter-id"}, Created: now.Add(-2 * time.Hour).Format("2006-01-02T15:04:05.000-0700"), }, - }); err != nil { + }) + if err != nil { // seed a lastCheck so it's not a first poll _ = lastCheck t.Fatalf("processIssue() error: %v", err) } - if len(p.dispatches) != maxEventsPerIssue { - t.Errorf("dispatched %d records, want capped at %d", len(p.dispatches), maxEventsPerIssue) + if len(pc.records) != maxEventsPerIssue { + t.Errorf("dispatched %d records, want capped at %d", len(pc.records), maxEventsPerIssue) } } From f2c408cb4b4abd1b67d7cbacb96208c041e9d5ed Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 25 Nov 2026 09:47:21 +0200 Subject: [PATCH 04/37] feat(jirapoll): limit reading to 5 minutes per cycle and 2 per issue Implements the time limits of ADR 0085 Decision item 3. - Run reads under a context that ends CycleTimeLimit (5m) after the cycle starts: the auth preflight, the search, the activity filter and the selected issues. Each issue is read under its own IssueTimeLimit (2m) context. Dispatching and committing checkpoints keep the caller's context, so they get the rest of the job's time. - An issue over its limit is a failed read: a WARNING names it, none of its records are taken and its lastCheck stays, and the next issue is read. When the cycle limit is reached the issue being read and those not reached wait for the next cycle, and the cycle dispatches and commits what it finished and exits normally. - A cycle that serves none of its selected issues fails: the existing "all N selected issues failed to process" error, or a new one when the cycle limit ended reading first. - The Jira guide describes the limits. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 + internal/jirapoll/poller.go | 65 ++++++++++--- internal/jirapoll/poller_idle_test.go | 130 ++++++++++++++++++++++++++ internal/jirapoll/poller_test.go | 3 + internal/jirapoll/types.go | 2 + 5 files changed, 188 insertions(+), 14 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 65ef5f60a2..5688c5e7ae 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1442,6 +1442,8 @@ The poller uses Jira entity properties for checkpoint tracking. It keeps no per- 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. +**Time limits.** A cycle stops reading from Jira five minutes after it starts: the authentication check, the search, the activity filter and the selected issues all count. Reading one issue stops after two minutes. An issue that takes longer is skipped with `WARNING: reading took longer than 2m0s; ...`: none of its records are dispatched and its `lastCheck` stays where it was, so it is tried again next cycle. When the five minutes run out, the poller dispatches what it finished, commits those checkpoints and exits normally; the issue it was reading and any it had not reached wait for the next cycle, and the run log names them or says how many. Dispatching and committing are not counted against the five minutes. A cycle that serves none of its selected issues, because they all failed or ran into these limits, fails. The limits are not configurable. + > **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` property. The driver treats it 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`. Three edge cases of checkpoint tracking are worth knowing: diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 9520fe2a6e..2b4f35754e 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -83,6 +83,12 @@ func New(client JiraClient, matcher EventMatcher, opts Options) *Poller { if opts.FirstPollBackfillWindow == 0 { opts.FirstPollBackfillWindow = 24 * time.Hour } + if opts.CycleTimeLimit == 0 { + opts.CycleTimeLimit = 5 * time.Minute + } + if opts.IssueTimeLimit == 0 { + opts.IssueTimeLimit = 2 * time.Minute + } return &Poller{ client: client, matcher: matcher, @@ -94,6 +100,14 @@ func New(client JiraClient, matcher EventMatcher, opts Options) *Poller { // cycles for one target repository from overlapping: with no lock, they // would dispatch the same requests twice (ADR 0085, Decision item 1). func (p *Poller) Run(ctx context.Context) error { + // Reading — the preflight, the search, the activity filter and every + // issue — must finish within CycleTimeLimit of the cycle's start, and + // one issue within IssueTimeLimit (ADR 0085, Decision item 3). The + // dispatch and checkpoint commit after it use ctx, so they get the rest + // of the job's time. + readCtx, cancelRead := context.WithTimeout(ctx, p.opts.CycleTimeLimit) + defer cancelRead() + p.dispatches = nil p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors = 0, 0, 0 p.statusCategoryCache = make(map[string]string) @@ -107,7 +121,7 @@ func (p *Poller) Run(ctx context.Context) error { // checkpoint operations. Without this, bad credentials cause Jira to // treat the request as unauthenticated and return empty results — // indistinguishable from a genuinely quiet project. - myself, err := p.client.GetMyself(ctx) + myself, err := p.client.GetMyself(readCtx) if err != nil { return fmt.Errorf("authentication preflight failed: %w", err) } @@ -122,7 +136,7 @@ func (p *Poller) Run(ctx context.Context) error { p.selfAccountID = userID(*myself) // Step 1: Execute JQL to get candidate issues. - candidates, err := p.searchCandidates(ctx) + candidates, err := p.searchCandidates(readCtx) if err != nil { return fmt.Errorf("search candidates: %w", err) } @@ -130,7 +144,7 @@ func (p *Poller) Run(ctx context.Context) error { // Step 2: 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 := p.filterActive(ctx, candidates) + active := p.filterActive(readCtx, candidates) // Step 3: Randomly select min(N, len(active)) candidates. selected := selectRandom(active, p.opts.N) @@ -149,29 +163,52 @@ func (p *Poller) Run(ctx context.Context) error { // candidate checkpoint per issue; processIssue returns it (zero if // there's nothing to advance) together with the issue's records, this // loop adds the two to the cycle as one unit, and Step 6 below commits - // the checkpoint only after - // Step 5's dispatch-file write has durably succeeded. Committing here - // instead would mean a local write failure permanently loses every - // event this cycle found: the checkpoint would already be past them in - // Jira with no record of them ever written anywhere. + // the checkpoint only after Step 5's dispatch-file write has durably + // succeeded. Committing here instead would mean a local write failure + // permanently loses every event this cycle found: the checkpoint would + // already be past them in Jira with no record of them ever written + // anywhere. An issue that times out, or that the cycle limit cuts off, + // contributes neither records nor a checkpoint, so its requests stay + // eligible next cycle. var pending []pendingCheckpoint - var processErrors int + var processErrors, tried int for _, issue := range selected { - pc, err := p.processIssue(ctx, issue) + if readCtx.Err() != nil { + break + } + tried++ + issueCtx, cancelIssue := context.WithTimeout(readCtx, p.opts.IssueTimeLimit) + pc, err := p.processIssue(issueCtx, issue) + issueTimedOut := errors.Is(issueCtx.Err(), context.DeadlineExceeded) + cancelIssue() if err != nil { var rle *roleLoadError - if errors.As(err, &rle) { + switch { + case errors.Is(readCtx.Err(), context.DeadlineExceeded): + log.Printf("WARNING: the %s cycle time limit cut off reading %s; it waits for the next cycle", p.opts.CycleTimeLimit, issue.Key) + case issueTimedOut: + log.Printf("WARNING: reading %s took longer than %s; none of its records were taken and its lastCheck was not advanced", issue.Key, p.opts.IssueTimeLimit) + case errors.As(err, &rle): return fmt.Errorf("load project roles for %s: %w", p.opts.JiraProject, rle.err) + default: + log.Printf("WARNING: processing %s: %v", issue.Key, err) } - log.Printf("WARNING: processing %s: %v", issue.Key, err) processErrors++ continue } p.dispatches = append(p.dispatches, pc.records...) pending = append(pending, pc) } - if processErrors > 0 && processErrors == len(selected) { - return fmt.Errorf("all %d selected issues failed to process", processErrors) + if left := len(selected) - tried; left > 0 { + log.Printf("WARNING: the %s cycle time limit was reached with %d selected issue(s) not read; they wait for the next cycle", p.opts.CycleTimeLimit, left) + } + // A cycle that served no selected issue fails, so a poller blocked by + // failing or slow issues shows as a failed run. + if len(selected) > 0 && len(pending) == 0 { + if processErrors == len(selected) { + return fmt.Errorf("all %d selected issues failed to process", processErrors) + } + return fmt.Errorf("the %s cycle time limit was reached before any selected issue was read (%d of %d tried, all failed or timed out)", p.opts.CycleTimeLimit, tried, len(selected)) } // Step 5: Write dispatch records. diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index f33f7e3954..f2fb9bb505 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -585,3 +585,133 @@ func TestProcessIssueReturnsRecordsAsOneUnit(t *testing.T) { t.Errorf("processIssue() = key %q, checkpoint %v, %d records; want PROJ-1, a checkpoint and both comments' records", pc.issueKey, pc.t, len(pc.records)) } } + +// slowClient blocks ListComments on the issues in slow until the call's +// context ends, like a Jira read that never returns, and fails a property +// write made with an ended context, so a commit that wrongly used the +// cycle's read context would fail. +type slowClient struct { + *mockClient + slow map[string]bool +} + +func (c slowClient) ListComments(ctx context.Context, key string) ([]jira.Comment, error) { + if c.slow[key] { + <-ctx.Done() + return nil, ctx.Err() + } + return c.mockClient.ListComments(ctx, key) +} + +func (c slowClient) SetEntityProperty(ctx context.Context, issueKey, propKey string, value any) error { + if err := ctx.Err(); err != nil { + return err + } + return c.mockClient.SetEntityProperty(ctx, issueKey, propKey, value) +} + +// timeLimitPoller returns a poller over two issues, PROJ-1 then PROJ-2, each +// with a fresh triage comment. With two active issues and N = 5 the pick +// keeps the search order. +func timeLimitPoller(t *testing.T, mc *mockClient, slow map[string]bool, cycle, issue time.Duration) *Poller { + now := time.Now().Truncate(time.Second) + if len(mc.searchResult) == 0 { + for n := 1; n <= 2; n++ { + mc.searchResult = append(mc.searchResult, idleTestIssue(n, now.Add(-48*time.Hour), now.Add(-time.Minute))) + addTriageComment(mc, fmt.Sprintf("PROJ-%d", n), fmt.Sprintf("50%d", n), now.Add(-time.Minute)) + } + } + return newTestPoller(slowClient{mc, slow}, &stubMatcher{agents: []string{"triage"}}, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProject: "PROJ", + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + CycleTimeLimit: cycle, + IssueTimeLimit: issue, + }) +} + +// An issue that takes longer than the per-issue limit is treated as a +// failed read: a WARNING names it, none of its records are taken, its +// lastCheck stays, and the next issue is served (ADR 0085, Decision +// item 3). +func TestRunIssueTimeLimit(t *testing.T) { + logs := captureLog(t) + mc := newMockClient() + p := timeLimitPoller(t, mc, map[string]bool{"PROJ-1": true}, time.Hour, 50*time.Millisecond) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if got := dispatchedKeys(p); len(got) != 1 || got[0] != "10002" { + t.Errorf("dispatched for %v, want PROJ-2 only", got) + } + if !storedLastCheckAt(t, mc, "PROJ-1").IsZero() { + t.Error("the timed-out issue's lastCheck advanced") + } + if storedLastCheckAt(t, mc, "PROJ-2").IsZero() { + t.Error("the served issue's lastCheck was not committed") + } + if want := "WARNING: reading PROJ-1 took longer than 50ms"; !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } +} + +// The cycle limit stops reading mid-issue: the cycle dispatches and commits +// what it finished and exits normally, and the cut-off issue's request is +// served by the next cycle. +func TestRunCycleTimeLimitLeavesRestForNextCycle(t *testing.T) { + logs := captureLog(t) + mc := newMockClient() + p := timeLimitPoller(t, mc, map[string]bool{"PROJ-2": true}, 200*time.Millisecond, time.Hour) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("cycle 1: %v", err) + } + if got := dispatchedKeys(p); len(got) != 1 || got[0] != "10001" { + t.Errorf("cycle 1 dispatched for %v, want PROJ-1 only", got) + } + if storedLastCheckAt(t, mc, "PROJ-1").IsZero() { + t.Error("cycle 1 did not commit PROJ-1's lastCheck after the read limit passed") + } + if !storedLastCheckAt(t, mc, "PROJ-2").IsZero() { + t.Error("cycle 1 advanced the cut-off issue's lastCheck") + } + if want := "WARNING: the 200ms cycle time limit cut off reading PROJ-2"; !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + + p = timeLimitPoller(t, mc, nil, time.Hour, time.Hour) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("cycle 2: %v", err) + } + if got := dispatchedKeys(p); len(got) != 1 || got[0] != "10002" { + t.Errorf("cycle 2 dispatched for %v, want the request cycle 1 left: PROJ-2", got) + } +} + +// A cycle that serves no selected issue because of the time limits fails, so +// a poller blocked by slow issues shows as a failed run. +func TestRunTimeLimitsServingNothingFailCycle(t *testing.T) { + t.Run("cycle limit on the first issue", func(t *testing.T) { + logs := captureLog(t) + mc := newMockClient() + p := timeLimitPoller(t, mc, map[string]bool{"PROJ-1": true}, 100*time.Millisecond, time.Hour) + err := p.Run(context.Background()) + if err == nil || !strings.Contains(err.Error(), "cycle time limit was reached before any selected issue was read (1 of 2 tried") { + t.Fatalf("Run() error = %v, want the cycle-limit failure", err) + } + if want := "1 selected issue(s) not read"; !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + if mc.listCommentsCalls["PROJ-2"] != 0 { + t.Error("read PROJ-2 after the cycle limit") + } + }) + t.Run("every issue over the per-issue limit", func(t *testing.T) { + mc := newMockClient() + p := timeLimitPoller(t, mc, map[string]bool{"PROJ-1": true, "PROJ-2": true}, time.Hour, 20*time.Millisecond) + err := p.Run(context.Background()) + if err == nil || !strings.Contains(err.Error(), "all 2 selected issues failed to process") { + t.Fatalf("Run() error = %v, want the all-failed guard", err) + } + }) +} diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index db80bd1f7b..f188f6b3d8 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -303,6 +303,9 @@ func TestNew(t *testing.T) { if p.opts.N != 5 { t.Errorf("N = %d, want default 5", p.opts.N) } + if p.opts.CycleTimeLimit != 5*time.Minute || p.opts.IssueTimeLimit != 2*time.Minute { + t.Errorf("time limits = %v per cycle, %v per issue; want the ADR 0085 defaults 5m and 2m", p.opts.CycleTimeLimit, p.opts.IssueTimeLimit) + } } func TestRunEmptyPoll(t *testing.T) { diff --git a/internal/jirapoll/types.go b/internal/jirapoll/types.go index b0a0418f53..963bbe2059 100644 --- a/internal/jirapoll/types.go +++ b/internal/jirapoll/types.go @@ -66,6 +66,8 @@ type Options struct { M int // Max candidate issues per cycle (default: 50) N int // Max issues to process per cycle (default: 5) FirstPollBackfillWindow time.Duration // How far back to backfill comments/changelog on an issue's first poll (default: 24h) + CycleTimeLimit time.Duration // Reading budget per cycle, from its start through the last issue read (default: 5m, ADR 0085) + IssueTimeLimit time.Duration // Reading budget per issue (default: 2m, ADR 0085) // Authorization holds the jira authorization provider from // config.yaml. The zero value (no provider entry) resolves every event From a8cfc1ce511a630e098dd46a31e2af5a3e44c4fb Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 03:29:16 +0200 Subject: [PATCH 05/37] feat(jirapoll): take each candidate's lastCheck from the search results Implements the checkpoint clause of ADR 0085 Decision item 2. The activity filter read every candidate's lastCheck property with its own call; the search now returns it with each row, so the filter makes no call of its own. Processing still reads lastCheck from the issue. - jira.LiveClient.SearchIssues takes the names of entity properties to return (the search/jql "properties" parameter) and decodes them into the new Issue.Properties. - searchCandidates asks for the target's lastCheck key. hasNewActivity parses the row's value with the new parseLastCheck, split out of loadLastCheck, and fails open as before: a row without the property, or with one that does not parse, is active. filterActive and hasNewActivity drop their context argument. - jiramock's search returns the requested properties an issue has, as Jira does. - The Jira guide and the behaviour-testing guide describe the change. Signed-off-by: guy oron --- docs/guides/dev/behaviour-testing.md | 6 ++ docs/guides/user/jira-integration.md | 4 +- internal/forge/jira/client.go | 8 ++- internal/forge/jira/client_test.go | 31 +++++++++ internal/forge/jira/types.go | 4 ++ internal/jirapoll/lock.go | 14 ++-- internal/jirapoll/poller.go | 33 +++++---- internal/jirapoll/poller_idle_test.go | 69 +++++++++++++------ internal/jirapoll/poller_invalid_id_test.go | 2 +- internal/jirapoll/poller_test.go | 27 ++++++-- internal/jirapoll/types.go | 5 +- pkg/behaviourtest/drivers/jiramock/server.go | 20 +++++- .../drivers/jiramock/server_test.go | 29 ++++++++ 13 files changed, 203 insertions(+), 49 deletions(-) diff --git a/docs/guides/dev/behaviour-testing.md b/docs/guides/dev/behaviour-testing.md index 72b25f9f02..7125aee1d0 100644 --- a/docs/guides/dev/behaviour-testing.md +++ b/docs/guides/dev/behaviour-testing.md @@ -1926,4 +1926,10 @@ 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. +**`jiramock` search properties change:** the search endpoint now returns the +entity properties named in the request's `properties` list that an issue +has, in each row's `properties` object, as Jira does. The Jira poller reads +each candidate's `lastCheck` from there, so the mock must serve it. A search +that names no properties is served as before. + 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 5688c5e7ae..f15a9eb0b5 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1435,7 +1435,7 @@ matches it. Use `labels: allowlist` if that group is broader than you want. ## Poll coordination -The poller uses Jira entity properties for checkpoint tracking. It keeps no per-issue lock: it relies on one poll cycle at a time per target repository (see [Scheduled workflow](#scheduled-workflow)). 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 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 checkpoint tracking. It keeps no per-issue lock: it relies on one poll cycle at a time per target repository (see [Scheduled workflow](#scheduled-workflow)). 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`, which the search returns with each row, clamped as described below; a candidate with no usable `lastCheck` (missing, unreadable, or in the future) or no usable `updated` time counts as new. Two properties are stored on each processed issue: - **Write check** (`fullsend.poll.{owner}.{repo}.writeCheck`) — written before the poller reads an issue's comments and history, to confirm the credential can write to the issue and so commit its `lastCheck`; nothing reads it. An issue that fails the check is skipped with `WARNING: processing : check write access to : ...`, and a cycle in which every selected issue fails ends in an error, so a credential that cannot write shows as a failed run. Earlier versions kept a lock at `fullsend.poll.{owner}.{repo}.lock`; the poller no longer reads, writes or removes it. - **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. @@ -1476,7 +1476,7 @@ 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. The activity filter adds one property read per candidate (at most M per cycle); a candidate with nothing new costs no property write, no comment or changelog listing and no `lastCheck` write. Each selected issue costs one property write for the write-access check. +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 search returns each candidate's `lastCheck` with its row, so the activity filter makes no call of its own; a candidate with nothing new costs no property read or write and no comment or changelog listing. A selected issue's `lastCheck` is still read from the issue before it is processed. Each selected issue costs one property write for the write-access check. Two more scaling limits: diff --git a/internal/forge/jira/client.go b/internal/forge/jira/client.go index 43491ab817..33335c452b 100644 --- a/internal/forge/jira/client.go +++ b/internal/forge/jira/client.go @@ -524,6 +524,7 @@ type searchRequest struct { MaxResults int `json:"maxResults"` Fields []string `json:"fields"` NextPageToken string `json:"nextPageToken,omitempty"` + Properties []string `json:"properties,omitempty"` } // searchFields lists the issue fields SearchIssues requests. The poller @@ -553,6 +554,10 @@ const maxSearchPages = 200 // maxSearchPages pages (10,000 issues at 50 per page) to prevent unbounded // memory growth. // +// properties names issue entity properties to return with each issue in +// Issue.Properties (Jira returns at most five), so a caller that needs one +// property per issue does not read it with a call per issue. +// // This endpoint is eventually consistent: Atlassian documents that recent // updates might not be immediately visible in results. For the poller that // means an issue can appear, re-sort under ORDER BY updated, or show a @@ -563,7 +568,7 @@ const maxSearchPages = 200 // 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) { +func (c *LiveClient) SearchIssues(ctx context.Context, jql string, limit int, properties ...string) ([]Issue, error) { var all []Issue var nextPageToken string for page := 0; page < maxSearchPages; page++ { @@ -576,6 +581,7 @@ func (c *LiveClient) SearchIssues(ctx context.Context, jql string, limit int) ([ MaxResults: 50, Fields: searchFields, NextPageToken: nextPageToken, + Properties: properties, } bodyJSON, err := json.Marshal(body) if err != nil { diff --git a/internal/forge/jira/client_test.go b/internal/forge/jira/client_test.go index 140ca01c4e..203ac94a7e 100644 --- a/internal/forge/jira/client_test.go +++ b/internal/forge/jira/client_test.go @@ -241,6 +241,37 @@ func TestSearchIssues_Pagination(t *testing.T) { assert.Equal(t, "PROJ-120", issues[119].Key) } +// SearchIssues asks for the named entity properties on every page and +// decodes them into Issue.Properties; without names it asks for none. +func TestSearchIssues_Properties(t *testing.T) { + t.Parallel() + client, mux := setupTest(t) + ctx := context.Background() + + var asked [][]string + mux.HandleFunc("/rest/api/3/search/jql", func(w http.ResponseWriter, r *http.Request) { + var body map[string]json.RawMessage + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + var props []string + if raw, ok := body["properties"]; ok { + require.NoError(t, json.Unmarshal(raw, &props)) + } + asked = append(asked, props) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"issues":[{"id":"1","key":"PROJ-1","fields":{},"properties":{"fullsend.poll.acme.platform.lastCheck":"2026-11-25T10:00:00Z"}},{"id":"2","key":"PROJ-2","fields":{}}],"isLast":true}`)) + }) + + issues, err := client.SearchIssues(ctx, "project = PROJ", 0, "fullsend.poll.acme.platform.lastCheck") + require.NoError(t, err) + require.Len(t, issues, 2) + assert.JSONEq(t, `"2026-11-25T10:00:00Z"`, string(issues[0].Properties["fullsend.poll.acme.platform.lastCheck"])) + assert.Nil(t, issues[1].Properties) + + _, err = client.SearchIssues(ctx, "project = PROJ", 0) + require.NoError(t, err) + assert.Equal(t, [][]string{{"fullsend.poll.acme.platform.lastCheck"}, nil}, asked) +} + // --------------------------------------------------------------------------- // ListComments pagination // --------------------------------------------------------------------------- diff --git a/internal/forge/jira/types.go b/internal/forge/jira/types.go index d72332080d..92747ada60 100644 --- a/internal/forge/jira/types.go +++ b/internal/forge/jira/types.go @@ -12,6 +12,10 @@ type Issue struct { Key string `json:"key"` Self string `json:"self"` Fields IssueFields `json:"fields"` + // Properties holds the issue entity properties SearchIssues was asked + // to return, keyed by property key. A property the issue does not have + // is absent. + Properties map[string]json.RawMessage `json:"properties,omitempty"` } // CreatedIssue is the response from POST /rest/api/3/issue. diff --git a/internal/jirapoll/lock.go b/internal/jirapoll/lock.go index e87e307cfe..89e56e7a42 100644 --- a/internal/jirapoll/lock.go +++ b/internal/jirapoll/lock.go @@ -99,7 +99,7 @@ func splitOwnerRepo(slug string) (string, string) { } // readLastCheck reads the lastCheck timestamp for an issue, clamped as -// loadLastCheck describes, and logs a WARNING when it clamps. +// parseLastCheck 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 { @@ -131,9 +131,8 @@ type storedLastCheck struct { 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. +// loadLastCheck reads an issue's lastCheck property and parses it with +// parseLastCheck, without logging. func (p *Poller) loadLastCheck(ctx context.Context, issueKey string) (storedLastCheck, error) { propKey := p.lastCheckKey() @@ -144,6 +143,13 @@ func (p *Poller) loadLastCheck(ctx context.Context, issueKey string) (storedLast } return storedLastCheck{}, fmt.Errorf("get lastCheck property: %w", err) } + return p.parseLastCheck(raw) +} + +// parseLastCheck parses and clamps a stored lastCheck value without +// logging, so the activity filter can report the clamps once per cycle +// instead of once per issue. An empty value is unset. +func (p *Poller) parseLastCheck(raw json.RawMessage) (storedLastCheck, error) { if len(raw) == 0 { return storedLastCheck{}, nil } diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 2b4f35754e..e647411eee 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -144,7 +144,7 @@ func (p *Poller) Run(ctx context.Context) error { // Step 2: 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 := p.filterActive(readCtx, candidates) + active := p.filterActive(candidates) // Step 3: Randomly select min(N, len(active)) candidates. selected := selectRandom(active, p.opts.N) @@ -435,18 +435,20 @@ func (p *Poller) searchCandidates(ctx context.Context) ([]jira.Issue, error) { jql = fmt.Sprintf("project = %q AND statusCategory != Done ORDER BY updated DESC", p.opts.JiraProject) } - return p.client.SearchIssues(ctx, jql, p.opts.M) + // The search returns each candidate's lastCheck, so the activity + // filter reads no property per candidate (ADR 0085, Decision item 2). + return p.client.SearchIssues(ctx, jql, p.opts.M, p.lastCheckKey()) } // filterActive keeps the candidates with new activity (see hasNewActivity) // and logs the cycle's clamped lastCheck values once. It neither reads nor // writes lock properties, including those left by earlier versions // (ADR 0085, Decision item 1). -func (p *Poller) filterActive(ctx context.Context, issues []jira.Issue) []jira.Issue { +func (p *Poller) filterActive(issues []jira.Issue) []jira.Issue { var active []jira.Issue var clamped clampReport for _, issue := range issues { - if p.hasNewActivity(ctx, issue, &clamped) { + if p.hasNewActivity(issue, &clamped) { active = append(active, issue) } } @@ -455,16 +457,19 @@ func (p *Poller) filterActive(ctx context.Context, issues []jira.Issue) []jira.I } // 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). -// 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) +// its updated value from the search row is after the lastCheck the search +// returned with it (ADR 0085, Decision item 2), clamped exactly as +// processIssue's read clamps it (ADR 0160, Decision item 1). The search's +// value only decides whether to skip the issue; processing reads lastCheck +// from the issue again. It fails open: an issue whose lastCheck the search +// did not return or that cannot be parsed, or that has no usable updated +// value, is active, so neither a search that drops the property nor an +// editor writing garbage can hide an issue. A parse 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(issue jira.Issue, clamped *clampReport) bool { + lc, err := p.parseLastCheck(issue.Properties[p.lastCheckKey()]) if err != nil { return true } diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index f2fb9bb505..19463ba229 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -324,8 +324,10 @@ func TestRunGarbageLastCheckAloneFailsCycle(t *testing.T) { } // 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. +// item 1), with lastCheck taken from the search row (ADR 0085, Decision +// item 2): only an issue whose usable lastCheck is at or after its updated +// value is dropped; every error and unset case keeps the issue. The filter +// reads no property itself. func TestFilterLockedActivityDecision(t *testing.T) { now := time.Now().Truncate(time.Second) key := lastCheckPropertyKey("acme", "platform") @@ -336,12 +338,10 @@ func TestFilterLockedActivityDecision(t *testing.T) { elsewhere := time.FixedZone("UTC-5", -5*3600) cases := []struct { name string - stored json.RawMessage // nil: no property - readErr bool + stored json.RawMessage // nil: the search returned no property 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}, @@ -361,14 +361,12 @@ func TestFilterLockedActivityDecision(t *testing.T) { 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") - } + mc.getPropertyHook = func(issueKey, propKey string) { t.Errorf("filter read %s of %s", propKey, issueKey) } + issue := jira.Issue{ID: "10001", Key: "PROJ-1", Fields: jira.IssueFields{Updated: tc.updated}} if tc.stored != nil { - mc.properties["PROJ-1"] = map[string]json.RawMessage{key: tc.stored} + issue.Properties = map[string]json.RawMessage{key: tc.stored} } - issue := jira.Issue{ID: "10001", Key: "PROJ-1", Fields: jira.IssueFields{Updated: tc.updated}} - active := idleTestPoller(mc, t).filterActive(context.Background(), []jira.Issue{issue}) + active := idleTestPoller(mc, t).filterActive([]jira.Issue{issue}) if got := len(active) == 1; got != tc.active { t.Errorf("active = %v, want %v", got, tc.active) } @@ -389,18 +387,15 @@ func TestFilterLockedGitLabTargetReadsItsOwnKey(t *testing.T) { } 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 := p.filterActive(context.Background(), []jira.Issue{issue}); len(active) != 0 { + stamp, _ := json.Marshal(now.Add(-time.Hour).UTC().Format(time.RFC3339Nano)) + p := newTestPoller(newMockClient(), nil, opts) + issue.Properties = map[string]json.RawMessage{p.lastCheckKey(): stamp} + if active := p.filterActive([]jira.Issue{issue}); len(active) != 0 { t.Errorf("lastCheck equal to updated under the GitLab key: active %v; want idle", active) } - mc = newMockClient() - setLastCheck(mc, issue.Key, "group", "project", now.Add(-time.Hour)) - if active := newTestPoller(mc, nil, opts).filterActive(context.Background(), []jira.Issue{issue}); len(active) != 1 { + issue.Properties = map[string]json.RawMessage{lastCheckPropertyKey("group", "project"): stamp} + if active := p.filterActive([]jira.Issue{issue}); len(active) != 1 { t.Errorf("lastCheck only under the GitHub-style key: active %v; want active", active) } } @@ -715,3 +710,37 @@ func TestRunTimeLimitsServingNothingFailCycle(t *testing.T) { } }) } + +// The search returns each candidate's lastCheck, so an idle candidate costs +// no property read (ADR 0085, Decision item 2); a picked issue's lastCheck +// is still read from the issue before processing. +func TestRunTakesLastCheckFromSearch(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)), + idleTestIssue(2, now.Add(-48*time.Hour), now.Add(-time.Minute)), + } + setLastCheck(mc, "PROJ-1", "acme", "platform", now.Add(-time.Hour)) + setLastCheck(mc, "PROJ-2", "acme", "platform", now.Add(-time.Hour)) + addTriageComment(mc, "PROJ-2", "502", now.Add(-time.Minute)) + reads := map[string]int{} + mc.getPropertyHook = func(issueKey, _ string) { reads[issueKey]++ } + + p := idleTestPoller(mc, t) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if got := mc.lastSearchProperties; len(got) != 1 || got[0] != lastCheckPropertyKey("acme", "platform") { + t.Errorf("search asked for properties %v, want only the lastCheck key", got) + } + if reads["PROJ-1"] != 0 { + t.Errorf("read %d properties of the idle PROJ-1, want 0", reads["PROJ-1"]) + } + if reads["PROJ-2"] == 0 { + t.Error("processing did not read PROJ-2's lastCheck from the issue") + } + if got := dispatchedKeys(p); len(got) != 1 || got[0] != "10002" { + t.Errorf("dispatched for %v, want PROJ-2 only", got) + } +} diff --git a/internal/jirapoll/poller_invalid_id_test.go b/internal/jirapoll/poller_invalid_id_test.go index f2979bda37..bf36b96755 100644 --- a/internal/jirapoll/poller_invalid_id_test.go +++ b/internal/jirapoll/poller_invalid_id_test.go @@ -154,7 +154,7 @@ type rawSearchClient struct { *mockClient } -func (c *rawSearchClient) SearchIssues(ctx context.Context, jql string, limit int) ([]jira.Issue, error) { +func (c *rawSearchClient) SearchIssues(ctx context.Context, jql string, limit int, properties ...string) ([]jira.Issue, error) { if c.searchErr != nil { return nil, c.searchErr } diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index f188f6b3d8..29a26def97 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -6,6 +6,7 @@ import ( "encoding/json" "fmt" "log" + "maps" "os" "path/filepath" "strings" @@ -32,6 +33,8 @@ type mockClient struct { lastQuery string lastLimit int + lastSearchProperties []string + issues map[string]*jira.Issue issueErr map[string]error @@ -101,9 +104,10 @@ func newMockClient() *mockClient { } } -func (m *mockClient) SearchIssues(_ context.Context, jql string, limit int) ([]jira.Issue, error) { +func (m *mockClient) SearchIssues(_ context.Context, jql string, limit int, properties ...string) ([]jira.Issue, error) { m.lastQuery = jql m.lastLimit = limit + m.lastSearchProperties = properties if m.searchErr != nil { return nil, m.searchErr } @@ -115,10 +119,25 @@ func (m *mockClient) SearchIssues(_ context.Context, jql string, limit int) ([]j m.searchResult[i].Fields.Labels = []string{} } } - if limit > 0 && len(m.searchResult) > limit { - return m.searchResult[:limit], nil + rows := m.searchResult + if limit > 0 && len(rows) > limit { + rows = rows[:limit] + } + // Like Jira, return each requested entity property the issue has. + out := make([]jira.Issue, len(rows)) + for i, issue := range rows { + for _, key := range properties { + if v, ok := m.properties[issue.Key][key]; ok { + issue.Properties = maps.Clone(issue.Properties) + if issue.Properties == nil { + issue.Properties = map[string]json.RawMessage{} + } + issue.Properties[key] = v + } + } + out[i] = issue } - return m.searchResult, nil + return out, nil } func (m *mockClient) GetIssue(_ context.Context, key string) (*jira.Issue, error) { diff --git a/internal/jirapoll/types.go b/internal/jirapoll/types.go index 963bbe2059..51255e62f9 100644 --- a/internal/jirapoll/types.go +++ b/internal/jirapoll/types.go @@ -15,8 +15,9 @@ type JiraClient interface { // SearchIssues executes a JQL search and returns up to limit matching // issues, stopping pagination once that many results are collected. // A limit <= 0 returns all matching issues (bounded by the - // implementation's own pagination cap). - SearchIssues(ctx context.Context, jql string, limit int) ([]jira.Issue, error) + // implementation's own pagination cap). Each issue carries the entity + // properties named in properties that it has, in Issue.Properties. + SearchIssues(ctx context.Context, jql string, limit int, properties ...string) ([]jira.Issue, error) GetIssue(ctx context.Context, issueIDOrKey string) (*jira.Issue, error) // GetStatus resolves a status name to its statusCategory, used to // classify status transitions (closed/reopened) without relying on diff --git a/pkg/behaviourtest/drivers/jiramock/server.go b/pkg/behaviourtest/drivers/jiramock/server.go index c438af3f34..379235754f 100644 --- a/pkg/behaviourtest/drivers/jiramock/server.go +++ b/pkg/behaviourtest/drivers/jiramock/server.go @@ -286,10 +286,28 @@ func handleSearch(w http.ResponseWriter, r *http.Request, s *State) { return } + // Like Jira, return each requested entity property an issue has. + var req struct { + Properties []string `json:"properties"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + http.Error(w, "bad search body: "+err.Error(), http.StatusBadRequest) + return + } + s.mu.Lock() issues := make([]jira.Issue, 0, len(s.issues)) for _, issue := range s.issues { - issues = append(issues, *issue) + row := *issue + for _, key := range req.Properties { + if v, ok := s.properties[row.Key][key]; ok { + if row.Properties == nil { + row.Properties = make(map[string]json.RawMessage) + } + row.Properties[key] = append(json.RawMessage(nil), v...) + } + } + issues = append(issues, row) } s.mu.Unlock() diff --git a/pkg/behaviourtest/drivers/jiramock/server_test.go b/pkg/behaviourtest/drivers/jiramock/server_test.go index 94a398fc42..75e264b644 100644 --- a/pkg/behaviourtest/drivers/jiramock/server_test.go +++ b/pkg/behaviourtest/drivers/jiramock/server_test.go @@ -30,6 +30,35 @@ func TestSearchReturnsAddedIssues(t *testing.T) { assert.Len(t, issues, 2) } +// Search returns each requested entity property an issue has, as Jira +// does, and no property it was not asked for. +func TestSearchReturnsRequestedProperties(t *testing.T) { + t.Parallel() + srv, state := NewServer() + defer srv.Close() + + state.AddIssue("PROJ-1", nil) + state.AddIssue("PROJ-2", nil) + + client, err := jira.New("test-token", jira.WithBaseURL(srv.URL)) + require.NoError(t, err) + ctx := context.Background() + require.NoError(t, client.SetEntityProperty(ctx, "PROJ-1", "acme.lastCheck", "2026-11-25T10:00:00Z")) + require.NoError(t, client.SetEntityProperty(ctx, "PROJ-1", "acme.other", "x")) + + issues, err := client.SearchIssues(ctx, "project = PROJ", 0, "acme.lastCheck") + require.NoError(t, err) + require.Len(t, issues, 2) + for _, issue := range issues { + switch issue.Key { + case "PROJ-1": + assert.Equal(t, map[string]json.RawMessage{"acme.lastCheck": json.RawMessage(`"2026-11-25T10:00:00Z"`)}, issue.Properties) + case "PROJ-2": + assert.Nil(t, issue.Properties) + } + } +} + // An issue without labels is served with "labels": [], as Jira serves it, // not null. func TestIssueWithoutLabelsHasEmptyList(t *testing.T) { From 95d4ad77920c21a7aa3caffda29a4108c2378df6 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 03:55:03 +0200 Subject: [PATCH 06/37] feat(jirapoll)!: search the whole backfill window, oldest change first Implements the pool of ADR 0085 Decision item 2, except the backfill_window_hours setting. - searchCandidates limits the configured query to the issues whose updated value falls within the backfill window, as () AND updated >= "-24h", and reads every row: Options.M and its 50-row limit go. - A query with no ORDER BY is sorted oldest change first (ORDER BY updated ASC). A query's own ORDER BY is kept, and ORDER BY updated DESC logs a WARNING once per cycle recommending oldest change first. The default query no longer carries a sort clause. - jira.SearchIssues returns ErrSearchTruncated with the issues it read when results remain after its 200-page cap (10,000 issues); the poller logs a WARNING and serves those rows, so a pool larger than the cap is not cut short silently. - The ORDER BY splitter moves from internal/config to the new internal/jql package so the poller can use it. - The Jira guide, the config reference and the custom poller example describe the window and the order, and their example queries drop the newest-first sort clause. BREAKING CHANGE: the default tracker.jira.poll.query is now "statusCategory != Done" with no ORDER BY, the poller reads issues oldest change first unless the query has its own ORDER BY, and it searches only issues updated within the last 24 hours, with no 50-row limit. A query that ends in ORDER BY updated DESC still works and logs a WARNING every cycle; remove the clause to get the recommended order. Signed-off-by: guy oron --- docs/guides/user/custom-poller-example.md | 5 +- docs/guides/user/jira-integration.md | 39 +++++--- docs/reference/config-reference.md | 21 +++-- internal/cli/poll_jira_config_test.go | 2 +- internal/config/issue_targets.go | 66 ++------------ internal/config/jira_tracking_test.go | 2 +- internal/forge/jira/client.go | 15 ++-- internal/forge/jira/client_test.go | 34 +++++++ internal/jirapoll/poller.go | 51 +++++++++-- internal/jirapoll/poller_test.go | 104 +++++++++++++++++++--- internal/jirapoll/types.go | 7 +- internal/jql/jql.go | 61 +++++++++++++ internal/jql/jql_test.go | 27 ++++++ 13 files changed, 321 insertions(+), 113 deletions(-) create mode 100644 internal/jql/jql.go create mode 100644 internal/jql/jql_test.go diff --git a/docs/guides/user/custom-poller-example.md b/docs/guides/user/custom-poller-example.md index 049ca04d0f..756ce56981 100644 --- a/docs/guides/user/custom-poller-example.md +++ b/docs/guides/user/custom-poller-example.md @@ -103,7 +103,8 @@ jobs: The poller reads the Jira site, project, and query from `tracker.jira` in `.fullsend/config.yaml`, and polls only when `poll.enabled` is `true`. It -always scopes the query to the project: +always scopes the query to the project and to the issues that changed within +the last 24 hours, oldest change first: ```yaml tracker: @@ -112,7 +113,7 @@ tracker: project: MYPROJECT poll: enabled: true - query: 'statusCategory != Done AND updated > -1w AND type = Bug' + query: 'statusCategory != Done AND type = Bug' ``` See [Jira Integration § Custom JQL](jira-integration.md#custom-jql). diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index f15a9eb0b5..19b90b50c7 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -994,7 +994,7 @@ pattern. ### Custom JQL -By default the poller searches for all non-done issues in the project, ordered by most recently updated. +By default the poller searches for all non-done issues in the project that changed within the last 24 hours, oldest change first. The poller reads the Jira site, project, and query only from [`tracker.jira`](../../reference/config-reference.md#trackerjira-connection-and-polling-settings) @@ -1008,15 +1008,26 @@ tracker: project: PROJ poll: enabled: true - query: 'labels = "fullsend" AND statusCategory != Done ORDER BY updated DESC' + query: 'labels = "fullsend" AND statusCategory != Done' ``` `base_url` and `project` are required. `api_url` defaults to `https://api.atlassian.com`. The poller always scopes the query as -`project = "" AND ()`, keeping a trailing `ORDER BY` at the -end, so the example above runs as -`project = "PROJ" AND (labels = "fullsend" AND statusCategory != Done) ORDER BY updated DESC`. -The parentheses in `poll.query` must be balanced. When `poll.query` is +`project = "" AND ()`, limits it to the issues whose +`updated` time falls within the 24-hour backfill window, and keeps a trailing +`ORDER BY` at the end, so the example above runs as +`(project = "PROJ" AND (labels = "fullsend" AND statusCategory != Done)) AND updated >= "-24h" ORDER BY updated ASC`. +The parentheses in `poll.query` must be balanced. + +Leave `ORDER BY` out of `poll.query` unless you need a particular order: +without one the poller sorts oldest change first (`ORDER BY updated ASC`), +which is the recommended order. A query with its own `ORDER BY` is searched +in that order. The order decides which issues are read when more issues +changed within the window than the search reads (see +[Poll coordination](#poll-coordination)); under newest change first the +oldest requests are the ones left out, and they can then leave the window +unserved. A query that sorts newest change first (`ORDER BY updated DESC`) +logs a WARNING every cycle that recommends oldest change first. When `poll.query` is omitted, the poller uses the default filter above. Unless `poll.enabled` is `true`, the poller skips the cycle without contacting Jira. @@ -1435,7 +1446,7 @@ matches it. Use `labels: allowlist` if that group is broader than you want. ## Poll coordination -The poller uses Jira entity properties for checkpoint tracking. It keeps no per-issue lock: it relies on one poll cycle at a time per target repository (see [Scheduled workflow](#scheduled-workflow)). 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`, which the search returns with each row, clamped as described below; a candidate with no usable `lastCheck` (missing, unreadable, or 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 checkpoint tracking. It keeps no per-issue lock: it relies on one poll cycle at a time per target repository (see [Scheduled workflow](#scheduled-workflow)). Each cycle searches for every issue that matches the query and changed within the 24-hour backfill window, with no row limit, 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`, which the search returns with each row, clamped as described below; a candidate with no usable `lastCheck` (missing, unreadable, or in the future) or no usable `updated` time counts as new. Two properties are stored on each processed issue: - **Write check** (`fullsend.poll.{owner}.{repo}.writeCheck`) — written before the poller reads an issue's comments and history, to confirm the credential can write to the issue and so commit its `lastCheck`; nothing reads it. An issue that fails the check is skipped with `WARNING: processing : check write access to : ...`, and a cycle in which every selected issue fails ends in an error, so a credential that cannot write shows as a failed run. Earlier versions kept a lock at `fullsend.poll.{owner}.{repo}.lock`; the poller no longer reads, writes or removes it. - **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. @@ -1468,10 +1479,10 @@ Three edge cases of checkpoint tracking are worth knowing: harmless (schedule accuracy affects latency, not correctness); the guarantee simply ends at 24 hours. A realistic trigger: **GitHub disables scheduled workflows after 60 days of repository inactivity**, which stops the poller - with no error anywhere. After a long gap, the starvation limit (M = 50, see + with no error anywhere. After a long gap, the per-cycle limit (N = 5, see below) compounds the problem — many issues may have accumulated new activity - simultaneously, and there is no rotation across cycles to reach issues - beyond the top M. If your deployment cannot tolerate the 24-hour bound, the + simultaneously, and a cycle processes only N of them, picked at random. If + your deployment cannot tolerate the 24-hour bound, the scheduler is pluggable: an external cron or Kubernetes CronJob that runs 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. @@ -1480,7 +1491,7 @@ Because each cron run is a fresh process, per-cycle Jira API cost is worth sizin 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. 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. +- **Every cycle lists the whole backfill window.** The search reads every issue that matches the query and changed within the last 24 hours, 50 rows per call, including issues already handled. A project where many issues change each day pays for that listing every cycle, and it counts against the cycle's five-minute time limit. The search stops after 200 calls (10,000 issues at 50 per call) and logs `WARNING: the search stopped after issues with more remaining; ...`; the issues beyond them are not examined that cycle. A cycle still processes at most N (default 5) of the issues with new activity, picked at random, so under a sustained backlog an issue can lose the draw until its request leaves the window. Narrow `tracker.jira.poll.query` (for example to a label or a subset of issue types) if either 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. @@ -1516,11 +1527,11 @@ When `acme/frontend` and `acme/backend` both poll issue `PROJ-42`: The two repos checkpoint independently and can process the same Jira comment — each dispatching to its own agent workflows. This is intentional: the same `/fs-triage` comment on a Jira issue may be relevant to multiple repos if their harness triggers match. -### 50-candidate cap with multiple repos +### Candidate search with multiple repos -Each repo's poller runs its own JQL query and gets its own top-M (default 50) candidate window. The cap is per-poller, not global — three repos polling the same project each see up to 50 candidates per cycle, not 50 shared across all three. +Each repo's poller runs its own JQL query and lists every matching issue that changed within the backfill window. Nothing is shared: three repos polling the same project each run the whole search, and each processes up to N (default 5) issues per cycle. -However, more pollers against the same Jira project means more API calls per cycle. Each poller independently reads an entity property per candidate for the activity filter, fetches changelogs, and paginates comments. For large multi-repo deployments, consider: +However, more pollers against the same Jira project means more API calls per cycle. Each poller independently runs its search, fetches changelogs, and paginates comments. For large multi-repo deployments, consider: - **Narrowing `tracker.jira.poll.query` per repo** to reduce candidate overlap. Use Jira Components or labels to segment the project (see the recommendation above), then scope each repo's query — e.g., `component = Frontend` or `labels = frontend` — so it skips issues that belong to other repos. - **Staggering cron schedules** so pollers from different repos don't hit the Jira API simultaneously. For example, offset each repo's schedule by one or two minutes. diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index aec4723ef9..32ec17f00d 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -81,7 +81,7 @@ tracker: # Issue tracker. At most one provider block # projects: [OTHER] # Jira project keys for cross-project issue creation or moves # poll: # enabled: true # Managed poll workflow switch (see the tracker.jira section) - # query: 'labels = "fullsend" ORDER BY updated DESC' # JQL; always scoped to project + # query: 'labels = "fullsend"' # JQL; always scoped to project # ── Authorization ──────────────────────────────────────────── authorization: # Extra sources of permission for triggering agents @@ -474,7 +474,7 @@ tracker: projects: [OTHER] poll: enabled: true - query: 'labels = "fullsend" AND statusCategory != Done ORDER BY updated DESC' + query: 'labels = "fullsend" AND statusCategory != Done' ``` - **`tracker.jira.base_url`** — The Jira site URL. It must be an `https` URL @@ -530,11 +530,18 @@ tracker: `fullsend jira poll` pipeline schedule. See [Jira polling](../cli/repos.md#jira-polling). - **`tracker.jira.poll.query`** — The JQL the poller runs. It defaults to - `statusCategory != Done ORDER BY updated DESC`. The query is always scoped - to `project`: the poller runs `project = "" AND ()` and - keeps a trailing `ORDER BY` after the closing parenthesis. The parentheses - in the query must be balanced. For example, the query above runs as - `project = "PROJ" AND (labels = "fullsend" AND statusCategory != Done) ORDER BY updated DESC`. + `statusCategory != Done`. The query is always scoped to `project` and to + the 24-hour backfill window: the poller runs + `(project = "" AND ()) AND updated >= "-24h"` and keeps a + trailing `ORDER BY` at the end. The parentheses in the query must be + balanced. For example, the query above runs as + `(project = "PROJ" AND (labels = "fullsend" AND statusCategory != Done)) AND updated >= "-24h" ORDER BY updated ASC`. + Without an `ORDER BY` the poller sorts oldest change first + (`ORDER BY updated ASC`), which is recommended. A query with its own + `ORDER BY` is searched in that order, and `ORDER BY updated DESC` logs a + WARNING every cycle: when more issues changed within the window than the + search reads, newest change first leaves the oldest requests out. See + [Custom JQL](../guides/user/jira-integration.md#custom-jql). `base_url` and `project` are required once `base_url`, `api_url`, `project`, a nonempty `run_label`, or `poll` is set. A mapping that only selects Jira (`jira: {}`) or only sets diff --git a/internal/cli/poll_jira_config_test.go b/internal/cli/poll_jira_config_test.go index b190d99e61..fae54dd9d4 100644 --- a/internal/cli/poll_jira_config_test.go +++ b/internal/cli/poll_jira_config_test.go @@ -60,7 +60,7 @@ func TestLoadJiraPollSettings_Defaults(t *testing.T) { got, err := loadJiraPollSettings(dir, "", "", "") require.NoError(t, err) assert.Equal(t, config.DefaultJiraAPIURL, got.apiURL) - assert.Equal(t, `project = "PROJ" AND (statusCategory != Done) ORDER BY updated DESC`, got.jql) + assert.Equal(t, `project = "PROJ" AND (statusCategory != Done)`, got.jql) assert.False(t, got.enabled, "an omitted poll mapping leaves polling disabled") } diff --git a/internal/config/issue_targets.go b/internal/config/issue_targets.go index 84cfee510f..9ae1c01c6a 100644 --- a/internal/config/issue_targets.go +++ b/internal/config/issue_targets.go @@ -10,6 +10,8 @@ import ( "unicode" "gopkg.in/yaml.v3" + + "github.com/fullsend-ai/fullsend/internal/jql" ) // Issue-tracker provider names accepted as keys under tracker:. @@ -98,8 +100,9 @@ const DefaultJiraAPIURL = "https://api.atlassian.com" // DefaultJiraPollQuery is the JQL predicate the Jira poller uses when // tracker.jira.poll.query is unset. It is always scoped to the configured -// project (see JiraTrackingConfig.PollJQL). -const DefaultJiraPollQuery = "statusCategory != Done ORDER BY updated DESC" +// project (see JiraTrackingConfig.PollJQL). It carries no ORDER BY, so the +// poller serves the oldest change first (ADR 0085, Decision item 2). +const DefaultJiraPollQuery = "statusCategory != Done" // JiraTrackingConfig holds Jira issue-tracking settings: the Jira site and // project this repository is connected to, the cross-project issue @@ -219,9 +222,6 @@ func (j *JiraTrackingConfig) HasConnectionSettings() bool { return j != nil && (j.BaseURL != "" || j.APIURL != "" || j.Project != "" || j.RunLabel != "" || j.Poll != nil) } -// jqlOrderByRe finds a trailing ORDER BY clause, case-insensitively. -var jqlOrderByRe = regexp.MustCompile(`(?i)\border\s+by\b`) - // ScopeJQLToProject scopes query to project as // `project = "" AND ()`, keeping a trailing ORDER BY // clause after the closing parenthesis. The ORDER BY is located outside @@ -229,7 +229,7 @@ var jqlOrderByRe = regexp.MustCompile(`(?i)\border\s+by\b`) // value is not split. An empty predicate (a query that is only an // ORDER BY clause) yields `project = ""` plus the ORDER BY. func ScopeJQLToProject(project, query string) string { - predicate, orderBy := splitJQLOrderBy(query) + predicate, orderBy := jql.SplitOrderBy(query) predicate = strings.TrimSpace(predicate) // Quote the key so a reserved-word key (AND, OR, IN) stays a value. scoped := fmt.Sprintf("project = %q", project) @@ -242,56 +242,6 @@ func ScopeJQLToProject(project, query string) string { return scoped } -// splitJQLOrderBy splits query at its last ORDER BY that is outside a -// quoted string, returning the predicate and the ORDER BY clause. -func splitJQLOrderBy(query string) (string, string) { - query = strings.TrimSpace(query) - quoted := quotedRanges(query) - matches := jqlOrderByRe.FindAllStringIndex(query, -1) - for i := len(matches) - 1; i >= 0; i-- { - start := matches[i][0] - if inRanges(start, quoted) { - continue - } - return query[:start], strings.TrimSpace(query[start:]) - } - return query, "" -} - -// quotedRanges returns the [start, end) byte ranges of single- or -// double-quoted strings in s, honoring backslash escapes. -func quotedRanges(s string) [][2]int { - var out [][2]int - var quote byte - start := 0 - for i := 0; i < len(s); i++ { - c := s[i] - switch { - case quote != 0 && c == '\\': - i++ - case quote != 0 && c == quote: - out = append(out, [2]int{start, i + 1}) - quote = 0 - case quote == 0 && (c == '"' || c == '\''): - quote = c - start = i - } - } - if quote != 0 { - out = append(out, [2]int{start, len(s)}) - } - return out -} - -func inRanges(pos int, ranges [][2]int) bool { - for _, r := range ranges { - if pos >= r[0] && pos < r[1] { - return true - } - } - return false -} - // JiraAllowedTargets lists the Jira projects (by key) agents may create // issues in beyond the source project. type JiraAllowedTargets struct { @@ -571,10 +521,10 @@ func (j *JiraTrackingConfig) ValidateConnection() error { // those inside quoted strings, are balanced and never close before they // open. func jqlParensBalanced(query string) bool { - quoted := quotedRanges(query) + quoted := jql.QuotedRanges(query) depth := 0 for i := 0; i < len(query); i++ { - if inRanges(i, quoted) { + if jql.InRanges(i, quoted) { continue } switch query[i] { diff --git a/internal/config/jira_tracking_test.go b/internal/config/jira_tracking_test.go index 8194b105ac..c5534aed3a 100644 --- a/internal/config/jira_tracking_test.go +++ b/internal/config/jira_tracking_test.go @@ -52,7 +52,7 @@ func TestJiraTracking_Defaults(t *testing.T) { assert.Equal(t, DefaultJiraAPIURL, jira.EffectiveAPIURL()) assert.False(t, jira.PollEnabled(), "omitted poll does not install the poll workflow") assert.Equal(t, DefaultJiraPollQuery, jira.PollQuery()) - assert.Equal(t, `project = "PROJ" AND (statusCategory != Done) ORDER BY updated DESC`, jira.PollJQL()) + assert.Equal(t, `project = "PROJ" AND (statusCategory != Done)`, jira.PollJQL()) var nilJira *JiraTrackingConfig assert.Equal(t, DefaultJiraAPIURL, nilJira.EffectiveAPIURL()) diff --git a/internal/forge/jira/client.go b/internal/forge/jira/client.go index 33335c452b..f163c13fdc 100644 --- a/internal/forge/jira/client.go +++ b/internal/forge/jira/client.go @@ -545,6 +545,10 @@ var searchFields = []string{"summary", "status", "labels", "reporter", "assignee // from overly broad JQL queries. const maxSearchPages = 200 +// ErrSearchTruncated is returned by SearchIssues, together with the issues +// it read, when the search still had results after maxSearchPages pages. +var ErrSearchTruncated = errors.New("search stopped at the page limit with results remaining") + // SearchIssues executes a JQL search and returns up to limit matching // issues, using the POST /rest/api/3/search/jql endpoint with cursor-based // pagination (nextPageToken + isLast). Pagination stops as soon as limit @@ -552,7 +556,9 @@ const maxSearchPages = 200 // bounds API cost rather than fetching everything and truncating // afterward. A limit <= 0 fetches all matching issues, capped at // maxSearchPages pages (10,000 issues at 50 per page) to prevent unbounded -// memory growth. +// memory growth. A search cut short by that cap returns the issues read so +// far with ErrSearchTruncated, so the caller can tell a cut from a complete +// result. // // properties names issue entity properties to return with each issue in // Issue.Properties (Jira returns at most five), so a caller that needs one @@ -593,15 +599,14 @@ func (c *LiveClient) SearchIssues(ctx context.Context, jql string, limit int, pr } all = append(all, result.Issues...) if limit > 0 && len(all) >= limit { - all = all[:limit] - break + return all[:limit], nil } if result.IsLast || len(result.Issues) == 0 || result.NextPageToken == "" { - break + return all, nil } nextPageToken = result.NextPageToken } - return all, nil + return all, ErrSearchTruncated } // GetIssue fetches a single issue by ID or key. diff --git a/internal/forge/jira/client_test.go b/internal/forge/jira/client_test.go index 203ac94a7e..abecf3894c 100644 --- a/internal/forge/jira/client_test.go +++ b/internal/forge/jira/client_test.go @@ -241,6 +241,40 @@ func TestSearchIssues_Pagination(t *testing.T) { assert.Equal(t, "PROJ-120", issues[119].Key) } +// A search that still has results after maxSearchPages pages returns what +// it read with ErrSearchTruncated; one that ends on its last allowed page +// does not. +func TestSearchIssues_TruncatedAtPageCap(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + lastIsLast bool + wantErr error + }{ + {name: "more results remain", wantErr: ErrSearchTruncated}, + {name: "ends on the last page", lastIsLast: true}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + client, mux := setupTest(t) + pages := 0 + mux.HandleFunc("/rest/api/3/search/jql", func(w http.ResponseWriter, r *http.Request) { + pages++ + writeJSON(t, w, http.StatusOK, SearchResult{ + Issues: []Issue{{ID: fmt.Sprintf("%d", pages), Key: fmt.Sprintf("PROJ-%d", pages)}}, + NextPageToken: "more", + IsLast: tc.lastIsLast && pages == maxSearchPages, + }) + }) + + issues, err := client.SearchIssues(context.Background(), "project = PROJ", 0) + require.ErrorIs(t, err, tc.wantErr) + assert.Len(t, issues, maxSearchPages) + assert.Equal(t, maxSearchPages, pages) + }) + } +} + // SearchIssues asks for the named entity properties on every page and // decodes them into Issue.Properties; without names it asks for none. func TestSearchIssues_Properties(t *testing.T) { diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index e647411eee..d0f60a3cdb 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "log" + "math" "os" "regexp" "strings" @@ -17,6 +18,7 @@ import ( "github.com/fullsend-ai/fullsend/internal/dispatch" "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/jql" "github.com/fullsend-ai/fullsend/internal/normevent" "github.com/fullsend-ai/fullsend/internal/randutil" ) @@ -74,9 +76,6 @@ type Poller struct { // New creates a Jira Poller with the given options. func New(client JiraClient, matcher EventMatcher, opts Options) *Poller { - if opts.M == 0 { - opts.M = 50 - } if opts.N == 0 { opts.N = 5 } @@ -135,7 +134,8 @@ func (p *Poller) Run(ctx context.Context) error { // as human follow-up re-dispatches the same agent in a loop. p.selfAccountID = userID(*myself) - // Step 1: Execute JQL to get candidate issues. + // Step 1: Search for the issues that changed within the backfill + // window. candidates, err := p.searchCandidates(readCtx) if err != nil { return fmt.Errorf("search candidates: %w", err) @@ -425,19 +425,52 @@ func (p *Poller) resolveActorRoles(ctx context.Context, actorIDs []string) error return nil } -// searchCandidates executes JQL and collects up to M results. +// newestChangeFirstRe matches an ORDER BY clause whose first key is the +// updated time, newest first. +var newestChangeFirstRe = regexp.MustCompile(`(?i)^order\s+by\s+updated(date)?\s+desc\b`) + +// searchCandidates returns every issue that matches the configured query +// and changed within the backfill window, with no row limit, in the query's +// sort order, or oldest change first when the query has none (ADR 0085, +// Decision item 2). func (p *Poller) searchCandidates(ctx context.Context) ([]jira.Issue, error) { - jql := p.opts.JQL - if jql == "" { + query := p.opts.JQL + if query == "" { if !validProjectKey.MatchString(p.opts.JiraProject) { return nil, fmt.Errorf("invalid Jira project key %q: must match %s", p.opts.JiraProject, validProjectKey.String()) } - jql = fmt.Sprintf("project = %q AND statusCategory != Done ORDER BY updated DESC", p.opts.JiraProject) + query = fmt.Sprintf("project = %q AND statusCategory != Done", p.opts.JiraProject) } // The search returns each candidate's lastCheck, so the activity // filter reads no property per candidate (ADR 0085, Decision item 2). - return p.client.SearchIssues(ctx, jql, p.opts.M, p.lastCheckKey()) + issues, err := p.client.SearchIssues(ctx, p.windowJQL(query), 0, p.lastCheckKey()) + if errors.Is(err, jira.ErrSearchTruncated) { + log.Printf("WARNING: the search stopped after %d issues with more remaining; the issues beyond them were not examined this cycle. Narrow the poll query so that fewer issues match", len(issues)) + return issues, nil + } + return issues, err +} + +// windowJQL limits query to the issues whose updated value falls within the +// backfill window, the window that already bounds a first poll and clamps an +// old lastCheck. It keeps the query's ORDER BY and adds oldest change first +// when the query has none. A query that sorts newest change first draws a +// WARNING, once per cycle: under a backlog that order can leave older +// requests waiting until they leave the window. +func (p *Poller) windowJQL(query string) string { + predicate, orderBy := jql.SplitOrderBy(query) + windowed := fmt.Sprintf(`updated >= "-%dh"`, int(math.Ceil(p.opts.FirstPollBackfillWindow.Hours()))) + if predicate = strings.TrimSpace(predicate); predicate != "" { + windowed = "(" + predicate + ") AND " + windowed + } + switch { + case orderBy == "": + orderBy = "ORDER BY updated ASC" + case newestChangeFirstRe.MatchString(orderBy): + log.Print("WARNING: the poll query sorts newest change first (ORDER BY updated DESC); oldest change first is recommended, because under a backlog older requests can wait until they leave the backfill window. Remove the ORDER BY clause or use ORDER BY updated ASC") + } + return windowed + " " + orderBy } // filterActive keeps the candidates with new activity (see hasNewActivity) diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index 29a26def97..bac428ad6d 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -316,9 +316,6 @@ func TestNew(t *testing.T) { JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ", }) - if p.opts.M != 50 { - t.Errorf("M = %d, want default 50", p.opts.M) - } if p.opts.N != 5 { t.Errorf("N = %d, want default 5", p.opts.N) } @@ -1594,32 +1591,113 @@ func TestSearchCandidatesQuotesProjectKey(t *testing.T) { t.Fatalf("searchCandidates() error: %v", err) } - want := `project = "PROJ" AND statusCategory != Done ORDER BY updated DESC` + want := `(project = "PROJ" AND statusCategory != Done) AND updated >= "-24h" ORDER BY updated ASC` if mc.lastQuery != want { t.Errorf("JQL = %q, want %q", mc.lastQuery, want) } } -// TestSearchCandidatesBoundsBySettingM checks that searchCandidates asks -// SearchIssues to stop paginating once M results are collected, instead of -// exhausting the full JQL match set and truncating client-side. -func TestSearchCandidatesBoundsBySettingM(t *testing.T) { +// TestSearchCandidatesHasNoRowLimit checks that searchCandidates reads every +// row of the search instead of the first 50 (ADR 0085, Decision item 2). +func TestSearchCandidatesHasNoRowLimit(t *testing.T) { mc := newMockClient() mc.searchResult = make([]jira.Issue, 200) for i := range mc.searchResult { mc.searchResult[i] = jira.Issue{ID: fmt.Sprintf("%d", i+1), Key: fmt.Sprintf("PROJ-%d", i+1)} } - p := newTestPoller(mc, nil, Options{JiraProject: "PROJ", M: 50}) + p := newTestPoller(mc, nil, Options{JiraProject: "PROJ"}) candidates, err := p.searchCandidates(context.Background()) if err != nil { t.Fatalf("searchCandidates() error: %v", err) } - if len(candidates) != 50 { - t.Errorf("len(candidates) = %d, want 50", len(candidates)) + if len(candidates) != 200 { + t.Errorf("len(candidates) = %d, want all 200", len(candidates)) + } + if mc.lastLimit != 0 { + t.Errorf("SearchIssues called with limit %d, want 0 (no row limit)", mc.lastLimit) + } +} + +// TestWindowJQL: the search is limited to the backfill window, keeps the +// query's own ORDER BY, defaults to oldest change first, and warns only +// when the query sorts newest change first (ADR 0085, Decision item 2). +func TestWindowJQL(t *testing.T) { + cases := []struct { + name string + query string + window time.Duration + want string + warn bool + }{ + {name: "no order by", query: `project = "PROJ" AND (labels = "fullsend")`, want: `(project = "PROJ" AND (labels = "fullsend")) AND updated >= "-24h" ORDER BY updated ASC`}, + {name: "newest change first", query: `project = "PROJ" ORDER BY updated DESC`, want: `(project = "PROJ") AND updated >= "-24h" ORDER BY updated DESC`, warn: true}, + {name: "newest change first, lowercase alias and a second key", query: `project = "PROJ" order by updatedDate desc, key`, want: `(project = "PROJ") AND updated >= "-24h" order by updatedDate desc, key`, warn: true}, + {name: "oldest change first", query: `project = "PROJ" ORDER BY updated ASC`, want: `(project = "PROJ") AND updated >= "-24h" ORDER BY updated ASC`}, + {name: "updated without a direction", query: `project = "PROJ" ORDER BY updated`, want: `(project = "PROJ") AND updated >= "-24h" ORDER BY updated`}, + {name: "another order", query: `project = "PROJ" ORDER BY created DESC`, want: `(project = "PROJ") AND updated >= "-24h" ORDER BY created DESC`}, + {name: "updated as a later key", query: `project = "PROJ" ORDER BY priority, updated DESC`, want: `(project = "PROJ") AND updated >= "-24h" ORDER BY priority, updated DESC`}, + {name: "order by inside quotes", query: `summary ~ "order by updated desc"`, want: `(summary ~ "order by updated desc") AND updated >= "-24h" ORDER BY updated ASC`}, + {name: "only an order by", query: `ORDER BY key`, want: `updated >= "-24h" ORDER BY key`}, + {name: "longer window", query: `project = "PROJ"`, window: 72 * time.Hour, want: `(project = "PROJ") AND updated >= "-72h" ORDER BY updated ASC`}, + {name: "part of an hour rounds up", query: `project = "PROJ"`, window: 90 * time.Minute, want: `(project = "PROJ") AND updated >= "-2h" ORDER BY updated ASC`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + logs := captureLog(t) + p := newTestPoller(newMockClient(), nil, Options{JiraProject: "PROJ", FirstPollBackfillWindow: tc.window}) + if got := p.windowJQL(tc.query); got != tc.want { + t.Errorf("windowJQL() = %q, want %q", got, tc.want) + } + if got := strings.Contains(logs.String(), "WARNING: the poll query sorts newest change first"); got != tc.warn { + t.Errorf("warned = %v, want %v:\n%s", got, tc.warn, logs) + } + }) + } +} + +// truncatedSearchClient serves the mock's rows as a search the client cut +// short at its page cap. +type truncatedSearchClient struct { + *mockClient +} + +func (c truncatedSearchClient) SearchIssues(ctx context.Context, jql string, limit int, properties ...string) ([]jira.Issue, error) { + issues, err := c.mockClient.SearchIssues(ctx, jql, limit, properties...) + if err != nil { + return nil, err + } + return issues, jira.ErrSearchTruncated +} + +// A search cut short at the client's page cap is not silent: the cycle +// warns, serves the rows it has, and exits normally. A query that sorts +// newest change first draws its warning once per cycle. +func TestRunSearchWarnings(t *testing.T) { + now := time.Now().Truncate(time.Second) + logs := captureLog(t) + mc := newMockClient() + mc.searchResult = []jira.Issue{idleTestIssue(1, now.Add(-48*time.Hour), now.Add(-time.Minute))} + addTriageComment(mc, "PROJ-1", "501", now.Add(-time.Minute)) + p := newTestPoller(truncatedSearchClient{mc}, &stubMatcher{agents: []string{"triage"}}, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProject: "PROJ", + JQL: `project = "PROJ" ORDER BY updated DESC`, + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + }) + + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if len(p.dispatches) != 1 { + t.Errorf("dispatched %d, want the returned row served", len(p.dispatches)) + } + if want := "WARNING: the search stopped after 1 issues with more remaining"; !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) } - if mc.lastLimit != 50 { - t.Errorf("SearchIssues called with limit %d, want 50 (p.opts.M)", mc.lastLimit) + if n := strings.Count(logs.String(), "WARNING: the poll query sorts newest change first"); n != 1 { + t.Errorf("newest-first warning logged %d times, want once per cycle:\n%s", n, logs) } } diff --git a/internal/jirapoll/types.go b/internal/jirapoll/types.go index 51255e62f9..a2117ebb2b 100644 --- a/internal/jirapoll/types.go +++ b/internal/jirapoll/types.go @@ -15,8 +15,10 @@ type JiraClient interface { // SearchIssues executes a JQL search and returns up to limit matching // issues, stopping pagination once that many results are collected. // A limit <= 0 returns all matching issues (bounded by the - // implementation's own pagination cap). Each issue carries the entity - // properties named in properties that it has, in Issue.Properties. + // implementation's own pagination cap; a search cut short by that cap + // returns the issues read so far with jira.ErrSearchTruncated). Each + // issue carries the entity properties named in properties that it has, + // in Issue.Properties. SearchIssues(ctx context.Context, jql string, limit int, properties ...string) ([]jira.Issue, error) GetIssue(ctx context.Context, issueIDOrKey string) (*jira.Issue, error) // GetStatus resolves a status name to its statusCategory, used to @@ -64,7 +66,6 @@ type Options struct { JiraProject string // Jira project key for default JQL JQL string // Custom JQL override OutputPath string // Path to write dispatch records JSON - M int // Max candidate issues per cycle (default: 50) N int // Max issues to process per cycle (default: 5) FirstPollBackfillWindow time.Duration // How far back to backfill comments/changelog on an issue's first poll (default: 24h) CycleTimeLimit time.Duration // Reading budget per cycle, from its start through the last issue read (default: 5m, ADR 0085) diff --git a/internal/jql/jql.go b/internal/jql/jql.go new file mode 100644 index 0000000000..8e6ec22f0e --- /dev/null +++ b/internal/jql/jql.go @@ -0,0 +1,61 @@ +// Package jql holds helpers for reading Jira Query Language strings. +package jql + +import ( + "regexp" + "strings" +) + +// orderByRe finds a trailing ORDER BY clause, case-insensitively. +var orderByRe = regexp.MustCompile(`(?i)\border\s+by\b`) + +// SplitOrderBy splits query at its last ORDER BY that is outside a +// quoted string, returning the predicate and the ORDER BY clause. +func SplitOrderBy(query string) (string, string) { + query = strings.TrimSpace(query) + quoted := QuotedRanges(query) + matches := orderByRe.FindAllStringIndex(query, -1) + for i := len(matches) - 1; i >= 0; i-- { + start := matches[i][0] + if InRanges(start, quoted) { + continue + } + return query[:start], strings.TrimSpace(query[start:]) + } + return query, "" +} + +// QuotedRanges returns the [start, end) byte ranges of single- or +// double-quoted strings in s, honoring backslash escapes. +func QuotedRanges(s string) [][2]int { + var out [][2]int + var quote byte + start := 0 + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case quote != 0 && c == '\\': + i++ + case quote != 0 && c == quote: + out = append(out, [2]int{start, i + 1}) + quote = 0 + case quote == 0 && (c == '"' || c == '\''): + quote = c + start = i + } + } + if quote != 0 { + out = append(out, [2]int{start, len(s)}) + } + return out +} + +// InRanges reports whether pos lies inside one of ranges. +func InRanges(pos int, ranges [][2]int) bool { + for _, r := range ranges { + if pos >= r[0] && pos < r[1] { + return true + } + } + return false +} diff --git a/internal/jql/jql_test.go b/internal/jql/jql_test.go new file mode 100644 index 0000000000..02afa87740 --- /dev/null +++ b/internal/jql/jql_test.go @@ -0,0 +1,27 @@ +package jql + +import "testing" + +func TestSplitOrderBy(t *testing.T) { + cases := []struct { + name, query, predicate, orderBy string + }{ + {name: "with order by", query: `labels = "fullsend" ORDER BY updated DESC`, predicate: `labels = "fullsend" `, orderBy: `ORDER BY updated DESC`}, + {name: "without order by", query: `labels = "fullsend"`, predicate: `labels = "fullsend"`}, + {name: "lowercase with surrounding space", query: ` status = Open order by created `, predicate: `status = Open `, orderBy: `order by created`}, + {name: "inside double quotes", query: `summary ~ "order by" AND status = Open`, predicate: `summary ~ "order by" AND status = Open`}, + {name: "inside single quotes", query: `summary ~ 'x order by y' ORDER BY key`, predicate: `summary ~ 'x order by y' `, orderBy: `ORDER BY key`}, + {name: "escaped quote", query: `summary ~ "a \" order by" ORDER BY key`, predicate: `summary ~ "a \" order by" `, orderBy: `ORDER BY key`}, + {name: "only order by", query: `ORDER BY updated DESC`, orderBy: `ORDER BY updated DESC`}, + {name: "unterminated quote", query: `summary ~ "order by`, predicate: `summary ~ "order by`}, + {name: "empty"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + predicate, orderBy := SplitOrderBy(tc.query) + if predicate != tc.predicate || orderBy != tc.orderBy { + t.Errorf("SplitOrderBy(%q) = %q, %q; want %q, %q", tc.query, predicate, orderBy, tc.predicate, tc.orderBy) + } + }) + } +} From c999caeb986672f311f7c6a81a76ad9c3716d3fc Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 05:51:48 +0200 Subject: [PATCH 07/37] test(jirapoll): cover both bad lastCheck forms and the all-failed guard Review follow-up for the unparseable lastCheck fix. - TestRunGarbageLastCheckTreatedAsUnset runs a full cycle for each way a stored value can fail: a string that is not a time, JSON that is not a string, and bytes that are not JSON. The first only reaches the time.Parse branch; the other two reach the json.Unmarshal branch. - It asserts the saved lastCheck equals the issue's updated value instead of only being set. - TestRunAllSelectedIssuesFailedFailsCycle restores coverage of Run's all-failed guard, which the replaced test was the only one to reach. Signed-off-by: guy oron --- internal/jirapoll/poller_idle_test.go | 92 ++++++++++++++++++--------- 1 file changed, 62 insertions(+), 30 deletions(-) diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index 4d27940e83..3ff3f7bf87 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -338,42 +338,74 @@ func TestRunFirstLookOldActivityThenIdle(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. +// 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") - logs := captureLog(t) - if err := idleTestPoller(mc, t).Run(context.Background()); err != nil { - t.Fatalf("cycle 1: %v", err) - } - if storedLastCheckAt(t, mc, "PROJ-1").IsZero() { - t.Fatal("cycle 1 saved no lastCheck over the garbage") - } - 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(), "not-a-time") { - 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) + 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", err) } - if mc.listCommentsCalls["PROJ-1"] != before { - t.Error("cycle 2 looked at an issue with nothing new") + if len(p.dispatches) != 0 { + t.Errorf("dispatched %d, want 0", len(p.dispatches)) } } From 71112a5ba35108d8758f215d23ebd2a84fa59122 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 05:54:26 +0200 Subject: [PATCH 08/37] test(jirapoll): pin the write check, the retry and the poll queue Review follow-up for the lock removal. - A denied issue keeps its lastCheck unset, so its request is retried; the served issue's lastCheck is committed. - The write-check property holds an RFC 3339 time, and a served issue costs two property writes: the check and the lastCheck. - TestRenderJiraPollCaller asserts the managed poll job's concurrency group and cancel-in-progress: false. With no per-issue lock, that group is what keeps two cycles from overlapping. - The two filter tests are renamed from FilterLocked to FilterActive, and the mock's counter comment no longer refers to a lock. Signed-off-by: guy oron --- internal/jirapoll/poller_idle_test.go | 4 ++-- internal/jirapoll/poller_test.go | 22 +++++++++++++++++----- internal/scaffold/jira_poll_test.go | 6 ++++++ 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index b38ba0ee70..95140115ed 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -326,7 +326,7 @@ func TestRunGarbageLastCheckAloneFailsCycle(t *testing.T) { // 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) { +func TestFilterActiveDecision(t *testing.T) { now := time.Now().Truncate(time.Second) key := lastCheckPropertyKey("acme", "platform") stamp := func(t time.Time) json.RawMessage { @@ -378,7 +378,7 @@ func TestFilterLockedActivityDecision(t *testing.T) { // A GitLab-target poller compares updated with its own lastCheck key, not // the GitHub-style one. -func TestFilterLockedGitLabTargetReadsItsOwnKey(t *testing.T) { +func TestFilterActiveGitLabTargetReadsItsOwnKey(t *testing.T) { now := time.Now().Truncate(time.Second) opts := Options{ TargetRepo: "group/project", diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index 5e8f90470d..f7f74336fd 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -64,9 +64,8 @@ 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. + // Per-issue call counts, so a test can show an issue cost nothing, + // including a write or a delete that the end state would not show. listCommentsCalls map[string]int // issueKey -> ListComments calls listChangelogCalls map[string]int // issueKey -> ListChangelog calls propertySetCalls map[string]int // issueKey -> SetEntityProperty calls @@ -1483,8 +1482,15 @@ func TestRunIgnoresLegacyLock(t *testing.T) { if mc.propertyDeleteCalls["PROJ-123"] != 0 { t.Errorf("deleted %d properties, want 0", mc.propertyDeleteCalls["PROJ-123"]) } - if _, ok := mc.properties["PROJ-123"][writeCheckPropertyKey("acme", "platform")]; !ok { - t.Error("the write-access check wrote no property") + var checked string + if err := json.Unmarshal(mc.properties["PROJ-123"][writeCheckPropertyKey("acme", "platform")], &checked); err != nil { + t.Fatalf("write-check property: %v", err) + } + if _, err := time.Parse(time.RFC3339, checked); err != nil { + t.Errorf("write-check property = %q, want an RFC 3339 time: %v", checked, err) + } + if n := mc.propertySetCalls["PROJ-123"]; n != 2 { + t.Errorf("wrote %d properties, want 2: one write check and one lastCheck", n) } } @@ -1542,6 +1548,12 @@ func TestRunWriteAccessCheck(t *testing.T) { if mc.listCommentsCalls["PROJ-2"] == 0 { t.Error("PROJ-2 was not read") } + if !storedLastCheckAt(t, mc, "PROJ-1").IsZero() { + t.Error("the denied issue's lastCheck advanced, so its request would not be retried") + } + if storedLastCheckAt(t, mc, "PROJ-2").IsZero() { + t.Error("the served issue's lastCheck was not committed") + } if want := "WARNING: processing PROJ-1: check write access to PROJ-1"; !strings.Contains(logs.String(), want) { t.Errorf("log lacks %q:\n%s", want, logs) } diff --git a/internal/scaffold/jira_poll_test.go b/internal/scaffold/jira_poll_test.go index d6f5d07225..0261b1cebd 100644 --- a/internal/scaffold/jira_poll_test.go +++ b/internal/scaffold/jira_poll_test.go @@ -45,6 +45,12 @@ func TestRenderJiraPollCaller(t *testing.T) { "FULLSEND_JIRA_CLIENT_SECRET": "${{ secrets.FULLSEND_JIRA_CLIENT_SECRET }}", }, wf.Jobs["poll"].Secrets, "the poll job receives the Jira credential choices") assert.Equal(t, "15", wf.Jobs["poll"].With["timeout_minutes"], "the caller sets the reusable poll timeout") + // The jira-poll driver keeps no per-issue lock (ADR 0085), so this + // group is what keeps two poll cycles from overlapping. + require.NotNil(t, wf.Jobs["poll"].Concurrency, "the poll job queues its runs") + assert.Equal(t, "${{ github.workflow }}-poll", wf.Jobs["poll"].Concurrency.Group) + assert.Equal(t, "!!bool", wf.Jobs["poll"].Concurrency.CancelInProgress.Tag) + assert.Equal(t, "false", wf.Jobs["poll"].Concurrency.CancelInProgress.Value, "a queued cycle waits; it is not cancelled") assert.Equal(t, "${{ needs.poll.outputs.matrix }}", wf.Jobs["dispatch"].With["matrix"]) for _, name := range []string{"FULLSEND_JIRA_TOKEN", "FULLSEND_JIRA_EMAIL", "FULLSEND_JIRA_CLIENT_ID", "FULLSEND_JIRA_CLIENT_SECRET"} { assert.Equal(t, "${{ secrets."+name+" }}", wf.Jobs["dispatch"].Secrets[name], From 5d27b040f17b352f19bb3363cc5ee3e0c7b8b207 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 05:54:31 +0200 Subject: [PATCH 09/37] docs(jira-poll): leave architecture.md alone and describe the write check Review follow-up for the lock removal. - Restore docs/architecture.md. main already describes the lock removal there (ADR 0085), and the edit here conflicted with it. - The Jira guide says the write-check property stays on the issue and why it is not deleted, and that the poll job's concurrency group covers one workflow file, so a repository must not be polled from a second workflow. The custom poller example says the same. - Three code comments no longer mention a Jira lock. Signed-off-by: guy oron --- docs/architecture.md | 14 ++++++-------- docs/guides/user/custom-poller-example.md | 4 +++- docs/guides/user/jira-integration.md | 4 ++-- internal/cli/poll.go | 2 +- internal/cli/poll_jira_gitlab.go | 2 +- internal/cli/poll_jira_gitlab_test.go | 2 +- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index c4b74c44ad..66d9bcb657 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -544,11 +544,10 @@ The existing design principle is that [the repo is the coordinator](problems/age ([guide](guides/user/chaining-follow-up-workflows.md), [ADR 0124](ADRs/0124-criteria-for-adding-a-built-in-agent-role.md)). - Per-repo **polling** complements webhook dispatch: `fullsend poll` uses poll - input drivers to discover work from remote systems (Jira first), runs one - cycle at a time per repository with no per-issue lock (ADR 0085), and feeds - the same dispatch pipeline as webhooks - ([ADR 0063](ADRs/0063-polling-based-work-discovery.md)). Initial scope is - per-repo mode only. + input drivers to discover work from remote systems (Jira first), coordinates + via source-native write-then-verify locks, and feeds the same dispatch pipeline + as webhooks ([ADR 0063](ADRs/0063-polling-based-work-discovery.md)). Initial + scope is per-repo mode only. - Jira poll candidate selection spends per-cycle slots only on candidates whose Jira `updated` is newer than their per-repository checkpoint, picks at random among them, and reads the per-cycle caps (N, default 5, and M, @@ -730,9 +729,8 @@ The existing design principle is that [the repo is the coordinator](problems/age remains open. - Is GitHub's event system sufficient for forge-native duplicate protection, or do we need additional coordination beyond label/state conventions and agent - idempotency? (Jira polling relies on one poll cycle at a time per repository - and no longer locks issues, per ADR 0085; ADR 0098 does not resolve this - question.) + idempotency? (Jira polling per ADR 0063 uses entity-property locks and runner + lock refresh; ADR 0098 does not resolve this question.) - How does work assignment interact with the backlog/priority agent described in [agent-architecture.md](problems/agent-architecture.md)? - How should explicit cancellation, retry, and reassignment interact with the automatic event-coalescing policy in diff --git a/docs/guides/user/custom-poller-example.md b/docs/guides/user/custom-poller-example.md index 049ca04d0f..0a0ce01f86 100644 --- a/docs/guides/user/custom-poller-example.md +++ b/docs/guides/user/custom-poller-example.md @@ -33,7 +33,9 @@ jobs: poll: runs-on: ubuntu-24.04 # The jira-poll driver keeps no per-issue lock: two overlapping cycles - # for one repository dispatch the same requests twice, so queue them. + # for one repository dispatch the same requests twice. This group queues + # the runs of this workflow; do not poll the same repository from a + # second workflow. concurrency: group: ${{ github.workflow }}-poll cancel-in-progress: false diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 65ef5f60a2..86d0372c5a 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -990,7 +990,7 @@ reuse fullsend's harness infrastructure the same way. See [Custom Poller Example](custom-poller-example.md) for more details on this pattern. -**The poll job's concurrency group (`cancel-in-progress: false`)** makes overlapping poll cycles queue rather than cancel each other, so only one poll cycle for this workflow runs at a time, including manually triggered runs. The poller relies on it: it keeps no per-issue lock, so two overlapping cycles for one repository dispatch the same requests twice. A scheduler other than the managed workflow or the managed GitLab schedule must itself keep cycles for one repository from overlapping. +**The poll job's concurrency group (`cancel-in-progress: false`)** makes overlapping poll cycles queue rather than cancel each other, so only one poll cycle for this workflow runs at a time, including manually triggered runs. The poller relies on it: it keeps no per-issue lock, so two overlapping cycles for one repository dispatch the same requests twice. The group covers this workflow file only, so do not poll the same repository from a second workflow: nothing queues the two against each other. A scheduler other than the managed workflow or the managed GitLab schedule must itself keep cycles for one repository from overlapping. ### Custom JQL @@ -1437,7 +1437,7 @@ matches it. Use `labels: allowlist` if that group is broader than you want. The poller uses Jira entity properties for checkpoint tracking. It keeps no per-issue lock: it relies on one poll cycle at a time per target repository (see [Scheduled workflow](#scheduled-workflow)). 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 in the future) or no usable `updated` time counts as new. Two properties are stored on each processed issue: -- **Write check** (`fullsend.poll.{owner}.{repo}.writeCheck`) — written before the poller reads an issue's comments and history, to confirm the credential can write to the issue and so commit its `lastCheck`; nothing reads it. An issue that fails the check is skipped with `WARNING: processing : check write access to : ...`, and a cycle in which every selected issue fails ends in an error, so a credential that cannot write shows as a failed run. Earlier versions kept a lock at `fullsend.poll.{owner}.{repo}.lock`; the poller no longer reads, writes or removes it. +- **Write check** (`fullsend.poll.{owner}.{repo}.writeCheck`) — written before the poller reads an issue's comments and history, to confirm the credential can write to the issue and so commit its `lastCheck`; nothing reads it. It stays on the issue and is overwritten on the next look: the poller does not delete it, because a delete would cost a second call per issue every cycle. An issue that fails the check is skipped with `WARNING: processing : check write access to : ...`, and a cycle in which every selected issue fails ends in an error, so a credential that cannot write shows as a failed run. Earlier versions kept a lock at `fullsend.poll.{owner}.{repo}.lock`; the poller no longer reads, writes or removes it. - **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. 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. diff --git a/internal/cli/poll.go b/internal/cli/poll.go index 5ff2d42e40..06591f64ad 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -414,7 +414,7 @@ type jiraPollArgs struct { // validTargetRepo matches "owner/repo" slugs (subgroup segments allowed, // matching splitOwnerRepo). Validated up front because a slash-less value -// would otherwise flow into a silently malformed Jira entity-property lock +// would otherwise flow into a silently malformed Jira entity-property // namespace and into NormalizedEvent.Repo. var validTargetRepo = regexp.MustCompile(`^[^/\s]+(/[^/\s]+)+$`) diff --git a/internal/cli/poll_jira_gitlab.go b/internal/cli/poll_jira_gitlab.go index 090f0f5e1b..56ce563e22 100644 --- a/internal/cli/poll_jira_gitlab.go +++ b/internal/cli/poll_jira_gitlab.go @@ -142,7 +142,7 @@ func runJiraPollGitLab(cmd *cobra.Command, f jiraPollGitLabFlags) error { return fmt.Errorf("create GitLab client: %w", err) } pollClient := gitlab.NewPollClient(glClient) - // Authenticate to GitLab before any Jira lock or checkpoint is touched, + // Authenticate to GitLab before any Jira issue property is touched, // so a bad Poller credential fails the cycle up front. if _, err := pollClient.GetAuthenticatedUserID(cmd.Context()); err != nil { return wrapGitLabAuthFailure(sel, fmt.Errorf("resolve GitLab poller identity: %w", err)) diff --git a/internal/cli/poll_jira_gitlab_test.go b/internal/cli/poll_jira_gitlab_test.go index 5cda72b1ed..05bf9b18d5 100644 --- a/internal/cli/poll_jira_gitlab_test.go +++ b/internal/cli/poll_jira_gitlab_test.go @@ -146,7 +146,7 @@ func TestPollCmd_JiraPollGitLabPreflight(t *testing.T) { // TestPollCmd_JiraPollGitLabAuthFailure drives the GitLab target through // client construction to the GitLab identity preflight, which runs before -// any Jira lock or checkpoint is touched. +// any Jira issue property is touched. func TestPollCmd_JiraPollGitLabAuthFailure(t *testing.T) { var gitlabCalls int srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { From a85a1423223b2c9b9b4e6326112407648e40f45f Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 05:58:06 +0200 Subject: [PATCH 10/37] fix(jirapoll): report a cancelled poll cycle as cancelled, not as timed out Review follow-up for the cycle and per-issue time limits. - When the caller's context ends, Run returns "poll cycle interrupted" with that error. It used to log that the cycle time limit was reached and return a time-limit error, because a cancelled read context looks the same as an expired one. - The error for a cycle that the time limit ended with no issue served now reads "... reached with none of the N selected issues served (M tried)". - The Jira guide no longer says a cycle can run long while reading under sustained Jira errors: retry waits count against the limits. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 +- internal/jirapoll/poller.go | 13 ++++++++++--- internal/jirapoll/poller_idle_test.go | 24 +++++++++++++++++++++++- 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 80e3742300..7dd50b1abe 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1482,7 +1482,7 @@ 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. 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. +- **Sustained Jira errors slow a cycle down.** Each Jira call retries up to 5 times with exponential backoff, honoring `Retry-After` (capped at 5 minutes). While the poller is reading, those waits count against the time limits above, so retries cannot hold one issue for more than two minutes or the reading for more than five. Committing checkpoints is not limited and can still run long under a sustained 429 or outage; 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. ## Multi-repo polling diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 2b4f35754e..5b027f991d 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -100,8 +100,8 @@ func New(client JiraClient, matcher EventMatcher, opts Options) *Poller { // cycles for one target repository from overlapping: with no lock, they // would dispatch the same requests twice (ADR 0085, Decision item 1). func (p *Poller) Run(ctx context.Context) error { - // Reading — the preflight, the search, the activity filter and every - // issue — must finish within CycleTimeLimit of the cycle's start, and + // Reading (the preflight, the search, the activity filter and every + // issue) must finish within CycleTimeLimit of the cycle's start, and // one issue within IssueTimeLimit (ADR 0085, Decision item 3). The // dispatch and checkpoint commit after it use ctx, so they get the rest // of the job's time. @@ -184,6 +184,8 @@ func (p *Poller) Run(ctx context.Context) error { if err != nil { var rle *roleLoadError switch { + case ctx.Err() != nil: + // The caller ended the cycle; reported after the loop. case errors.Is(readCtx.Err(), context.DeadlineExceeded): log.Printf("WARNING: the %s cycle time limit cut off reading %s; it waits for the next cycle", p.opts.CycleTimeLimit, issue.Key) case issueTimedOut: @@ -199,6 +201,11 @@ func (p *Poller) Run(ctx context.Context) error { p.dispatches = append(p.dispatches, pc.records...) pending = append(pending, pc) } + // The caller's context ended, not a time limit of this cycle: stop + // before anything is dispatched or committed. + if err := ctx.Err(); err != nil { + return fmt.Errorf("poll cycle interrupted: %w", err) + } if left := len(selected) - tried; left > 0 { log.Printf("WARNING: the %s cycle time limit was reached with %d selected issue(s) not read; they wait for the next cycle", p.opts.CycleTimeLimit, left) } @@ -208,7 +215,7 @@ func (p *Poller) Run(ctx context.Context) error { if processErrors == len(selected) { return fmt.Errorf("all %d selected issues failed to process", processErrors) } - return fmt.Errorf("the %s cycle time limit was reached before any selected issue was read (%d of %d tried, all failed or timed out)", p.opts.CycleTimeLimit, tried, len(selected)) + return fmt.Errorf("the %s cycle time limit was reached with none of the %d selected issues served (%d tried)", p.opts.CycleTimeLimit, len(selected), tried) } // Step 5: Write dispatch records. diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index eddc251025..1bbb69475c 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -3,6 +3,7 @@ package jirapoll import ( "context" "encoding/json" + "errors" "fmt" "path/filepath" "strings" @@ -696,7 +697,7 @@ func TestRunTimeLimitsServingNothingFailCycle(t *testing.T) { mc := newMockClient() p := timeLimitPoller(t, mc, map[string]bool{"PROJ-1": true}, 100*time.Millisecond, time.Hour) err := p.Run(context.Background()) - if err == nil || !strings.Contains(err.Error(), "cycle time limit was reached before any selected issue was read (1 of 2 tried") { + if err == nil || !strings.Contains(err.Error(), "cycle time limit was reached with none of the 2 selected issues served (1 tried)") { t.Fatalf("Run() error = %v, want the cycle-limit failure", err) } if want := "1 selected issue(s) not read"; !strings.Contains(logs.String(), want) { @@ -715,3 +716,24 @@ func TestRunTimeLimitsServingNothingFailCycle(t *testing.T) { } }) } + +// When the caller's context ends, the cycle stops with that error and does +// not blame a time limit of its own. +func TestRunCallerCancelIsNotATimeLimit(t *testing.T) { + logs := captureLog(t) + mc := newMockClient() + p := timeLimitPoller(t, mc, map[string]bool{"PROJ-1": true}, time.Hour, time.Hour) + ctx, cancel := context.WithCancel(context.Background()) + time.AfterFunc(50*time.Millisecond, cancel) + + err := p.Run(ctx) + if !errors.Is(err, context.Canceled) { + t.Fatalf("Run() error = %v, want the caller's cancellation", err) + } + if strings.Contains(logs.String(), "time limit") || strings.Contains(logs.String(), "took longer than") { + t.Errorf("a cancelled cycle logged a time limit:\n%s", logs) + } + if mc.listCommentsCalls["PROJ-2"] != 0 { + t.Error("read PROJ-2 after the cycle was cancelled") + } +} From fa9fcb0eee0be5279281223e9261d1234048ebcc Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 06:02:04 +0200 Subject: [PATCH 11/37] fix(jiramock): serve a search whose body cannot be read, as before Review follow-up for taking lastCheck from the search results. - The mock's search answered 400 to a body it could not decode. It ignored the body before, so it now treats such a body as naming no properties. - The multi-repo section of the Jira guide no longer says each poller reads an entity property per candidate; the search returns it. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 +- pkg/behaviourtest/drivers/jiramock/server.go | 8 +++----- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 9d86692bd7..7c4152c481 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1520,7 +1520,7 @@ The two repos checkpoint independently and can process the same Jira comment — Each repo's poller runs its own JQL query and gets its own top-M (default 50) candidate window. The cap is per-poller, not global — three repos polling the same project each see up to 50 candidates per cycle, not 50 shared across all three. -However, more pollers against the same Jira project means more API calls per cycle. Each poller independently reads an entity property per candidate for the activity filter, fetches changelogs, and paginates comments. For large multi-repo deployments, consider: +However, more pollers against the same Jira project means more API calls per cycle. Each poller independently runs its search, fetches changelogs, and paginates comments. For large multi-repo deployments, consider: - **Narrowing `tracker.jira.poll.query` per repo** to reduce candidate overlap. Use Jira Components or labels to segment the project (see the recommendation above), then scope each repo's query — e.g., `component = Frontend` or `labels = frontend` — so it skips issues that belong to other repos. - **Staggering cron schedules** so pollers from different repos don't hit the Jira API simultaneously. For example, offset each repo's schedule by one or two minutes. diff --git a/pkg/behaviourtest/drivers/jiramock/server.go b/pkg/behaviourtest/drivers/jiramock/server.go index 379235754f..56fe9feaa3 100644 --- a/pkg/behaviourtest/drivers/jiramock/server.go +++ b/pkg/behaviourtest/drivers/jiramock/server.go @@ -286,14 +286,12 @@ func handleSearch(w http.ResponseWriter, r *http.Request, s *State) { return } - // Like Jira, return each requested entity property an issue has. + // Like Jira, return each requested entity property an issue has. A + // body the mock cannot read names no properties, as before. var req struct { Properties []string `json:"properties"` } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { - http.Error(w, "bad search body: "+err.Error(), http.StatusBadRequest) - return - } + _ = json.NewDecoder(r.Body).Decode(&req) s.mu.Lock() issues := make([]jira.Issue, 0, len(s.issues)) From afeda2cc692b32e63bca00d131e7392b73f9b4fc Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 06:12:17 +0200 Subject: [PATCH 12/37] docs(jira-poll): say what the window search no longer reports after an outage Review follow-up for the window search. The search returns only issues that changed within the backfill window. An issue whose last change is older than the window is no longer listed, so: - it is not checkpointed on first enable, and - activity on it that fell out of the window during an outage leaves no "predates the backfill window" line in the log. The Jira guide's first-enable bullet, its resume-after-a-gap bullet and its troubleshooting row said otherwise. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 8daae35d74..f5f993c907 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1459,7 +1459,7 @@ These properties are namespaced per target repo, so multiple repos can poll the Three edge cases of checkpoint tracking are worth knowing: -- **First enable on an existing backlog.** Every issue starts with an unset `lastCheck`, so on the first poll of an issue the poller has no checkpoint to filter by. Activity is instead bounded by a fixed 24-hour backfill window (not currently configurable): an `opened` event is emitted only for issues created within the window, and only comments and changelog entries from within the window produce events. Backlog issues with no activity (including comment edits) inside the window are silently checkpointed without dispatching. If you want the initial rollout scoped even tighter, narrow the candidate set with a custom `--jql`. +- **First enable on an existing backlog.** Every issue starts with an unset `lastCheck`, so on the first poll of an issue the poller has no checkpoint to filter by. Activity is instead bounded by a fixed 24-hour backfill window (not currently configurable): an `opened` event is emitted only for issues created within the window, and only comments and changelog entries from within the window produce events. Backlog issues with no activity (including comment edits) inside the window are not returned by the search, so nothing is dispatched for them. If you want the initial rollout scoped even tighter, narrow `tracker.jira.poll.query`. - **Resuming after a gap longer than 24 hours permanently drops events in the gap.** The same 24-hour backfill window that bounds a first poll also bounds resumption. When the poller reads a stored `lastCheck` older than @@ -1468,13 +1468,14 @@ Three edge cases of checkpoint tracking are worth knowing: 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, 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 in the run log, and only for an issue that changed again within the + window: when it is selected it logs + `WARNING: lastCheck for ("") predates the backfill window; clamping to `. + An issue whose last change is older than the window is not returned by the + search, so activity on it that fell out of the window leaves no line in the + log. The `WARNING: activity filter: …` line that contains the same phrase + `predates the backfill window` now appears only for an issue at the very + edge of the window. 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 @@ -1559,7 +1560,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 may have been 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. An issue with no change inside the window is not returned by the search and leaves no log line, so its lost events are not reported. 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 | From 048b710f59c5ba9b7e1168046f41f933dfffc304 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 07:05:41 +0200 Subject: [PATCH 13/37] feat(jirapoll): limit one issue to 250 records and 768 KB per cycle Implements the per-issue limits of ADR 0085 Decision item 3. - One issue contributes at most 250 dispatch records per cycle on both targets and, on the GitHub target, 768 KB of the poll job's matrix output. Over a limit the driver keeps the oldest records, by the time of the event that produced them, drops the rest with a WARNING that names the issue, and still advances the checkpoint. Records within the limits keep their order. - matrixOutputSize measures records as the managed workflow emits them, compact JSON inside {"include":[...]}, at two bytes per UTF-16 code unit, which is how GitHub approximates job output size. Go's escaped <, > and & count at their escaped length, so the measure can be above what GitHub sees and is never below. - The cap of 100 events per issue is unchanged. - The Jira guide describes the limits. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 + internal/jirapoll/limits.go | 120 ++++++++++++++++ internal/jirapoll/limits_test.go | 202 +++++++++++++++++++++++++++ internal/jirapoll/poller.go | 11 +- 4 files changed, 333 insertions(+), 2 deletions(-) create mode 100644 internal/jirapoll/limits.go create mode 100644 internal/jirapoll/limits_test.go diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index f5f993c907..a3ac65c17b 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1455,6 +1455,8 @@ These properties are namespaced per target repo, so multiple repos can poll the **Time limits.** A cycle stops reading from Jira five minutes after it starts: the authentication check, the search, the activity filter and the selected issues all count. Reading one issue stops after two minutes. An issue that takes longer is skipped with `WARNING: reading took longer than 2m0s; ...`: none of its records are dispatched and its `lastCheck` stays where it was, so it is tried again next cycle. When the five minutes run out, the poller dispatches what it finished, commits those checkpoints and exits normally; the issue it was reading and any it had not reached wait for the next cycle, and the run log names them or says how many. Dispatching and committing are not counted against the five minutes. A cycle that serves none of its selected issues, because they all failed or ran into these limits, fails. The limits are not configurable. +**Per-issue limits.** One look at an issue handles at most 100 events, and the dispatch records they produce (one for each agent an event matches) are limited to 250 per issue and, on GitHub, to 768 KB of the poll job's `matrix` output. The size is counted the way GitHub counts job outputs, at two bytes per UTF-16 code unit. Over a limit the poller keeps the oldest records, drops the rest, logs `WARNING: produced dispatch records this cycle; ...`, and still advances `lastCheck`, so the dropped requests are not retried. The limits bound the agent runs that a rewound `lastCheck` or a bulk change can start from one issue: 250 is GitHub's limit of 256 jobs in a matrix less a small margin, and 768 KB is three quarters of GitHub's 1 MB limit on a job's outputs. The size limit does not apply on GitLab, which starts each pipeline separately. + > **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` property. The driver treats it 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`. Three edge cases of checkpoint tracking are worth knowing: diff --git a/internal/jirapoll/limits.go b/internal/jirapoll/limits.go new file mode 100644 index 0000000000..a906eb0b73 --- /dev/null +++ b/internal/jirapoll/limits.go @@ -0,0 +1,120 @@ +package jirapoll + +import ( + "encoding/json" + "fmt" + "log" + "slices" + "time" + "unicode/utf16" +) + +// Limits on the dispatch records one issue contributes to a cycle (ADR 0085, +// Decision items 3 and 4). +const ( + // maxRecordsPerIssue is GitHub's 256-job matrix limit less a small + // margin. It applies on both targets, so that there is one rule. + maxRecordsPerIssue = 250 + // maxMatrixOutputBytes is three quarters of GitHub's 1 MB limit on a + // job's outputs, measured as matrixOutputSize measures it. It applies on + // the GitHub target only: GitLab starts each pipeline separately and + // has no batch output. + maxMatrixOutputBytes = 768 * 1024 +) + +// matrixEnvelopeSize is the size of a matrix output that holds no records. +const matrixEnvelopeSize = 2 * len(`{"include":[]}`) + +// recordOutputSize returns the size counted for one record inside the poll +// job's matrix output. The managed workflow builds that output with +// jq -c '{include: .}', so the record is measured as compact JSON. GitHub +// approximates output size from the UTF-16 encoding, so each UTF-16 code +// unit counts as two bytes. Go writes <, > and & (and U+2028, U+2029) as +// six-character escapes where jq writes the character itself, so for text +// that holds them this count is above what GitHub sees, never below. A +// record that cannot be encoded counts as empty here; writing the dispatch +// file reports it. +func recordOutputSize(record DispatchRecord) int { + data, err := json.Marshal(record) + if err != nil { + return 0 + } + units := 0 + for _, r := range string(data) { + units += utf16.RuneLen(r) + } + return 2 * units +} + +// matrixOutputSize returns the size GitHub counts for the poll job's matrix +// output when it holds records. +func matrixOutputSize(records []DispatchRecord) int { + size := matrixEnvelopeSize + for i, record := range records { + if i > 0 { + size += 2 // the comma between two records + } + size += recordOutputSize(record) + } + return size +} + +// issueRecord is a dispatch record with the time of the event that produced +// it. +type issueRecord struct { + record DispatchRecord + at time.Time +} + +// capIssueRecords applies the per-issue limits to the records one issue +// produced this cycle: at most maxRecordsPerIssue records and, on the +// GitHub target, maxMatrixOutputBytes of matrix output. Within the limits it +// returns the records in the order given. Over a limit it keeps the oldest +// records that fit, oldest first, and drops the rest with a WARNING that +// names the issue. The drop is deliberate, like the event cap in +// processIssue: one issue does not honestly produce that many records in a +// cycle, so the limits bound the runs that a rewound lastCheck or a bulk +// change can start. The caller still advances the checkpoint. +func (p *Poller) capIssueRecords(issueKey string, records []issueRecord) []DispatchRecord { + if len(records) == 0 { + return nil + } + sized := p.opts.TargetForge != TargetForgeGitLab + // fit returns how many of the leading records are within the limits. + fit := func() int { + size := matrixEnvelopeSize + for i, r := range records { + if i == maxRecordsPerIssue { + return i + } + if !sized { + continue + } + if i > 0 { + size += 2 + } + if size += recordOutputSize(r.record); size > maxMatrixOutputBytes { + return i + } + } + return len(records) + } + + kept := fit() + if kept < len(records) { + slices.SortStableFunc(records, func(a, b issueRecord) int { return a.at.Compare(b.at) }) + kept = fit() + limits := fmt.Sprintf("%d records", maxRecordsPerIssue) + if sized { + limits += fmt.Sprintf(" and %d KB of GitHub job output", maxMatrixOutputBytes/1024) + } + log.Printf("WARNING: %s produced %d dispatch records this cycle; one issue contributes at most %s, so the oldest %d are kept and %d dropped (possible lastCheck rewind or bulk change)", + issueKey, len(records), limits, kept, len(records)-kept) + } + + out := make([]DispatchRecord, kept) + for i := range out { + out[i] = records[i].record + } + return out +} diff --git a/internal/jirapoll/limits_test.go b/internal/jirapoll/limits_test.go new file mode 100644 index 0000000000..088a996135 --- /dev/null +++ b/internal/jirapoll/limits_test.go @@ -0,0 +1,202 @@ +package jirapoll + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + "unicode/utf16" + + "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/normevent" +) + +// The matrix output is measured as the compact JSON the managed workflow +// builds, two bytes per UTF-16 code unit. +func TestMatrixOutputSize(t *testing.T) { + utf16Bytes := func(s string) int { return 2 * len(utf16.Encode([]rune(s))) } + + if got, want := matrixOutputSize(nil), utf16Bytes(`{"include":[]}`); got != want { + t.Errorf("empty matrix = %d, want %d", got, want) + } + + records := []DispatchRecord{ + {Agent: "triage", Role: "triage", SourceRepo: "acme/platform", EventType: "comment", EventPayload: json.RawMessage(`{"body":"héllo 😀"}`), StatusRepo: "acme/platform", StatusNumber: "7"}, + {Agent: "code", TriggerSource: "label", EventPayload: json.RawMessage(`{ "body" : "a\u003cb" }`)}, + } + // é is one UTF-16 code unit and 😀 is two. The second payload is + // compacted, and its escaped < keeps its six characters. + want := utf16Bytes(`{"include":[` + + `{"agent":"triage","role":"triage","source_repo":"acme/platform","event_type":"comment","event_payload":{"body":"héllo 😀"},"status_repo":"acme/platform","status_number":"7"},` + + `{"agent":"code","role":"","source_repo":"","event_type":"","event_payload":{"body":"a\u003cb"},"trigger_source":"label","status_repo":"","status_number":""}` + + `]}`) + if got := matrixOutputSize(records); got != want { + t.Errorf("matrixOutputSize() = %d, want %d", got, want) + } + + if got := recordOutputSize(DispatchRecord{EventPayload: json.RawMessage(`{`)}); got != 0 { + t.Errorf("a record that cannot be encoded = %d, want 0", got) + } +} + +// commentMatcher produces agents records per event. Each record carries the +// comment's body, so a test can tell which events' records were kept, and +// pad extra characters. +type commentMatcher struct { + agents int + pad int +} + +func (m commentMatcher) Match(_ context.Context, event *normevent.Event) ([]DispatchRecord, error) { + body := "" + if event.Transition.Comment != nil { + body = event.Transition.Comment.Body + } + payload, err := json.Marshal(map[string]string{"body": body, "pad": strings.Repeat("x", m.pad)}) + if err != nil { + return nil, err + } + records := make([]DispatchRecord, m.agents) + for i := range records { + records[i] = DispatchRecord{Agent: fmt.Sprintf("agent-%d", i), EventPayload: payload} + } + return records, nil +} + +// limitsTestIssue processes an issue with n comments, listed newest first: +// comment c000 is the newest and the last one the oldest. +func limitsTestIssue(t *testing.T, targetForge string, n int, matcher EventMatcher) (pendingCheckpoint, string) { + t.Helper() + logs := captureLog(t) + now := time.Now().Truncate(time.Second) + mc := newMockClient() + for i := range n { + mc.comments["PROJ-123"] = append(mc.comments["PROJ-123"], jira.Comment{ + ID: fmt.Sprintf("%d", i), + Body: fmt.Sprintf("/fs-triage c%03d", i), + Created: now.Add(-time.Duration(i+1) * time.Minute).Format(jiraTimeLayout), + Author: jira.User{AccountID: "u1", AccountType: "atlassian"}, + }) + } + mc.roleMembership = map[string]string{"u1": "Developers"} + + p := newTestPoller(mc, matcher, Options{ + TargetRepo: "acme/platform", + TargetForge: targetForge, + GitLabURL: "https://gitlab.example.com", + JiraBaseURL: "https://acme.atlassian.net", + JiraProject: "PROJ", + }) + pc, err := p.processIssue(context.Background(), idleTestIssue(123, now.Add(-48*time.Hour), now)) + if err != nil { + t.Fatalf("processIssue() error: %v", err) + } + if pc.t.IsZero() { + t.Error("the checkpoint does not advance") + } + return pc, logs.String() +} + +// bodiesOf returns the comment body each record carries. +func bodiesOf(t *testing.T, records []DispatchRecord) []string { + t.Helper() + bodies := make([]string, len(records)) + for i, record := range records { + var payload struct { + Body string `json:"body"` + } + if err := json.Unmarshal(record.EventPayload, &payload); err != nil { + t.Fatalf("record %d payload: %v", i, err) + } + bodies[i] = payload.Body + } + return bodies +} + +// One issue contributes at most 250 records on both targets: the oldest are +// kept, the rest dropped with a WARNING that names the issue, and the +// checkpoint advances (ADR 0085, Decision item 3). +func TestProcessIssueKeepsOldest250Records(t *testing.T) { + for _, targetForge := range []string{TargetForgeGitHub, TargetForgeGitLab} { + t.Run(targetForge, func(t *testing.T) { + // 90 comments with 3 records each: 270 records. + pc, logs := limitsTestIssue(t, targetForge, 90, commentMatcher{agents: 3}) + + if len(pc.records) != maxRecordsPerIssue { + t.Fatalf("kept %d records, want %d", len(pc.records), maxRecordsPerIssue) + } + bodies := bodiesOf(t, pc.records) + // The 83 oldest comments (c089 down to c007) fill 249 places + // and c006 gets the last one. + if bodies[0] != "/fs-triage c089" || bodies[249] != "/fs-triage c006" { + t.Errorf("kept from %q to %q, want the oldest first: c089 to c006", bodies[0], bodies[249]) + } + for _, body := range bodies { + if body < "/fs-triage c006" { + t.Fatalf("kept a record of %q, one of the newest comments", body) + } + } + if want := "WARNING: PROJ-123 produced 270 dispatch records this cycle"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + if want := "the oldest 250 are kept and 20 dropped"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + }) + } +} + +// On the GitHub target one issue also contributes at most 768 KB of matrix +// output; GitLab has no batch output, so the size limit does not apply +// there. +func TestProcessIssueKeepsOldestRecordsWithinSizeLimit(t *testing.T) { + // 10 records of about 200 KB each: 100,000 padding characters at two + // bytes each. + matcher := commentMatcher{agents: 1, pad: 100_000} + + t.Run("github", func(t *testing.T) { + pc, logs := limitsTestIssue(t, TargetForgeGitHub, 10, matcher) + + if len(pc.records) != 3 { + t.Fatalf("kept %d records, want 3 of about 200 KB each", len(pc.records)) + } + size := matrixOutputSize(pc.records) + if size > maxMatrixOutputBytes { + t.Errorf("kept %d bytes, over the %d limit", size, maxMatrixOutputBytes) + } + if next := size + 2 + recordOutputSize(pc.records[0]); next <= maxMatrixOutputBytes { + t.Errorf("one more record would make %d bytes, within the %d limit, yet it was dropped", next, maxMatrixOutputBytes) + } + if bodies := bodiesOf(t, pc.records); bodies[0] != "/fs-triage c009" || bodies[2] != "/fs-triage c007" { + t.Errorf("kept %v, want the three oldest comments, oldest first", bodies) + } + if want := "one issue contributes at most 250 records and 768 KB of GitHub job output, so the oldest 3 are kept and 7 dropped"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + }) + + t.Run("gitlab", func(t *testing.T) { + pc, logs := limitsTestIssue(t, TargetForgeGitLab, 10, matcher) + + if len(pc.records) != 10 { + t.Errorf("kept %d records, want all 10: the size limit is for GitHub only", len(pc.records)) + } + if strings.Contains(logs, "dispatch records this cycle") { + t.Errorf("logged a limit that was not reached:\n%s", logs) + } + }) +} + +// Records within the limits keep the order they were produced in. +func TestProcessIssueWithinLimitsKeepsOrder(t *testing.T) { + pc, logs := limitsTestIssue(t, TargetForgeGitHub, 3, commentMatcher{agents: 1}) + + if got, want := strings.Join(bodiesOf(t, pc.records), ","), "/fs-triage c000,/fs-triage c001,/fs-triage c002"; got != want { + t.Errorf("records = %s, want the listing order %s", got, want) + } + if strings.Contains(logs, "dispatch records this cycle") { + t.Errorf("logged a limit that was not reached:\n%s", logs) + } +} diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index b9d8d98a39..a46deca133 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -687,6 +687,7 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (pendingChe // A cycle in which every event fails validation fails the whole // cycle in Run instead, holding the checkpoints so those events // are retried. + var records []issueRecord for _, event := range events { ne := p.toNormalizedEvent(event) p.eventsSeen++ @@ -715,7 +716,7 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (pendingChe } if p.matcher != nil { - records, matchErr := p.matcher.Match(ctx, &ne) + matched, matchErr := p.matcher.Match(ctx, &ne) if matchErr != nil { // Counted beside validation failures so an // all-matcher-error cycle fails the run at the @@ -725,10 +726,16 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (pendingChe p.eventsMatchErrors++ continue } - pc.records = append(pc.records, records...) + for _, record := range matched { + records = append(records, issueRecord{record: record, at: event.UpdatedAt}) + } } } + // One issue contributes at most 250 records and, on the GitHub target, + // 768 KB (ADR 0085, Decision item 3). The checkpoint advances past + // whatever is dropped, as with the event cap above. + pc.records = p.capIssueRecords(issue.Key, records) return pc, nil } From 00f8edbb7045e249c92f7aa076d4eb269ff5d02b Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 07:18:07 +0200 Subject: [PATCH 14/37] test(jirapoll): pin that a record over 768 KB on its own is dropped The per-issue size limit drops a single record that is over the limit, since dispatching it would lose the whole batch. The limit tests did not cover that case. Signed-off-by: guy oron --- internal/jirapoll/limits_test.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/internal/jirapoll/limits_test.go b/internal/jirapoll/limits_test.go index 088a996135..479c678c40 100644 --- a/internal/jirapoll/limits_test.go +++ b/internal/jirapoll/limits_test.go @@ -177,6 +177,19 @@ func TestProcessIssueKeepsOldestRecordsWithinSizeLimit(t *testing.T) { } }) + // A record that is over the limit on its own is dropped too: dispatching + // it would lose the whole batch. + t.Run("github, one record over the limit", func(t *testing.T) { + pc, logs := limitsTestIssue(t, TargetForgeGitHub, 1, commentMatcher{agents: 1, pad: 400_000}) + + if len(pc.records) != 0 { + t.Errorf("kept %d records, want 0", len(pc.records)) + } + if want := "the oldest 0 are kept and 1 dropped"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + }) + t.Run("gitlab", func(t *testing.T) { pc, logs := limitsTestIssue(t, TargetForgeGitLab, 10, matcher) From ede31d197c99685cc98515406e16937a6710c01c Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 07:58:10 +0200 Subject: [PATCH 15/37] fix(jirapoll): exit normally at the cycle time limit, as ADR 0085 says Review follow-up for the cycle and per-issue time limits. ADR 0085 Decision item 3 says that at the cycle limit the driver stops reading and exits normally, and that a cycle ends in an error when every issue it tried failed or timed out. Two cases did not follow it: - A search that ran into the cycle limit failed the run. It now logs a WARNING, reads no issue and exits normally. - An issue the cycle limit cut off counted as a failure, so a cycle that finished no issue always failed. It now waits for the next cycle without counting, and the cycle fails only when at least one issue failed or took longer than the per-issue limit and none was served. The Jira guide describes both. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 +- internal/jirapoll/poller.go | 30 ++++++--- internal/jirapoll/poller_idle_test.go | 87 ++++++++++++++++++++++++--- 3 files changed, 99 insertions(+), 20 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 486561d05e..7f8c674a8f 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1442,7 +1442,7 @@ The poller uses Jira entity properties for checkpoint tracking. It keeps no per- 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. -**Time limits.** A cycle stops reading from Jira five minutes after it starts: the authentication check, the search, the activity filter and the selected issues all count. Reading one issue stops after two minutes. An issue that takes longer is skipped with `WARNING: reading took longer than 2m0s; ...`: none of its records are dispatched and its `lastCheck` stays where it was, so it is tried again next cycle. When the five minutes run out, the poller dispatches what it finished, commits those checkpoints and exits normally; the issue it was reading and any it had not reached wait for the next cycle, and the run log names them or says how many. Dispatching and committing are not counted against the five minutes. A cycle that serves none of its selected issues, because they all failed or ran into these limits, fails. The limits are not configurable. +**Time limits.** A cycle stops reading from Jira five minutes after it starts: the authentication check, the search, the activity filter and the selected issues all count. Reading one issue stops after two minutes. An issue that takes longer is skipped with `WARNING: reading took longer than 2m0s; ...`: none of its records are dispatched and its `lastCheck` stays where it was, so it is tried again next cycle. When the five minutes run out, the poller dispatches what it finished, commits those checkpoints and exits normally; the issue it was reading and any it had not reached wait for the next cycle, and the run log names them or says how many. Dispatching and committing are not counted against the five minutes. Running into the five minutes is not a failure by itself, so a cycle whose search used them up reads no issue and still exits normally, with a WARNING. A cycle in which every issue it read failed or took longer than two minutes does fail, so a poller blocked by slow issues shows as a failed run. The limits are not configurable. > **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` property. The driver treats it as untrusted: a `lastCheck` dated 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`. diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 67286b2a02..198731d218 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -138,7 +138,14 @@ func (p *Poller) Run(ctx context.Context) error { // Step 1: Execute JQL to get candidate issues. candidates, err := p.searchCandidates(readCtx) if err != nil { - return fmt.Errorf("search candidates: %w", err) + if ctx.Err() != nil || !errors.Is(readCtx.Err(), context.DeadlineExceeded) { + return fmt.Errorf("search candidates: %w", err) + } + // The cycle time limit includes the search. Reaching it stops the + // reading and the cycle exits normally (ADR 0085, Decision item 3): + // no issue was read, so nothing is dispatched or committed. + log.Printf("WARNING: the %s cycle time limit was reached during the search; no issue was read this cycle", p.opts.CycleTimeLimit) + candidates = nil } // Step 2: Drop the issues with nothing new since their lastCheck @@ -171,7 +178,7 @@ func (p *Poller) Run(ctx context.Context) error { // contributes neither records nor a checkpoint, so its requests stay // eligible next cycle. var pending []pendingCheckpoint - var processErrors, tried int + var failed, tried int for _, issue := range selected { if readCtx.Err() != nil { break @@ -187,15 +194,17 @@ func (p *Poller) Run(ctx context.Context) error { case ctx.Err() != nil: // The caller ended the cycle; reported after the loop. case errors.Is(readCtx.Err(), context.DeadlineExceeded): + // Not a failure: the issue is unfinished and waits. log.Printf("WARNING: the %s cycle time limit cut off reading %s; it waits for the next cycle", p.opts.CycleTimeLimit, issue.Key) case issueTimedOut: log.Printf("WARNING: reading %s took longer than %s; none of its records were taken and its lastCheck was not advanced", issue.Key, p.opts.IssueTimeLimit) + failed++ case errors.As(err, &rle): return fmt.Errorf("load project roles for %s: %w", p.opts.JiraProject, rle.err) default: log.Printf("WARNING: processing %s: %v", issue.Key, err) + failed++ } - processErrors++ continue } p.dispatches = append(p.dispatches, pc.records...) @@ -209,13 +218,16 @@ func (p *Poller) Run(ctx context.Context) error { if left := len(selected) - tried; left > 0 { log.Printf("WARNING: the %s cycle time limit was reached with %d selected issue(s) not read; they wait for the next cycle", p.opts.CycleTimeLimit, left) } - // A cycle that served no selected issue fails, so a poller blocked by - // failing or slow issues shows as a failed run. - if len(selected) > 0 && len(pending) == 0 { - if processErrors == len(selected) { - return fmt.Errorf("all %d selected issues failed to process", processErrors) + // A cycle in which every issue it read failed or timed out ends in an + // error, so a poller blocked by failing or slow issues shows as a failed + // run. Reaching the cycle time limit is not a failure by itself: what + // was finished is dispatched and committed below, and the rest waits + // (ADR 0085, Decision item 3). + if failed > 0 && len(pending) == 0 { + if failed == len(selected) { + return fmt.Errorf("all %d selected issues failed to process", failed) } - return fmt.Errorf("the %s cycle time limit was reached with none of the %d selected issues served (%d tried)", p.opts.CycleTimeLimit, len(selected), tried) + return fmt.Errorf("all %d issues read before the %s cycle time limit failed or timed out; the other %d selected issues wait for the next cycle", failed, p.opts.CycleTimeLimit, len(selected)-failed) } // Step 5: Write dispatch records. diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index be8a51cb90..521176bbed 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "errors" "fmt" + "os" "path/filepath" "strings" "testing" @@ -740,25 +741,57 @@ func TestRunCycleTimeLimitLeavesRestForNextCycle(t *testing.T) { } } -// A cycle that serves no selected issue because of the time limits fails, so -// a poller blocked by slow issues shows as a failed run. -func TestRunTimeLimitsServingNothingFailCycle(t *testing.T) { - t.Run("cycle limit on the first issue", func(t *testing.T) { +// slowSearchClient holds SearchIssues until the call's context ends. It then +// fails with the context's error or, when late is set, returns the rows, +// like a search whose last page arrives just after the time limit. +type slowSearchClient struct { + *mockClient + late bool +} + +func (c slowSearchClient) SearchIssues(ctx context.Context, jql string, limit int) ([]jira.Issue, error) { + <-ctx.Done() + if !c.late { + return nil, ctx.Err() + } + return c.mockClient.SearchIssues(context.Background(), jql, limit) +} + +// Reaching the cycle time limit is not a failure by itself: the cycle exits +// normally, even when it finished no issue. A cycle in which every issue it +// read failed or timed out ends in an error, so a poller blocked by slow +// issues shows as a failed run (ADR 0085, Decision item 3). +func TestRunTimeLimitOutcomes(t *testing.T) { + t.Run("the cycle limit cuts off the first issue: normal exit", func(t *testing.T) { logs := captureLog(t) mc := newMockClient() p := timeLimitPoller(t, mc, map[string]bool{"PROJ-1": true}, 100*time.Millisecond, time.Hour) - err := p.Run(context.Background()) - if err == nil || !strings.Contains(err.Error(), "cycle time limit was reached with none of the 2 selected issues served (1 tried)") { - t.Fatalf("Run() error = %v, want the cycle-limit failure", err) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) } - if want := "1 selected issue(s) not read"; !strings.Contains(logs.String(), want) { - t.Errorf("log lacks %q:\n%s", want, logs) + for _, want := range []string{"cycle time limit cut off reading PROJ-1", "1 selected issue(s) not read"} { + if !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } } if mc.listCommentsCalls["PROJ-2"] != 0 { t.Error("read PROJ-2 after the cycle limit") } + if len(p.dispatches) != 0 || !storedLastCheckAt(t, mc, "PROJ-1").IsZero() { + t.Errorf("dispatched %d and saved a lastCheck for an issue that was not finished", len(p.dispatches)) + } }) - t.Run("every issue over the per-issue limit", func(t *testing.T) { + + t.Run("a slow issue, then the cycle limit: error", func(t *testing.T) { + mc := newMockClient() + p := timeLimitPoller(t, mc, map[string]bool{"PROJ-1": true, "PROJ-2": true}, 450*time.Millisecond, 300*time.Millisecond) + err := p.Run(context.Background()) + if err == nil || !strings.Contains(err.Error(), "all 1 issues read before the 450ms cycle time limit failed or timed out; the other 1 selected issues wait") { + t.Fatalf("Run() error = %v, want the failure of a cycle blocked by a slow issue", err) + } + }) + + t.Run("every issue over the per-issue limit: error", func(t *testing.T) { mc := newMockClient() p := timeLimitPoller(t, mc, map[string]bool{"PROJ-1": true, "PROJ-2": true}, time.Hour, 20*time.Millisecond) err := p.Run(context.Background()) @@ -766,6 +799,40 @@ func TestRunTimeLimitsServingNothingFailCycle(t *testing.T) { t.Fatalf("Run() error = %v, want the all-failed guard", err) } }) + + for _, late := range []bool{false, true} { + name := "the search fails at the cycle limit: normal exit" + want := "cycle time limit was reached during the search; no issue was read this cycle" + if late { + name = "the search returns after the cycle limit: normal exit" + want = "2 selected issue(s) not read" + } + t.Run(name, func(t *testing.T) { + logs := captureLog(t) + mc := newMockClient() + timeLimitPoller(t, mc, nil, time.Hour, time.Hour) // fills mc with the two issues + out := filepath.Join(t.TempDir(), "dispatches.json") + p := newTestPoller(slowSearchClient{mc, late}, &stubMatcher{agents: []string{"triage"}}, Options{ + TargetRepo: "acme/platform", + JiraBaseURL: "https://acme.atlassian.net", + JiraProject: "PROJ", + OutputPath: out, + CycleTimeLimit: 50 * time.Millisecond, + }) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + if mc.listCommentsCalls["PROJ-1"]+mc.listCommentsCalls["PROJ-2"] != 0 { + t.Error("read an issue after the cycle limit") + } + if data, err := os.ReadFile(out); err != nil || string(data) != "[]\n" { + t.Errorf("dispatch file = %q, %v; want an empty batch", data, err) + } + }) + } } // When the caller's context ends, the cycle stops with that error and does From 5847e8cd96f5fd366987f861bded12f78a37188d Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 08:02:45 +0200 Subject: [PATCH 16/37] refactor(jirapoll): parseLastCheck cannot fail, so it returns no error With the unparseable-lastCheck fix merged in, a stored value that is not a timestamp is treated as unset instead of returning an error, so parseLastCheck has no error left to return. Drop the return value and the branch in hasNewActivity that checked it. Signed-off-by: guy oron --- internal/jirapoll/lock.go | 17 +++++++++-------- internal/jirapoll/poller.go | 14 +++++--------- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/internal/jirapoll/lock.go b/internal/jirapoll/lock.go index 51169dff50..5a3a5bed0f 100644 --- a/internal/jirapoll/lock.go +++ b/internal/jirapoll/lock.go @@ -146,15 +146,16 @@ func (p *Poller) loadLastCheck(ctx context.Context, issueKey string) (storedLast } return storedLastCheck{}, fmt.Errorf("get lastCheck property: %w", err) } - return p.parseLastCheck(raw) + return p.parseLastCheck(raw), nil } // parseLastCheck parses and clamps a stored lastCheck value without // logging, so the activity filter can report the clamps once per cycle -// instead of once per issue. An empty value is unset. -func (p *Poller) parseLastCheck(raw json.RawMessage) (storedLastCheck, error) { +// instead of once per issue. An empty value is unset, and so is one that is +// not a timestamp. +func (p *Poller) parseLastCheck(raw json.RawMessage) storedLastCheck { if len(raw) == 0 { - return storedLastCheck{}, nil + return storedLastCheck{} } // A value that is not a timestamp is treated as unset, like a future @@ -165,14 +166,14 @@ func (p *Poller) parseLastCheck(raw json.RawMessage) (storedLastCheck, error) { // is never logged. var ts string if err := json.Unmarshal(raw, &ts); err != nil { - return storedLastCheck{clamp: clampInvalid}, nil + return storedLastCheck{clamp: clampInvalid} } // 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{clamp: clampInvalid}, nil + return storedLastCheck{clamp: clampInvalid} } // lastCheck lives in an issue entity property writable by anyone with @@ -193,12 +194,12 @@ func (p *Poller) parseLastCheck(raw json.RawMessage) (storedLastCheck, error) { const clockSkew = 2 * time.Minute if t.After(now.Add(clockSkew)) { lc.value, lc.clamp = time.Time{}, clampFuture - return lc, nil + return lc } if floor := now.Add(-p.opts.FirstPollBackfillWindow); t.Before(floor) { lc.value, lc.clamp = floor, clampFloor } - return lc, nil + return lc } // advanceLastCheck updates the lastCheck timestamp for an issue. diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index f77b45c4f3..828e4a0c64 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -481,17 +481,13 @@ func (p *Poller) filterActive(issues []jira.Issue) []jira.Issue { // processIssue's read clamps it (ADR 0160, Decision item 1). The search's // value only decides whether to skip the issue; processing reads lastCheck // from the issue again. It fails open: an issue whose lastCheck the search -// did not return or that cannot be parsed, or that has no usable updated +// did not return or that is not a timestamp, or that has no usable updated // value, is active, so neither a search that drops the property nor an -// editor writing garbage can hide an issue. A parse 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. +// editor writing garbage can hide an issue. 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(issue jira.Issue, clamped *clampReport) bool { - lc, err := p.parseLastCheck(issue.Properties[p.lastCheckKey()]) - if err != nil { - return true - } + lc := p.parseLastCheck(issue.Properties[p.lastCheckKey()]) updated, updatedErr := parseJiraTimestamp(issue.Fields.Updated) active := lc.value.IsZero() || updatedErr != nil || updated.After(lc.value) switch lc.clamp { From 60dbfaa8f62e7a11784f7ca0aae016e0f5568196 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 08:08:59 +0200 Subject: [PATCH 17/37] refactor(jirapoll): keep an issue's records in order when the limits drop some capIssueRecords sorted the records by event time when a limit was exceeded, so the kept records came out oldest first on overflow and in production order otherwise. It now ranks the records by event time without moving them, keeps the oldest that fit, and returns the kept ones in the order they were produced. The limits only ever drop the newest records; they never reorder. Signed-off-by: guy oron --- internal/jirapoll/limits.go | 57 ++++++++++++++++++-------------- internal/jirapoll/limits_test.go | 17 +++++----- 2 files changed, 41 insertions(+), 33 deletions(-) diff --git a/internal/jirapoll/limits.go b/internal/jirapoll/limits.go index a906eb0b73..6c749a40e7 100644 --- a/internal/jirapoll/limits.go +++ b/internal/jirapoll/limits.go @@ -68,10 +68,10 @@ type issueRecord struct { // capIssueRecords applies the per-issue limits to the records one issue // produced this cycle: at most maxRecordsPerIssue records and, on the -// GitHub target, maxMatrixOutputBytes of matrix output. Within the limits it -// returns the records in the order given. Over a limit it keeps the oldest -// records that fit, oldest first, and drops the rest with a WARNING that -// names the issue. The drop is deliberate, like the event cap in +// GitHub target, maxMatrixOutputBytes of matrix output. It keeps the oldest +// records that fit, by the time of the event that produced them, and drops +// the rest with a WARNING that names the issue. The records it keeps stay in +// the order given. The drop is deliberate, like the event cap in // processIssue: one issue does not honestly produce that many records in a // cycle, so the limits bound the runs that a rewound lastCheck or a bulk // change can start. The caller still advances the checkpoint. @@ -80,30 +80,35 @@ func (p *Poller) capIssueRecords(issueKey string, records []issueRecord) []Dispa return nil } sized := p.opts.TargetForge != TargetForgeGitLab - // fit returns how many of the leading records are within the limits. - fit := func() int { - size := matrixEnvelopeSize - for i, r := range records { - if i == maxRecordsPerIssue { - return i - } - if !sized { - continue - } - if i > 0 { - size += 2 + + // Rank the records oldest first without moving them. Events are not + // produced in time order: comments come before changelog entries, and + // an edited comment carries the time of its edit. + oldestFirst := make([]int, len(records)) + for i := range oldestFirst { + oldestFirst[i] = i + } + slices.SortStableFunc(oldestFirst, func(a, b int) int { return records[a].at.Compare(records[b].at) }) + + keep := make([]bool, len(records)) + kept, size := 0, matrixEnvelopeSize + for _, i := range oldestFirst { + if kept == maxRecordsPerIssue { + break + } + if sized { + if kept > 0 { + size += 2 // the comma between two records } - if size += recordOutputSize(r.record); size > maxMatrixOutputBytes { - return i + if size += recordOutputSize(records[i].record); size > maxMatrixOutputBytes { + break } } - return len(records) + keep[i] = true + kept++ } - kept := fit() if kept < len(records) { - slices.SortStableFunc(records, func(a, b issueRecord) int { return a.at.Compare(b.at) }) - kept = fit() limits := fmt.Sprintf("%d records", maxRecordsPerIssue) if sized { limits += fmt.Sprintf(" and %d KB of GitHub job output", maxMatrixOutputBytes/1024) @@ -112,9 +117,11 @@ func (p *Poller) capIssueRecords(issueKey string, records []issueRecord) []Dispa issueKey, len(records), limits, kept, len(records)-kept) } - out := make([]DispatchRecord, kept) - for i := range out { - out[i] = records[i].record + out := make([]DispatchRecord, 0, kept) + for i, r := range records { + if keep[i] { + out = append(out, r.record) + } } return out } diff --git a/internal/jirapoll/limits_test.go b/internal/jirapoll/limits_test.go index 479c678c40..84df91f643 100644 --- a/internal/jirapoll/limits_test.go +++ b/internal/jirapoll/limits_test.go @@ -116,8 +116,9 @@ func bodiesOf(t *testing.T, records []DispatchRecord) []string { } // One issue contributes at most 250 records on both targets: the oldest are -// kept, the rest dropped with a WARNING that names the issue, and the -// checkpoint advances (ADR 0085, Decision item 3). +// kept in the order they were produced, the rest dropped with a WARNING +// that names the issue, and the checkpoint advances (ADR 0085, Decision +// item 3). func TestProcessIssueKeepsOldest250Records(t *testing.T) { for _, targetForge := range []string{TargetForgeGitHub, TargetForgeGitLab} { t.Run(targetForge, func(t *testing.T) { @@ -128,10 +129,10 @@ func TestProcessIssueKeepsOldest250Records(t *testing.T) { t.Fatalf("kept %d records, want %d", len(pc.records), maxRecordsPerIssue) } bodies := bodiesOf(t, pc.records) - // The 83 oldest comments (c089 down to c007) fill 249 places - // and c006 gets the last one. - if bodies[0] != "/fs-triage c089" || bodies[249] != "/fs-triage c006" { - t.Errorf("kept from %q to %q, want the oldest first: c089 to c006", bodies[0], bodies[249]) + // The 83 oldest comments (c007 to c089) take 249 places and + // c006 gets one. The listing order, newest first, is kept. + if bodies[0] != "/fs-triage c006" || bodies[1] != "/fs-triage c007" || bodies[249] != "/fs-triage c089" { + t.Errorf("kept %q, %q ... %q; want one record of c006, then c007 to c089", bodies[0], bodies[1], bodies[249]) } for _, body := range bodies { if body < "/fs-triage c006" { @@ -169,8 +170,8 @@ func TestProcessIssueKeepsOldestRecordsWithinSizeLimit(t *testing.T) { if next := size + 2 + recordOutputSize(pc.records[0]); next <= maxMatrixOutputBytes { t.Errorf("one more record would make %d bytes, within the %d limit, yet it was dropped", next, maxMatrixOutputBytes) } - if bodies := bodiesOf(t, pc.records); bodies[0] != "/fs-triage c009" || bodies[2] != "/fs-triage c007" { - t.Errorf("kept %v, want the three oldest comments, oldest first", bodies) + if got, want := strings.Join(bodiesOf(t, pc.records), ","), "/fs-triage c007,/fs-triage c008,/fs-triage c009"; got != want { + t.Errorf("kept %s, want the three oldest comments in listing order: %s", got, want) } if want := "one issue contributes at most 250 records and 768 KB of GitHub job output, so the oldest 3 are kept and 7 dropped"; !strings.Contains(logs, want) { t.Errorf("log lacks %q:\n%s", want, logs) From 07a34db9799d20342d6e392b627a30c8d9ae2d53 Mon Sep 17 00:00:00 2001 From: guy oron Date: Fri, 27 Nov 2026 03:16:28 +0200 Subject: [PATCH 18/37] docs(jira-poll): put the default-query sentence back with the query paragraph The sort-order paragraph added for the window search ended with the sentence about an omitted poll.query and poll.enabled. Move it back to the end of the paragraph that describes the query. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index a573de28d6..aff1052ae5 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1017,7 +1017,9 @@ tracker: `updated` time falls within the 24-hour backfill window, and keeps a trailing `ORDER BY` at the end, so the example above runs as `(project = "PROJ" AND (labels = "fullsend" AND statusCategory != Done)) AND updated >= "-24h" ORDER BY updated ASC`. -The parentheses in `poll.query` must be balanced. +The parentheses in `poll.query` must be balanced. When `poll.query` is +omitted, the poller uses the default filter above. Unless `poll.enabled` is +`true`, the poller skips the cycle without contacting Jira. Leave `ORDER BY` out of `poll.query` unless you need a particular order: without one the poller sorts oldest change first (`ORDER BY updated ASC`), @@ -1027,9 +1029,7 @@ changed within the window than the search reads (see [Poll coordination](#poll-coordination)); under newest change first the oldest requests are the ones left out, and they can then leave the window unserved. A query that sorts newest change first (`ORDER BY updated DESC`) -logs a WARNING every cycle that recommends oldest change first. When `poll.query` is -omitted, the poller uses the default filter above. Unless `poll.enabled` is -`true`, the poller skips the cycle without contacting Jira. +logs a WARNING every cycle that recommends oldest change first. The `--jira-url`, `--jira-project`, and `--jql` flags were removed and are rejected, and `JIRA_BASE_URL` is not read. Because the query is always From f32dd09ba59863532df8fceeca1368b33dc099af Mon Sep 17 00:00:00 2001 From: guy oron Date: Fri, 27 Nov 2026 04:31:44 +0200 Subject: [PATCH 19/37] docs(jirapoll): drop the lock from two comments that came with the main merge The project-set refactor on main describes a processed issue as read under the lock and its lock as kept single. The lock is gone on this branch, so the test comment names the write-check property and the uniqueIssues comment no longer lists a lock. Signed-off-by: guy oron --- internal/jirapoll/multi_project_test.go | 12 ++++++------ internal/jirapoll/poller.go | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/internal/jirapoll/multi_project_test.go b/internal/jirapoll/multi_project_test.go index 10085490ff..e988f2793c 100644 --- a/internal/jirapoll/multi_project_test.go +++ b/internal/jirapoll/multi_project_test.go @@ -256,16 +256,16 @@ func TestRun_TwoProjectsShareOneSearch(t *testing.T) { if want := `project in ("ALPHA", "BETA") AND (labels = x OR project = OTHER) ORDER BY created ASC`; mc.lastQuery != want { t.Errorf("JQL = %q, want %q", mc.lastQuery, want) } - // N = 2 issues of the 3 candidates are processed: each processed issue - // gets its lastCheck read under the lock. - locked := 0 + // N = 2 of the candidates are processed: each processed issue gets its + // write-check property. + processed := 0 for _, key := range []string{"ALPHA-1", "BETA-1", "ALPHA-2", "BETA-2", "ALPHA-3"} { if _, ok := mc.properties[key]; ok { - locked++ + processed++ } } - if locked > 2 { - t.Errorf("%d issues were processed, want at most N = 2 across the set", locked) + if processed > 2 { + t.Errorf("%d issues were processed, want at most N = 2 across the set", processed) } } diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index f074e99997..46167b9403 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -445,7 +445,7 @@ func (p *Poller) searchCandidates(ctx context.Context, jql string) ([]jira.Issue // ID, which stays the same when an issue moves between projects of the // set, or its key when Jira serves no ID. Jira can return the same issue // twice when results shift between the pages of one search; processing it -// once per cycle keeps its lock, checkpoint and dispatches single. +// once per cycle keeps its checkpoint and dispatches single. func uniqueIssues(issues []jira.Issue) []jira.Issue { seen := make(map[string]bool, len(issues)) unique := issues[:0:0] From d0737740d5432667a2e5cce95eaa33f64c8f6326 Mon Sep 17 00:00:00 2001 From: guy oron Date: Fri, 27 Nov 2026 04:33:46 +0200 Subject: [PATCH 20/37] refactor(jirapoll): use config's ORDER BY splitter instead of a jql package On main the poller imports config for its query scoping (#9883), so the internal/jql package this branch added to keep the poller free of that import is no longer needed. Export config.SplitJQLOrderBy, use it in windowJQL, and delete internal/jql. The quote helpers go back to being private to config, as they are on main. Signed-off-by: guy oron --- internal/config/issue_targets.go | 61 +++++++++++++++++++++++++++++--- internal/jirapoll/poller.go | 3 +- internal/jql/jql.go | 61 -------------------------------- internal/jql/jql_test.go | 27 -------------- 4 files changed, 57 insertions(+), 95 deletions(-) delete mode 100644 internal/jql/jql.go delete mode 100644 internal/jql/jql_test.go diff --git a/internal/config/issue_targets.go b/internal/config/issue_targets.go index aa71ce0953..ee7a830f8d 100644 --- a/internal/config/issue_targets.go +++ b/internal/config/issue_targets.go @@ -10,8 +10,6 @@ import ( "unicode" "gopkg.in/yaml.v3" - - "github.com/fullsend-ai/fullsend/internal/jql" ) // Issue-tracker provider names accepted as keys under tracker:. @@ -222,6 +220,9 @@ func (j *JiraTrackingConfig) HasConnectionSettings() bool { return j != nil && (j.BaseURL != "" || j.APIURL != "" || j.Project != "" || j.RunLabel != "" || j.Poll != nil) } +// jqlOrderByRe finds a trailing ORDER BY clause, case-insensitively. +var jqlOrderByRe = regexp.MustCompile(`(?i)\border\s+by\b`) + // ScopeJQLToProject scopes query to project as // `project = "" AND ()`, keeping a trailing ORDER BY // clause after the closing parenthesis. The ORDER BY is located outside @@ -239,7 +240,7 @@ func ScopeJQLToProject(project, query string) string { // keys and the predicate's parentheses (see ValidJiraProjectKey and // JQLParensBalanced): this function only formats. func ScopeJQLToProjects(projects []string, query string) string { - predicate, orderBy := jql.SplitOrderBy(query) + predicate, orderBy := SplitJQLOrderBy(query) predicate = strings.TrimSpace(predicate) // Quote each key so a reserved-word key (AND, OR, IN) stays a value. quoted := make([]string, len(projects)) @@ -261,6 +262,56 @@ func ScopeJQLToProjects(projects []string, query string) string { return scoped } +// SplitJQLOrderBy splits query at its last ORDER BY that is outside a +// quoted string, returning the predicate and the ORDER BY clause. +func SplitJQLOrderBy(query string) (string, string) { + query = strings.TrimSpace(query) + quoted := quotedRanges(query) + matches := jqlOrderByRe.FindAllStringIndex(query, -1) + for i := len(matches) - 1; i >= 0; i-- { + start := matches[i][0] + if inRanges(start, quoted) { + continue + } + return query[:start], strings.TrimSpace(query[start:]) + } + return query, "" +} + +// quotedRanges returns the [start, end) byte ranges of single- or +// double-quoted strings in s, honoring backslash escapes. +func quotedRanges(s string) [][2]int { + var out [][2]int + var quote byte + start := 0 + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case quote != 0 && c == '\\': + i++ + case quote != 0 && c == quote: + out = append(out, [2]int{start, i + 1}) + quote = 0 + case quote == 0 && (c == '"' || c == '\''): + quote = c + start = i + } + } + if quote != 0 { + out = append(out, [2]int{start, len(s)}) + } + return out +} + +func inRanges(pos int, ranges [][2]int) bool { + for _, r := range ranges { + if pos >= r[0] && pos < r[1] { + return true + } + } + return false +} + // JiraAllowedTargets lists the Jira projects (by key) agents may create // issues in beyond the source project. type JiraAllowedTargets struct { @@ -547,10 +598,10 @@ func (j *JiraTrackingConfig) ValidateConnection() error { // open. A query that passes cannot close the parenthesis ScopeJQLToProjects // wraps it in, so it cannot widen the project scope. func JQLParensBalanced(query string) bool { - quoted := jql.QuotedRanges(query) + quoted := quotedRanges(query) depth := 0 for i := 0; i < len(query); i++ { - if jql.InRanges(i, quoted) { + if inRanges(i, quoted) { continue } switch query[i] { diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index b68b5db598..0dc550af13 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -20,7 +20,6 @@ import ( "github.com/fullsend-ai/fullsend/internal/config" "github.com/fullsend-ai/fullsend/internal/dispatch" "github.com/fullsend-ai/fullsend/internal/forge/jira" - "github.com/fullsend-ai/fullsend/internal/jql" "github.com/fullsend-ai/fullsend/internal/normevent" "github.com/fullsend-ai/fullsend/internal/randutil" ) @@ -544,7 +543,7 @@ func uniqueIssues(issues []jira.Issue) []jira.Issue { // WARNING, once per cycle: under a backlog that order can leave older // requests waiting until they leave the window. func (p *Poller) windowJQL(query string) string { - predicate, orderBy := jql.SplitOrderBy(query) + predicate, orderBy := config.SplitJQLOrderBy(query) windowed := fmt.Sprintf(`updated >= "-%dh"`, int(math.Ceil(p.opts.FirstPollBackfillWindow.Hours()))) if predicate = strings.TrimSpace(predicate); predicate != "" { windowed = "(" + predicate + ") AND " + windowed diff --git a/internal/jql/jql.go b/internal/jql/jql.go deleted file mode 100644 index 8e6ec22f0e..0000000000 --- a/internal/jql/jql.go +++ /dev/null @@ -1,61 +0,0 @@ -// Package jql holds helpers for reading Jira Query Language strings. -package jql - -import ( - "regexp" - "strings" -) - -// orderByRe finds a trailing ORDER BY clause, case-insensitively. -var orderByRe = regexp.MustCompile(`(?i)\border\s+by\b`) - -// SplitOrderBy splits query at its last ORDER BY that is outside a -// quoted string, returning the predicate and the ORDER BY clause. -func SplitOrderBy(query string) (string, string) { - query = strings.TrimSpace(query) - quoted := QuotedRanges(query) - matches := orderByRe.FindAllStringIndex(query, -1) - for i := len(matches) - 1; i >= 0; i-- { - start := matches[i][0] - if InRanges(start, quoted) { - continue - } - return query[:start], strings.TrimSpace(query[start:]) - } - return query, "" -} - -// QuotedRanges returns the [start, end) byte ranges of single- or -// double-quoted strings in s, honoring backslash escapes. -func QuotedRanges(s string) [][2]int { - var out [][2]int - var quote byte - start := 0 - for i := 0; i < len(s); i++ { - c := s[i] - switch { - case quote != 0 && c == '\\': - i++ - case quote != 0 && c == quote: - out = append(out, [2]int{start, i + 1}) - quote = 0 - case quote == 0 && (c == '"' || c == '\''): - quote = c - start = i - } - } - if quote != 0 { - out = append(out, [2]int{start, len(s)}) - } - return out -} - -// InRanges reports whether pos lies inside one of ranges. -func InRanges(pos int, ranges [][2]int) bool { - for _, r := range ranges { - if pos >= r[0] && pos < r[1] { - return true - } - } - return false -} diff --git a/internal/jql/jql_test.go b/internal/jql/jql_test.go deleted file mode 100644 index 02afa87740..0000000000 --- a/internal/jql/jql_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package jql - -import "testing" - -func TestSplitOrderBy(t *testing.T) { - cases := []struct { - name, query, predicate, orderBy string - }{ - {name: "with order by", query: `labels = "fullsend" ORDER BY updated DESC`, predicate: `labels = "fullsend" `, orderBy: `ORDER BY updated DESC`}, - {name: "without order by", query: `labels = "fullsend"`, predicate: `labels = "fullsend"`}, - {name: "lowercase with surrounding space", query: ` status = Open order by created `, predicate: `status = Open `, orderBy: `order by created`}, - {name: "inside double quotes", query: `summary ~ "order by" AND status = Open`, predicate: `summary ~ "order by" AND status = Open`}, - {name: "inside single quotes", query: `summary ~ 'x order by y' ORDER BY key`, predicate: `summary ~ 'x order by y' `, orderBy: `ORDER BY key`}, - {name: "escaped quote", query: `summary ~ "a \" order by" ORDER BY key`, predicate: `summary ~ "a \" order by" `, orderBy: `ORDER BY key`}, - {name: "only order by", query: `ORDER BY updated DESC`, orderBy: `ORDER BY updated DESC`}, - {name: "unterminated quote", query: `summary ~ "order by`, predicate: `summary ~ "order by`}, - {name: "empty"}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - predicate, orderBy := SplitOrderBy(tc.query) - if predicate != tc.predicate || orderBy != tc.orderBy { - t.Errorf("SplitOrderBy(%q) = %q, %q; want %q, %q", tc.query, predicate, orderBy, tc.predicate, tc.orderBy) - } - }) - } -} From acbb149e1daf7587fc2f22b1d711c74ff6396082 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 07:18:47 +0200 Subject: [PATCH 21/37] fix(jirapoll): count the matrix output the way GitHub enforces its limit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The size limit on an issue's records counted two bytes per UTF-16 code unit, after GitHub's documentation, which says a job's output size is "approximated based on UTF-16 encoding". Measured on github.com, the 1 MB limit is enforced at two bytes for each byte of the output's UTF-8 text: outputs of 262,000 "é", 174,000 "語" and 131,000 "😀" are accepted, and outputs a thousand characters longer are rejected with "Job outputs exceed 1,048,576 bytes". The old count was right for ASCII and two to three times too low for every other character, so a batch of mostly non-ASCII comments could pass the 768 KB limit and still be rejected by GitHub, which loses the whole batch. Count two bytes per UTF-8 byte. Also count U+007F as the six-character escape jq writes for it, where Go writes the character itself; a new test compares the count with jq's own output for each kind of character, and is skipped where jq is not installed. Limits for plain ASCII text are unchanged. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 +- internal/jirapoll/limits.go | 34 ++++++------ internal/jirapoll/limits_test.go | 80 +++++++++++++++++++++++++--- 3 files changed, 92 insertions(+), 24 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 2aff22f6ea..05f2307589 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1455,7 +1455,7 @@ These properties are namespaced per target repo, so multiple repos can poll the **Time limits.** A cycle stops reading from Jira five minutes after it starts: the authentication check, the search, the activity filter and the selected issues all count. Reading one issue stops after two minutes. An issue that takes longer is skipped with `WARNING: reading took longer than 2m0s; ...`: none of its records are dispatched and its `lastCheck` stays where it was, so it is tried again next cycle. When the five minutes run out, the poller dispatches what it finished, commits those checkpoints and exits normally; the issue it was reading and any it had not reached wait for the next cycle, and the run log names them or says how many. Dispatching and committing are not counted against the five minutes. Running into the five minutes is not a failure by itself, so a cycle whose search used them up reads no issue and still exits normally, with a WARNING. A cycle in which every issue it read failed or took longer than two minutes does fail, so a poller blocked by slow issues shows as a failed run. The limits are not configurable. -**Per-issue limits.** One look at an issue handles at most 100 events, and the dispatch records they produce (one for each agent an event matches) are limited to 250 per issue and, on GitHub, to 768 KB of the poll job's `matrix` output. The size is counted the way GitHub counts job outputs, at two bytes per UTF-16 code unit. Over a limit the poller keeps the oldest records, drops the rest, logs `WARNING: produced dispatch records this cycle; ...`, and still advances `lastCheck`, so the dropped requests are not retried. The limits bound the agent runs that a rewound `lastCheck` or a bulk change can start from one issue: 250 is GitHub's limit of 256 jobs in a matrix less a small margin, and 768 KB is three quarters of GitHub's 1 MB limit on a job's outputs. The size limit does not apply on GitLab, which starts each pipeline separately. +**Per-issue limits.** One look at an issue handles at most 100 events, and the dispatch records they produce (one for each agent an event matches) are limited to 250 per issue and, on GitHub, to 768 KB of the poll job's `matrix` output. The size is counted the way GitHub counts job outputs, at two bytes for each byte of the output's UTF-8 text, so 768 KB is about 384 KB of JSON. Over a limit the poller keeps the oldest records, drops the rest, logs `WARNING: produced dispatch records this cycle; ...`, and still advances `lastCheck`, so the dropped requests are not retried. The limits bound the agent runs that a rewound `lastCheck` or a bulk change can start from one issue: 250 is GitHub's limit of 256 jobs in a matrix less a small margin, and 768 KB is three quarters of GitHub's 1 MB limit on a job's outputs. The size limit does not apply on GitLab, which starts each pipeline separately. > **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` property. The driver treats it as untrusted: a `lastCheck` dated 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`. diff --git a/internal/jirapoll/limits.go b/internal/jirapoll/limits.go index 6c749a40e7..e779dd3caf 100644 --- a/internal/jirapoll/limits.go +++ b/internal/jirapoll/limits.go @@ -1,12 +1,12 @@ package jirapoll import ( + "bytes" "encoding/json" "fmt" "log" "slices" "time" - "unicode/utf16" ) // Limits on the dispatch records one issue contributes to a cycle (ADR 0085, @@ -25,25 +25,29 @@ const ( // matrixEnvelopeSize is the size of a matrix output that holds no records. const matrixEnvelopeSize = 2 * len(`{"include":[]}`) -// recordOutputSize returns the size counted for one record inside the poll -// job's matrix output. The managed workflow builds that output with -// jq -c '{include: .}', so the record is measured as compact JSON. GitHub -// approximates output size from the UTF-16 encoding, so each UTF-16 code -// unit counts as two bytes. Go writes <, > and & (and U+2028, U+2029) as -// six-character escapes where jq writes the character itself, so for text -// that holds them this count is above what GitHub sees, never below. A -// record that cannot be encoded counts as empty here; writing the dispatch -// file reports it. +// recordOutputSize returns the size GitHub counts for one record inside the +// poll job's matrix output. The managed workflow builds that output with +// jq -c '{include: .}', so the record is measured as compact JSON. +// +// GitHub counts two bytes for each byte of an output's UTF-8 text. Its +// documentation says only that the size is "approximated based on UTF-16 +// encoding"; the rule here was measured on github.com in November 2026, +// where a job is rejected for outputs over 1,048,576 bytes: outputs of +// 262,000 "é", 174,000 "語" and 131,000 "😀" are accepted and outputs a +// thousand characters longer are rejected, as is one of 524,270 "a". +// +// The count is never below what GitHub sees. Go writes <, > and & (and +// U+2028, U+2029) as six-character escapes where jq writes the character +// itself, so text that holds them is counted high. jq writes U+007F as a +// six-character escape where Go writes the character, so each one counts +// for the five bytes Go did not write. A record that cannot be encoded +// counts as empty here; writing the dispatch file reports it. func recordOutputSize(record DispatchRecord) int { data, err := json.Marshal(record) if err != nil { return 0 } - units := 0 - for _, r := range string(data) { - units += utf16.RuneLen(r) - } - return 2 * units + return 2 * (len(data) + 5*bytes.Count(data, []byte{0x7f})) } // matrixOutputSize returns the size GitHub counts for the poll job's matrix diff --git a/internal/jirapoll/limits_test.go b/internal/jirapoll/limits_test.go index 84df91f643..1d8fd5ca49 100644 --- a/internal/jirapoll/limits_test.go +++ b/internal/jirapoll/limits_test.go @@ -1,46 +1,110 @@ package jirapoll import ( + "bytes" "context" "encoding/json" "fmt" + "os/exec" "strings" "testing" "time" - "unicode/utf16" "github.com/fullsend-ai/fullsend/internal/forge/jira" "github.com/fullsend-ai/fullsend/internal/normevent" ) // The matrix output is measured as the compact JSON the managed workflow -// builds, two bytes per UTF-16 code unit. +// builds, at two bytes for each byte of its UTF-8 text. func TestMatrixOutputSize(t *testing.T) { - utf16Bytes := func(s string) int { return 2 * len(utf16.Encode([]rune(s))) } + counted := func(s string) int { return 2 * len(s) } - if got, want := matrixOutputSize(nil), utf16Bytes(`{"include":[]}`); got != want { + if got, want := matrixOutputSize(nil), counted(`{"include":[]}`); got != want { t.Errorf("empty matrix = %d, want %d", got, want) } records := []DispatchRecord{ - {Agent: "triage", Role: "triage", SourceRepo: "acme/platform", EventType: "comment", EventPayload: json.RawMessage(`{"body":"héllo 😀"}`), StatusRepo: "acme/platform", StatusNumber: "7"}, + {Agent: "triage", Role: "triage", SourceRepo: "acme/platform", EventType: "comment", EventPayload: json.RawMessage(`{"body":"héllo 語 😀"}`), StatusRepo: "acme/platform", StatusNumber: "7"}, {Agent: "code", TriggerSource: "label", EventPayload: json.RawMessage(`{ "body" : "a\u003cb" }`)}, } - // é is one UTF-16 code unit and 😀 is two. The second payload is + // é is two bytes of UTF-8, 語 three and 😀 four. The second payload is // compacted, and its escaped < keeps its six characters. - want := utf16Bytes(`{"include":[` + - `{"agent":"triage","role":"triage","source_repo":"acme/platform","event_type":"comment","event_payload":{"body":"héllo 😀"},"status_repo":"acme/platform","status_number":"7"},` + + want := counted(`{"include":[` + + `{"agent":"triage","role":"triage","source_repo":"acme/platform","event_type":"comment","event_payload":{"body":"héllo 語 😀"},"status_repo":"acme/platform","status_number":"7"},` + `{"agent":"code","role":"","source_repo":"","event_type":"","event_payload":{"body":"a\u003cb"},"trigger_source":"label","status_repo":"","status_number":""}` + `]}`) if got := matrixOutputSize(records); got != want { t.Errorf("matrixOutputSize() = %d, want %d", got, want) } + // jq writes U+007F as \u007f: six bytes where Go wrote one. + plain := recordOutputSize(DispatchRecord{EventPayload: json.RawMessage(`{"body":"ab"}`)}) + withDEL := recordOutputSize(DispatchRecord{EventPayload: json.RawMessage("{\"body\":\"a\x7fb\"}")}) + if got, want := withDEL-plain, counted(`\u007f`); got != want { + t.Errorf("a U+007F adds %d, want %d", got, want) + } + if got := recordOutputSize(DispatchRecord{EventPayload: json.RawMessage(`{`)}); got != 0 { t.Errorf("a record that cannot be encoded = %d, want 0", got) } } +// The count is never below the size of the matrix jq builds from the same +// records, whatever characters a comment holds, and is exact for text that +// Go and jq write alike. +func TestMatrixOutputSizeIsNotBelowJq(t *testing.T) { + jq, err := exec.LookPath("jq") + if err != nil { + t.Skip("jq is not installed") + } + + var ascii strings.Builder + for c := rune(0); c < 0x80; c++ { + ascii.WriteRune(c) + } + bodies := map[string]string{ + "plain text": "/fs-triage please look at this", + "every ASCII code": ascii.String(), + "U+007F": strings.Repeat("\x7f", 100), + "HTML characters": strings.Repeat("<>&", 100), + "line separators": strings.Repeat("\u2028\u2029", 100), + "two-byte characters": strings.Repeat("é", 100), + "three-byte characters": strings.Repeat("語", 100), + "four-byte characters": strings.Repeat("😀", 100), + "invalid UTF-8": strings.Repeat("\xff", 100), + } + for name, body := range bodies { + t.Run(name, func(t *testing.T) { + payload, err := json.Marshal(map[string]string{"body": body}) + if err != nil { + t.Fatal(err) + } + records := []DispatchRecord{ + {Agent: "triage", EventPayload: payload, StatusNumber: "7"}, + {Agent: "code", EventPayload: payload, StatusNumber: "8"}, + } + file, err := json.Marshal(records) + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(jq, "-cj", "{include: .}") + cmd.Stdin = bytes.NewReader(file) + matrix, err := cmd.Output() + if err != nil { + t.Fatalf("jq: %v", err) + } + + got, min := matrixOutputSize(records), 2*len(matrix) + if got < min { + t.Errorf("matrixOutputSize() = %d, below the %d GitHub counts for jq's output", got, min) + } + if name == "plain text" && got != min { + t.Errorf("matrixOutputSize() = %d, want exactly %d for plain text", got, min) + } + }) + } +} + // commentMatcher produces agents records per event. Each record carries the // comment's body, so a test can tell which events' records were kept, and // pad extra characters. From 28eb759eda9d1aa9db74e8b40d9f537a012f710d Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 07:18:47 +0200 Subject: [PATCH 22/37] fix(jirapoll): count the matrix output the way GitHub enforces its limit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The size limit on an issue's records counted two bytes per UTF-16 code unit, after GitHub's documentation, which says a job's output size is "approximated based on UTF-16 encoding". Measured on github.com, the 1 MB limit is enforced at two bytes for each byte of the output's UTF-8 text: outputs of 262,000 "é", 174,000 "語" and 131,000 "😀" are accepted, and outputs a thousand characters longer are rejected with "Job outputs exceed 1,048,576 bytes". The old count was right for ASCII and two to three times too low for every other character, so a batch of mostly non-ASCII comments could pass the 768 KB limit and still be rejected by GitHub, which loses the whole batch. Count two bytes per UTF-8 byte. Also count U+007F as the six-character escape jq writes for it, where Go writes the character itself; a new test compares the count with jq's own output for each kind of character, and is skipped where jq is not installed. Limits for plain ASCII text are unchanged. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 +- internal/jirapoll/limits.go | 34 ++++++------ internal/jirapoll/limits_test.go | 80 +++++++++++++++++++++++++--- 3 files changed, 92 insertions(+), 24 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 801cd71778..375674e228 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1646,7 +1646,7 @@ These properties are namespaced per target repo, so multiple repos can poll the **Time limits.** A cycle stops reading from Jira five minutes after it starts: the authentication check, the search, the activity filter and the selected issues all count. Reading one issue stops after two minutes. An issue that takes longer is skipped with `WARNING: reading took longer than 2m0s; ...`: none of its records are dispatched and its `lastCheck` stays where it was, so it is tried again next cycle. When the five minutes run out, the poller dispatches what it finished, commits those checkpoints and exits normally; the issue it was reading and any it had not reached wait for the next cycle, and the run log names them or says how many. Dispatching and committing are not counted against the five minutes. Running into the five minutes is not a failure by itself, so a cycle whose search used them up reads no issue and still exits normally, with a WARNING. A cycle in which every issue it read failed or took longer than two minutes does fail, so a poller blocked by slow issues shows as a failed run. The limits are not configurable. -**Per-issue limits.** One look at an issue handles at most 100 events, and the dispatch records they produce (one for each agent an event matches) are limited to 250 per issue and, on GitHub, to 768 KB of the poll job's `matrix` output. The size is counted the way GitHub counts job outputs, at two bytes per UTF-16 code unit. Over a limit the poller keeps the oldest records, drops the rest, logs `WARNING: produced dispatch records this cycle; ...`, and still advances `lastCheck`, so the dropped requests are not retried. The limits bound the agent runs that a rewound `lastCheck` or a bulk change can start from one issue: 250 is GitHub's limit of 256 jobs in a matrix less a small margin, and 768 KB is three quarters of GitHub's 1 MB limit on a job's outputs. The size limit does not apply on GitLab, which starts each pipeline separately. +**Per-issue limits.** One look at an issue handles at most 100 events, and the dispatch records they produce (one for each agent an event matches) are limited to 250 per issue and, on GitHub, to 768 KB of the poll job's `matrix` output. The size is counted the way GitHub counts job outputs, at two bytes for each byte of the output's UTF-8 text, so 768 KB is about 384 KB of JSON. Over a limit the poller keeps the oldest records, drops the rest, logs `WARNING: produced dispatch records this cycle; ...`, and still advances `lastCheck`, so the dropped requests are not retried. The limits bound the agent runs that a rewound `lastCheck` or a bulk change can start from one issue: 250 is GitHub's limit of 256 jobs in a matrix less a small margin, and 768 KB is three quarters of GitHub's 1 MB limit on a job's outputs. The size limit does not apply on GitLab, which starts each pipeline separately. > **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` property. The driver treats it as untrusted: a `lastCheck` dated 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`. diff --git a/internal/jirapoll/limits.go b/internal/jirapoll/limits.go index 6c749a40e7..e779dd3caf 100644 --- a/internal/jirapoll/limits.go +++ b/internal/jirapoll/limits.go @@ -1,12 +1,12 @@ package jirapoll import ( + "bytes" "encoding/json" "fmt" "log" "slices" "time" - "unicode/utf16" ) // Limits on the dispatch records one issue contributes to a cycle (ADR 0085, @@ -25,25 +25,29 @@ const ( // matrixEnvelopeSize is the size of a matrix output that holds no records. const matrixEnvelopeSize = 2 * len(`{"include":[]}`) -// recordOutputSize returns the size counted for one record inside the poll -// job's matrix output. The managed workflow builds that output with -// jq -c '{include: .}', so the record is measured as compact JSON. GitHub -// approximates output size from the UTF-16 encoding, so each UTF-16 code -// unit counts as two bytes. Go writes <, > and & (and U+2028, U+2029) as -// six-character escapes where jq writes the character itself, so for text -// that holds them this count is above what GitHub sees, never below. A -// record that cannot be encoded counts as empty here; writing the dispatch -// file reports it. +// recordOutputSize returns the size GitHub counts for one record inside the +// poll job's matrix output. The managed workflow builds that output with +// jq -c '{include: .}', so the record is measured as compact JSON. +// +// GitHub counts two bytes for each byte of an output's UTF-8 text. Its +// documentation says only that the size is "approximated based on UTF-16 +// encoding"; the rule here was measured on github.com in November 2026, +// where a job is rejected for outputs over 1,048,576 bytes: outputs of +// 262,000 "é", 174,000 "語" and 131,000 "😀" are accepted and outputs a +// thousand characters longer are rejected, as is one of 524,270 "a". +// +// The count is never below what GitHub sees. Go writes <, > and & (and +// U+2028, U+2029) as six-character escapes where jq writes the character +// itself, so text that holds them is counted high. jq writes U+007F as a +// six-character escape where Go writes the character, so each one counts +// for the five bytes Go did not write. A record that cannot be encoded +// counts as empty here; writing the dispatch file reports it. func recordOutputSize(record DispatchRecord) int { data, err := json.Marshal(record) if err != nil { return 0 } - units := 0 - for _, r := range string(data) { - units += utf16.RuneLen(r) - } - return 2 * units + return 2 * (len(data) + 5*bytes.Count(data, []byte{0x7f})) } // matrixOutputSize returns the size GitHub counts for the poll job's matrix diff --git a/internal/jirapoll/limits_test.go b/internal/jirapoll/limits_test.go index ce23d61c0c..844802baef 100644 --- a/internal/jirapoll/limits_test.go +++ b/internal/jirapoll/limits_test.go @@ -1,46 +1,110 @@ package jirapoll import ( + "bytes" "context" "encoding/json" "fmt" + "os/exec" "strings" "testing" "time" - "unicode/utf16" "github.com/fullsend-ai/fullsend/internal/forge/jira" "github.com/fullsend-ai/fullsend/internal/normevent" ) // The matrix output is measured as the compact JSON the managed workflow -// builds, two bytes per UTF-16 code unit. +// builds, at two bytes for each byte of its UTF-8 text. func TestMatrixOutputSize(t *testing.T) { - utf16Bytes := func(s string) int { return 2 * len(utf16.Encode([]rune(s))) } + counted := func(s string) int { return 2 * len(s) } - if got, want := matrixOutputSize(nil), utf16Bytes(`{"include":[]}`); got != want { + if got, want := matrixOutputSize(nil), counted(`{"include":[]}`); got != want { t.Errorf("empty matrix = %d, want %d", got, want) } records := []DispatchRecord{ - {Agent: "triage", Role: "triage", SourceRepo: "acme/platform", EventType: "comment", EventPayload: json.RawMessage(`{"body":"héllo 😀"}`), StatusRepo: "acme/platform", StatusNumber: "7"}, + {Agent: "triage", Role: "triage", SourceRepo: "acme/platform", EventType: "comment", EventPayload: json.RawMessage(`{"body":"héllo 語 😀"}`), StatusRepo: "acme/platform", StatusNumber: "7"}, {Agent: "code", TriggerSource: "label", EventPayload: json.RawMessage(`{ "body" : "a\u003cb" }`)}, } - // é is one UTF-16 code unit and 😀 is two. The second payload is + // é is two bytes of UTF-8, 語 three and 😀 four. The second payload is // compacted, and its escaped < keeps its six characters. - want := utf16Bytes(`{"include":[` + - `{"agent":"triage","role":"triage","source_repo":"acme/platform","event_type":"comment","event_payload":{"body":"héllo 😀"},"status_repo":"acme/platform","status_number":"7"},` + + want := counted(`{"include":[` + + `{"agent":"triage","role":"triage","source_repo":"acme/platform","event_type":"comment","event_payload":{"body":"héllo 語 😀"},"status_repo":"acme/platform","status_number":"7"},` + `{"agent":"code","role":"","source_repo":"","event_type":"","event_payload":{"body":"a\u003cb"},"trigger_source":"label","status_repo":"","status_number":""}` + `]}`) if got := matrixOutputSize(records); got != want { t.Errorf("matrixOutputSize() = %d, want %d", got, want) } + // jq writes U+007F as \u007f: six bytes where Go wrote one. + plain := recordOutputSize(DispatchRecord{EventPayload: json.RawMessage(`{"body":"ab"}`)}) + withDEL := recordOutputSize(DispatchRecord{EventPayload: json.RawMessage("{\"body\":\"a\x7fb\"}")}) + if got, want := withDEL-plain, counted(`\u007f`); got != want { + t.Errorf("a U+007F adds %d, want %d", got, want) + } + if got := recordOutputSize(DispatchRecord{EventPayload: json.RawMessage(`{`)}); got != 0 { t.Errorf("a record that cannot be encoded = %d, want 0", got) } } +// The count is never below the size of the matrix jq builds from the same +// records, whatever characters a comment holds, and is exact for text that +// Go and jq write alike. +func TestMatrixOutputSizeIsNotBelowJq(t *testing.T) { + jq, err := exec.LookPath("jq") + if err != nil { + t.Skip("jq is not installed") + } + + var ascii strings.Builder + for c := rune(0); c < 0x80; c++ { + ascii.WriteRune(c) + } + bodies := map[string]string{ + "plain text": "/fs-triage please look at this", + "every ASCII code": ascii.String(), + "U+007F": strings.Repeat("\x7f", 100), + "HTML characters": strings.Repeat("<>&", 100), + "line separators": strings.Repeat("\u2028\u2029", 100), + "two-byte characters": strings.Repeat("é", 100), + "three-byte characters": strings.Repeat("語", 100), + "four-byte characters": strings.Repeat("😀", 100), + "invalid UTF-8": strings.Repeat("\xff", 100), + } + for name, body := range bodies { + t.Run(name, func(t *testing.T) { + payload, err := json.Marshal(map[string]string{"body": body}) + if err != nil { + t.Fatal(err) + } + records := []DispatchRecord{ + {Agent: "triage", EventPayload: payload, StatusNumber: "7"}, + {Agent: "code", EventPayload: payload, StatusNumber: "8"}, + } + file, err := json.Marshal(records) + if err != nil { + t.Fatal(err) + } + cmd := exec.Command(jq, "-cj", "{include: .}") + cmd.Stdin = bytes.NewReader(file) + matrix, err := cmd.Output() + if err != nil { + t.Fatalf("jq: %v", err) + } + + got, min := matrixOutputSize(records), 2*len(matrix) + if got < min { + t.Errorf("matrixOutputSize() = %d, below the %d GitHub counts for jq's output", got, min) + } + if name == "plain text" && got != min { + t.Errorf("matrixOutputSize() = %d, want exactly %d for plain text", got, min) + } + }) + } +} + // commentMatcher produces agents records per event. Each record carries the // comment's body, so a test can tell which events' records were kept, and // pad extra characters. From 0a619f0f27eb30a9f650901530f0b822f80f3e9d Mon Sep 17 00:00:00 2001 From: guy oron Date: Mon, 30 Nov 2026 12:54:38 +0200 Subject: [PATCH 23/37] fix(jirapoll): hold the issue time limit when it passes inside the matcher Review follow-up for the per-issue time limit. Run looked at an issue's time limit only when processIssue returned an error. processIssue drops an event whose match fails and advances the checkpoint past it, so a matcher that honours its context and ran out of time after an issue's first event would lose the issue's other requests. The matcher fullsend ships ignores its context, so no request is lost today. Run now treats a passed limit the same way with or without an error: none of the issue's records are taken and its lastCheck stays. Signed-off-by: guy oron --- internal/jirapoll/poller.go | 8 +++++ internal/jirapoll/poller_idle_test.go | 48 +++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 198731d218..d96baf3564 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -188,6 +188,14 @@ func (p *Poller) Run(ctx context.Context) error { pc, err := p.processIssue(issueCtx, issue) issueTimedOut := errors.Is(issueCtx.Err(), context.DeadlineExceeded) cancelIssue() + // A time limit that passed while the issue was read ends it the + // same way when processIssue reports no error. A matcher that + // honours its context fails the events it had left; processIssue + // drops an event whose match failed and advances past it, so + // taking the result would lose those requests. + if err == nil && issueTimedOut { + err = context.DeadlineExceeded + } if err != nil { var rle *roleLoadError switch { diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index 521176bbed..235f5a94fe 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/normevent" ) // Tests for ADR 0160: the poller skips candidates with nothing new since @@ -709,6 +710,53 @@ func TestRunIssueTimeLimit(t *testing.T) { } } +// slowMatcher matches the first event of the issue with ID slow and holds +// that issue's later events until the call's context ends, like a matcher +// that honours its context. +type slowMatcher struct { + stubMatcher + slow string + calls int +} + +func (m *slowMatcher) Match(ctx context.Context, event *normevent.Event) ([]DispatchRecord, error) { + if fmt.Sprintf("%d", event.Entity.ID) == m.slow { + if m.calls++; m.calls > 1 { + <-ctx.Done() + return nil, ctx.Err() + } + } + return m.stubMatcher.Match(ctx, event) +} + +// The per-issue limit holds when it passes inside the matcher, where the +// failure does not reach Run as an error: an event whose match fails is +// dropped and the checkpoint advances past it. An issue that ran out of +// time after its first event contributes none of its records and keeps its +// lastCheck, so the next cycle serves all of its requests. +func TestRunIssueTimeLimitInsideTheMatcher(t *testing.T) { + logs := captureLog(t) + mc := newMockClient() + p := timeLimitPoller(t, mc, nil, time.Hour, 50*time.Millisecond) + addTriageComment(mc, "PROJ-1", "503", time.Now().Truncate(time.Second).Add(-30*time.Second)) + p.matcher = &slowMatcher{stubMatcher: stubMatcher{agents: []string{"triage"}}, slow: "10001"} + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + if got := dispatchedKeys(p); len(got) != 1 || got[0] != "10002" { + t.Errorf("dispatched for %v, want PROJ-2 only", got) + } + if !storedLastCheckAt(t, mc, "PROJ-1").IsZero() { + t.Error("the timed-out issue's lastCheck advanced") + } + if storedLastCheckAt(t, mc, "PROJ-2").IsZero() { + t.Error("the served issue's lastCheck was not committed") + } + if want := "WARNING: reading PROJ-1 took longer than 50ms"; !strings.Contains(logs.String(), want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } +} + // The cycle limit stops reading mid-issue: the cycle dispatches and commits // what it finished and exits normally, and the cut-off issue's request is // served by the next cycle. From d226986f60fc68e9022f52b572ace669fa88a466 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 11:57:02 +0200 Subject: [PATCH 24/37] docs(jira-poll): add troubleshooting rows for overlapping cycles and a failed write check With the per-issue lock gone, two cycles that overlap dispatch the same requests twice, and an issue the credential cannot write to is skipped with a warning. The Troubleshooting table had a row for neither: its only row on duplicate dispatches gave a cleared lastCheck as the cause. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 39bd0c3407..838bf52053 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1754,6 +1754,8 @@ However, more pollers against the same Jira project means more API calls per cyc | `the jira-poll driver requires tracker.jira in config.yaml` | The effective config has no `tracker.jira` site and project | Set `tracker.jira.base_url` and `tracker.jira.project` — see [Custom JQL](#custom-jql) | | `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 | +| Duplicate dispatches that keep happening | Two poll cycles for the same repository ran at the same time: a second workflow or job polls the repository, or a scheduler other than the managed one lets cycles overlap | The poller keeps no per-issue lock, so overlapping cycles dispatch the same requests twice. Run one poller per repository and keep its cycles from overlapping; on GitHub Actions the poll job needs a concurrency group with `cancel-in-progress: false`. See [Scheduled workflow](#scheduled-workflow) | +| `WARNING: processing : check write access to : ...` in the poll log, or the poll fails with `all N selected issues failed to process` | The Jira credential cannot write to the issue. Before it reads an issue the poller writes a property on it, which needs **Edit Issues** | Grant the poller account Edit Issues on the project — see [Minimum Jira permissions](#minimum-jira-permissions). An issue that fails the check is skipped: nothing is dispatched for it and its `lastCheck` does not move, so it is read again on the next cycle. The run fails only when every issue the cycle read failed; the `WARNING: processing : ...` lines above the error give each issue's cause, which can be other than write access | | 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 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) | From 820d2b8daa39c812f557605bc16afbde4b82c319 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 11:58:18 +0200 Subject: [PATCH 25/37] docs(jira-poll): count a slow issue as failed in the write-check troubleshooting row A cycle now also fails when every issue it read took longer than the per-issue time limit, and such an issue has its own WARNING line. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 31a1261ba4..f2e0eef036 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1757,7 +1757,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 | | Duplicate dispatches that keep happening | Two poll cycles for the same repository ran at the same time: a second workflow or job polls the repository, or a scheduler other than the managed one lets cycles overlap | The poller keeps no per-issue lock, so overlapping cycles dispatch the same requests twice. Run one poller per repository and keep its cycles from overlapping; on GitHub Actions the poll job needs a concurrency group with `cancel-in-progress: false`. See [Scheduled workflow](#scheduled-workflow) | -| `WARNING: processing : check write access to : ...` in the poll log, or the poll fails with `all N selected issues failed to process` | The Jira credential cannot write to the issue. Before it reads an issue the poller writes a property on it, which needs **Edit Issues** | Grant the poller account Edit Issues on the project — see [Minimum Jira permissions](#minimum-jira-permissions). An issue that fails the check is skipped: nothing is dispatched for it and its `lastCheck` does not move, so it is read again on the next cycle. The run fails only when every issue the cycle read failed; the `WARNING: processing : ...` lines above the error give each issue's cause, which can be other than write access | +| `WARNING: processing : check write access to : ...` in the poll log, or the poll fails with `all N selected issues failed to process` | The Jira credential cannot write to the issue. Before it reads an issue the poller writes a property on it, which needs **Edit Issues** | Grant the poller account Edit Issues on the project — see [Minimum Jira permissions](#minimum-jira-permissions). An issue that fails the check is skipped: nothing is dispatched for it and its `lastCheck` does not move, so it is read again on the next cycle. The run fails only when every issue the cycle read failed or took longer than its time limit; the `WARNING` lines above the error give each issue's cause, which can be other than write access | | 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 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) | From 8827fae63c1957057eccf076cc61b9a9a6f228b6 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 12:01:09 +0200 Subject: [PATCH 26/37] docs(jira-poll): name the token scope the write check needs Setting an issue property needs the Edit Issues permission and, for an OAuth or scoped token, the write:jira-work scope (Atlassian's REST API reference, "Set issue property"). A token can hold the permission and lack the scope, which is the case the write check exists to catch. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 838bf52053..c346fe959b 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1755,7 +1755,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 | | Duplicate dispatches that keep happening | Two poll cycles for the same repository ran at the same time: a second workflow or job polls the repository, or a scheduler other than the managed one lets cycles overlap | The poller keeps no per-issue lock, so overlapping cycles dispatch the same requests twice. Run one poller per repository and keep its cycles from overlapping; on GitHub Actions the poll job needs a concurrency group with `cancel-in-progress: false`. See [Scheduled workflow](#scheduled-workflow) | -| `WARNING: processing : check write access to : ...` in the poll log, or the poll fails with `all N selected issues failed to process` | The Jira credential cannot write to the issue. Before it reads an issue the poller writes a property on it, which needs **Edit Issues** | Grant the poller account Edit Issues on the project — see [Minimum Jira permissions](#minimum-jira-permissions). An issue that fails the check is skipped: nothing is dispatched for it and its `lastCheck` does not move, so it is read again on the next cycle. The run fails only when every issue the cycle read failed; the `WARNING: processing : ...` lines above the error give each issue's cause, which can be other than write access | +| `WARNING: processing : check write access to : ...` in the poll log, or the poll fails with `all N selected issues failed to process` | The Jira credential cannot write to the issue. Before it reads an issue the poller writes a property on it, which needs **Edit Issues** and, with an OAuth or scoped token, the `write:jira-work` scope (granular: `write:issue.property:jira`) | Grant the poller account Edit Issues on the project — see [Minimum Jira permissions](#minimum-jira-permissions) — or add the scope to the token. An issue that fails the check is skipped: nothing is dispatched for it and its `lastCheck` does not move, so it is read again on the next cycle. The run fails only when every issue the cycle read failed; the `WARNING: processing : ...` lines above the error give each issue's cause, which can be other than write access | | 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 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) | From 07582e18854875d109ce22cb57e0786a08974e3e Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 13:38:40 +0200 Subject: [PATCH 27/37] docs(jirapoll): drop the lock from the entity execution table and a test comment The capability table in the entity execution contract came with main and still said the jira-poll driver owns dispatch through checkpoints and lock properties. The driver keeps no lock on this branch. The comment of TestPropertyKey_DottedSlugsDoNotCollide named a lock key where the test checks the write-check key. Signed-off-by: guy oron --- docs/normative/entity-execution-cli/v1/README.md | 2 +- internal/jirapoll/poller_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/normative/entity-execution-cli/v1/README.md b/docs/normative/entity-execution-cli/v1/README.md index c9266e5578..507cdb691d 100644 --- a/docs/normative/entity-execution-cli/v1/README.md +++ b/docs/normative/entity-execution-cli/v1/README.md @@ -95,7 +95,7 @@ A provider/kind pair becomes eligible when it has all four capabilities: | GitHub issue, pull request | Mapped | Covered | Bounded GitHub filter subset for both kinds, with GraphQL advanced search for combined discovery and selective acquisition | A selective-acquisition adapter exists (`internal/forge/github.EntityAdapter`), but source membership and snapshot staging remain pending under [#9598](https://github.com/fullsend-ai/fullsend/issues/9598), so the pair stays ineligible. The existing GitHub `forge.Client` already reads issues, pull requests, comments, label events, reviews, and review threads. No `fullsend poll` driver uses GitHub, so entity discovery competes with no driver | | GitHub Discussion | Mapped | Covered | None. The GitHub subset guards only `is:issue` and `is:pr` | No Discussion ingress or conversation client under [ADR 0086](../../../ADRs/0086-conversation-surface-for-agent-participation.md) | | GitLab issue, merge request | Mapped. Reviews, reactions, issue type, and close reason are `unsupported` | Covered | Only the `open`, `closed`, and `all` presets | No entity adapter. The `--forge gitlab` poller and the webhook fast path own dispatch through shared poll state ([ADR 0125](../../../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md), [ADR 0132](../../../ADRs/0132-occurrence-aware-shared-poller-state.md)). Cutover needs a plan for that state | -| Jira issue | Mapped. Complete `label_applications` needs full changelog coverage | Covered | Native JQL within a project guard | No entity adapter. The `jira-poll` driver owns dispatch through checkpoints and lock properties. The source project is separate from the target code repository | +| Jira issue | Mapped. Complete `label_applications` needs full changelog coverage | Covered | Native JQL within a project guard | No entity adapter. The `jira-poll` driver owns dispatch through checkpoints. The source project is separate from the target code repository | #### Why GitHub issues and pull requests come first diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index f8efd944da..d9ac1bcb3f 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -1035,7 +1035,7 @@ func TestReadLastCheck_ClampsUntrustedValues(t *testing.T) { } // TestPropertyKey_DottedSlugsDoNotCollide: distinct target repos with dots -// must not collapse to the same lock/lastCheck property key. +// must not collapse to the same writeCheck/lastCheck property key. func TestPropertyKey_DottedSlugsDoNotCollide(t *testing.T) { o1, r1 := splitOwnerRepo("a.b/c") o2, r2 := splitOwnerRepo("a/b.c") From 8ff4790dfac363bc74fac67511f586f919ec98ee Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 13:40:17 +0200 Subject: [PATCH 28/37] fix(jirapoll): leave a discarded issue out of the cycle's event counts An issue that times out, or fails, contributes no records and no checkpoint, but the events it had converted stayed in the counts the all-dropped guard reads. An event it matched before timing out then kept the guard from firing for another issue whose events were all dropped, and that issue's lastCheck advanced past requests that were never dispatched. The counts are now put back when an issue's result is not taken. Signed-off-by: guy oron --- internal/jirapoll/poller.go | 7 ++++++ internal/jirapoll/poller_idle_test.go | 32 +++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index f4ca03ca75..b7415383cb 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -182,6 +182,7 @@ func (p *Poller) Run(ctx context.Context) error { } tried++ issueCtx, cancelIssue := context.WithTimeout(readCtx, p.opts.IssueTimeLimit) + seen, invalid, matchErrors := p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors pc, err := p.processIssue(issueCtx, issue) issueTimedOut := errors.Is(issueCtx.Err(), context.DeadlineExceeded) cancelIssue() @@ -194,6 +195,12 @@ func (p *Poller) Run(ctx context.Context) error { err = context.DeadlineExceeded } if err != nil { + // An issue whose result is not taken leaves the cycle's event + // counts as they were, so the all-dropped guard below judges + // only the events of the issues it commits. Otherwise an event + // this issue matched before it timed out would keep the guard + // from firing for another issue whose events were all dropped. + p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors = seen, invalid, matchErrors var rle *roleLoadError switch { case ctx.Err() != nil: diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index 030f00e9cc..d8bf4fde72 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -714,11 +714,15 @@ func TestRunIssueTimeLimit(t *testing.T) { // that honours its context. type slowMatcher struct { stubMatcher - slow string - calls int + slow string + failing string // entity ID whose events fail matching + calls int } func (m *slowMatcher) Match(ctx context.Context, event *normevent.Event) ([]DispatchRecord, error) { + if fmt.Sprintf("%d", event.Entity.ID) == m.failing { + return nil, errors.New("match failed") + } if fmt.Sprintf("%d", event.Entity.ID) == m.slow { if m.calls++; m.calls > 1 { <-ctx.Done() @@ -756,6 +760,30 @@ func TestRunIssueTimeLimitInsideTheMatcher(t *testing.T) { } } +// A discarded issue's events do not count toward the cycle's all-dropped +// guard. PROJ-1 matches one event and then runs out of time, so none of its +// records are taken; the one event of PROJ-2 fails matching. If PROJ-1's +// matched event still counted, the guard would not fire and PROJ-2's +// lastCheck would advance past a request that was never dispatched. +func TestRunTimedOutIssueDoesNotCountTowardAllDroppedGuard(t *testing.T) { + mc := newMockClient() + p := timeLimitPoller(t, mc, nil, time.Hour, 50*time.Millisecond) + addTriageComment(mc, "PROJ-1", "503", time.Now().Truncate(time.Second).Add(-30*time.Second)) + p.matcher = &slowMatcher{stubMatcher: stubMatcher{agents: []string{"triage"}}, slow: "10001", failing: "10002"} + err := p.Run(context.Background()) + if want := "all 1 events this cycle were dropped before dispatch (0 failed normalized-event validation, 1 failed matching)"; err == nil || !strings.Contains(err.Error(), want) { + t.Fatalf("Run() error = %v, want %q", err, want) + } + if got := dispatchedKeys(p); len(got) != 0 { + t.Errorf("dispatched for %v, want nothing", got) + } + for _, key := range []string{"PROJ-1", "PROJ-2"} { + if !storedLastCheckAt(t, mc, key).IsZero() { + t.Errorf("the lastCheck of %s advanced", key) + } + } +} + // The cycle limit stops reading mid-issue: the cycle dispatches and commits // what it finished and exits normally, and the cut-off issue's request is // served by the next cycle. From eb0498fe49790903feccf944e8d9a42c80060329 Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 2 Dec 2026 12:54:57 +0200 Subject: [PATCH 29/37] fix(jirapoll): keep a timed-out issue out of the no-match warning An issue that timed out after an event matched no agent stayed in the cycle's list of unmatched events, so the warning could name an issue whose remaining events were never tried. Its entries are now dropped with its event counts. Signed-off-by: guy oron --- internal/jirapoll/poller.go | 5 ++++- internal/jirapoll/poller_idle_test.go | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 46b17e8ade..bbd14fc27a 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -184,7 +184,7 @@ func (p *Poller) Run(ctx context.Context) error { } tried++ issueCtx, cancelIssue := context.WithTimeout(readCtx, p.opts.IssueTimeLimit) - seen, invalid, matchErrors := p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors + seen, invalid, matchErrors, unmatched := p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors, len(p.unmatched) pc, err := p.processIssue(issueCtx, issue) issueTimedOut := errors.Is(issueCtx.Err(), context.DeadlineExceeded) cancelIssue() @@ -202,7 +202,10 @@ func (p *Poller) Run(ctx context.Context) error { // only the events of the issues it commits. Otherwise an event // this issue matched before it timed out would keep the guard // from firing for another issue whose events were all dropped. + // Its unmatched events leave the no-match warning the same way: + // the events it had left were never tried against an agent. p.eventsSeen, p.eventsInvalid, p.eventsMatchErrors = seen, invalid, matchErrors + p.unmatched = p.unmatched[:unmatched] var rle *roleLoadError switch { case ctx.Err() != nil: diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index 0f95fbbb8c..2de53f1ff0 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -740,6 +740,27 @@ func (m *slowMatcher) Match(ctx context.Context, event *normevent.Event) ([]Disp return m.stubMatcher.Match(ctx, event) } +// An issue that timed out stays out of the no-match warning. The warning +// says no agent matched the events of the issues it names, and the events a +// timed-out issue had left were never tried. +func TestRunTimedOutIssueStaysOutOfNoMatchWarning(t *testing.T) { + annotations := captureAnnotations(t) + mc := newMockClient() + p := timeLimitPoller(t, mc, nil, time.Hour, 50*time.Millisecond) + addTriageComment(mc, "PROJ-1", "503", time.Now().Truncate(time.Second).Add(-30*time.Second)) + p.matcher = &slowMatcher{slow: "10001"} + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + got := annotations.String() + if want := "PROJ-2 (comment_added /fs-triage)"; !strings.Contains(got, want) { + t.Errorf("warning lacks %q:\n%s", want, got) + } + if strings.Contains(got, "PROJ-1") { + t.Errorf("warning names the timed-out issue:\n%s", got) + } +} + // The per-issue limit holds when it passes inside the matcher, where the // failure does not reach Run as an error: an event whose match fails is // dropped and the checkpoint advances past it. An issue that ran out of From 42af816cdd9f3edffa04c49d63a1a288fe1a98b5 Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 2 Dec 2026 13:07:15 +0200 Subject: [PATCH 30/37] test(config): expect the default poll query without an ordering The effective-config test that came with main's entity-source changes spells out the query translated from tracker.jira. This branch drops ORDER BY updated DESC from the default query, so the expected value loses it too. Signed-off-by: guy oron --- internal/config/entity_sources_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/config/entity_sources_test.go b/internal/config/entity_sources_test.go index ede2447135..bc3c2f9a56 100644 --- a/internal/config/entity_sources_test.go +++ b/internal/config/entity_sources_test.go @@ -582,7 +582,7 @@ func TestEffectiveYAML_NormalizedTracker(t *testing.T) { connection: jira projects: - PROJ - query: statusCategory != Done ORDER BY updated DESC + query: statusCategory != Done discovery: true origin: translated command_default: From b66e01c1c5a96ee252c244372aa75aadfe92ddc7 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 00:40:51 +0200 Subject: [PATCH 31/37] docs(jira-poll): wrap the time-limit paragraphs at 80 columns Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 05e999da27..ccf3c51ef8 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1726,7 +1726,20 @@ The poller uses Jira entity properties for checkpoint tracking. It keeps no per- 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. -**Time limits.** A cycle stops reading from Jira five minutes after it starts: the authentication check, the search, the activity filter and the selected issues all count. Reading one issue stops after two minutes. An issue that takes longer is skipped with `WARNING: reading took longer than 2m0s; ...`: none of its records are dispatched and its `lastCheck` stays where it was, so it is tried again next cycle. When the five minutes run out, the poller dispatches what it finished, commits those checkpoints and exits normally; the issue it was reading and any it had not reached wait for the next cycle, and the run log names them or says how many. Dispatching and committing are not counted against the five minutes. Running into the five minutes is not a failure by itself, so a cycle whose search used them up reads no issue and still exits normally, with a WARNING. A cycle in which every issue it read failed or took longer than two minutes does fail, so a poller blocked by slow issues shows as a failed run. The limits are not configurable. +**Time limits.** A cycle stops reading from Jira five minutes after it starts: +the authentication check, the search, the activity filter and the selected +issues all count. Reading one issue stops after two minutes. An issue that takes +longer is skipped with `WARNING: reading took longer than 2m0s; ...`: none +of its records are dispatched and its `lastCheck` stays where it was, so it is +tried again next cycle. When the five minutes run out, the poller dispatches +what it finished, commits those checkpoints and exits normally; the issue it was +reading and any it had not reached wait for the next cycle, and the run log +names them or says how many. Dispatching and committing are not counted against +the five minutes. Running into the five minutes is not a failure by itself, so a +cycle whose search used them up reads no issue and still exits normally, with a +WARNING. A cycle in which every issue it read failed or took longer than two +minutes does fail, so a poller blocked by slow issues shows as a failed run. The +limits are not configurable. > **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` property. The driver treats it 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`. @@ -1766,7 +1779,14 @@ 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. 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 slow a cycle down.** Each Jira call retries up to 5 times with exponential backoff, honoring `Retry-After` (capped at 5 minutes). While the poller is reading, those waits count against the time limits above, so retries cannot hold one issue for more than two minutes or the reading for more than five. Committing checkpoints is not limited and can still run long under a sustained 429 or outage; 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. +- **Sustained Jira errors slow a cycle down.** Each Jira call retries up to 5 + times with exponential backoff, honoring `Retry-After` (capped at 5 minutes). + While the poller is reading, those waits count against the time limits above, + so retries cannot hold one issue for more than two minutes or the reading for + more than five. Committing checkpoints is not limited and can still run long + under a sustained 429 or outage; 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. ## Multi-repo polling From 96805f51834e1fb2c5feb485d7c9186f3a8892fb Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 00:41:23 +0200 Subject: [PATCH 32/37] docs(jira-poll): wrap the backfill-window paragraph at 80 columns Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 3beb1d2f43..ce2184962d 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1789,7 +1789,18 @@ Because each cron run is a fresh process, per-cycle Jira API cost is worth sizin Two more scaling limits: -- **Every cycle lists the whole backfill window.** The search reads every issue that matches the query and changed within the last 24 hours, 50 rows per call, including issues already handled. A project where many issues change each day pays for that listing every cycle, and it counts against the cycle's five-minute time limit. The search stops after 200 calls (10,000 issues at 50 per call) and logs `WARNING: the search stopped after issues with more remaining; ...`; the issues beyond them are not examined that cycle. A cycle still processes at most N (default 5) of the issues with new activity, picked at random, so under a sustained backlog an issue can lose the draw until its request leaves the window. Narrow `tracker.jira.poll.query` (for example to a label or a subset of issue types) if either applies to you. +- **Every cycle lists the whole backfill window.** The search reads every issue + that matches the query and changed within the last 24 hours, 50 rows per call, + including issues already handled. A project where many issues change each day + pays for that listing every cycle, and it counts against the cycle's + five-minute time limit. The search stops after 200 calls (10,000 issues at 50 + per call) and logs + `WARNING: the search stopped after issues with more remaining; ...`; the + issues beyond them are not examined that cycle. A cycle still processes at + most N (default 5) of the issues with new activity, picked at random, so under + a sustained backlog an issue can lose the draw until its request leaves the + window. Narrow `tracker.jira.poll.query` (for example to a label or a subset + of issue types) if either 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 slow a cycle down.** Each Jira call retries up to 5 times with exponential backoff, honoring `Retry-After` (capped at 5 minutes). From 3d9df689784e2678270a35af00e75c0765af4513 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 00:41:31 +0200 Subject: [PATCH 33/37] docs(jira-poll): wrap the per-issue limits paragraph at 80 columns Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 68f1789afe..67a6930565 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1752,7 +1752,18 @@ WARNING. A cycle in which every issue it read failed or took longer than two minutes does fail, so a poller blocked by slow issues shows as a failed run. The limits are not configurable. -**Per-issue limits.** One look at an issue handles at most 100 events, and the dispatch records they produce (one for each agent an event matches) are limited to 250 per issue and, on GitHub, to 768 KB of the poll job's `matrix` output. The size is counted the way GitHub counts job outputs, at two bytes for each byte of the output's UTF-8 text, so 768 KB is about 384 KB of JSON. Over a limit the poller keeps the oldest records, drops the rest, logs `WARNING: produced dispatch records this cycle; ...`, and still advances `lastCheck`, so the dropped requests are not retried. The limits bound the agent runs that a rewound `lastCheck` or a bulk change can start from one issue: 250 is GitHub's limit of 256 jobs in a matrix less a small margin, and 768 KB is three quarters of GitHub's 1 MB limit on a job's outputs. The size limit does not apply on GitLab, which starts each pipeline separately. +**Per-issue limits.** One look at an issue handles at most 100 events, and the +dispatch records they produce (one for each agent an event matches) are limited +to 250 per issue and, on GitHub, to 768 KB of the poll job's `matrix` output. +The size is counted the way GitHub counts job outputs, at two bytes for each +byte of the output's UTF-8 text, so 768 KB is about 384 KB of JSON. Over a limit +the poller keeps the oldest records, drops the rest, logs +`WARNING: produced dispatch records this cycle; ...`, and still +advances `lastCheck`, so the dropped requests are not retried. The limits bound +the agent runs that a rewound `lastCheck` or a bulk change can start from one +issue: 250 is GitHub's limit of 256 jobs in a matrix less a small margin, and +768 KB is three quarters of GitHub's 1 MB limit on a job's outputs. The size +limit does not apply on GitLab, which starts each pipeline separately. > **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` property. The driver treats it 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`. From 20982f4eeb9227eb2e6f77e6642ec4ffb0040b22 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 16:03:54 +0200 Subject: [PATCH 34/37] test(jirapoll): pin that an unparseable lastCheck is unset, not floored Every unparseable row of the filter's decision table had updated one hour ago, inside the backfill window, where "treated as unset" and "floored to the window start" give the same answer. The new row has updated three days ago: unset keeps the issue active, while a floor would drop it and leave the bad value stored. Signed-off-by: guy oron --- internal/jirapoll/poller_idle_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index d83e016cab..d21eca132f 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -437,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}, From e1bf3983d31a18439fb24fb57c405b25da8169db Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 16:06:06 +0200 Subject: [PATCH 35/37] refactor(jirapoll): drop the unused delete from the poller's Jira client With the lock gone the driver deletes no entity property, so DeleteEntityProperty leaves the JiraClient interface and the test mock. A delete now fails to compile, which replaces the mock's delete counter. TestRunIgnoresLegacyLock also fails if the legacy lock is read: until now a filter that read it and skipped the issue on a read error passed. Signed-off-by: guy oron --- internal/jirapoll/poller_idle_test.go | 6 ++--- internal/jirapoll/poller_test.go | 35 +++++++++------------------ internal/jirapoll/types.go | 1 - 3 files changed, 15 insertions(+), 27 deletions(-) diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index e3a1762486..494f71daef 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -112,9 +112,9 @@ func TestRunSkipsIdleCandidates(t *testing.T) { } 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 c := mc.listCommentsCalls[key] + mc.listChangelogCalls[key] + mc.propertySetCalls[key]; c != 0 { + t.Errorf("idle %s: comments %d, changelog %d, property writes %d; want all zero", + key, mc.listCommentsCalls[key], mc.listChangelogCalls[key], mc.propertySetCalls[key]) } } if want := "poll complete: 10 candidates, 3 active, 3 selected, 3 dispatches"; !strings.Contains(logs.String(), want) { diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index d9ac1bcb3f..ffc25787f7 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -65,11 +65,10 @@ type mockClient struct { userGroupsCalls map[string]int // accountID -> GetUserGroups call count // Per-issue call counts, so a test can show an issue cost nothing, - // including a write or a delete that the end state would not 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 + // including a write that the end state would not show. + listCommentsCalls map[string]int // issueKey -> ListComments calls + listChangelogCalls map[string]int // issueKey -> ListChangelog calls + propertySetCalls map[string]int // issueKey -> SetEntityProperty calls // getPropertyHook, if set, runs after each GetEntityProperty call // captures its return value, and before that value is returned. Used @@ -93,10 +92,9 @@ func newMockClient() *mockClient { 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), + listCommentsCalls: make(map[string]int), + listChangelogCalls: make(map[string]int), + propertySetCalls: make(map[string]int), } } @@ -192,17 +190,6 @@ func (m *mockClient) SetEntityProperty(_ context.Context, issueKey, propKey stri return nil } -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) - } - return nil -} - func (m *mockClient) GetMyself(_ context.Context) (*jira.User, error) { if m.myselfErr != nil { return nil, m.myselfErr @@ -1461,6 +1448,11 @@ func TestRunIgnoresLegacyLock(t *testing.T) { const legacyLockKey = "fullsend.poll.acme.platform.lock" legacyLock := json.RawMessage(`{"id":"other-poller-uuid","ts":"` + now.Format(time.RFC3339) + `","phase":"running"}`) mc.properties["PROJ-123"] = map[string]json.RawMessage{legacyLockKey: legacyLock} + mc.getPropertyHook = func(issueKey, propKey string) { + if propKey == legacyLockKey { + t.Errorf("read the legacy lock of %s", issueKey) + } + } router := &stubMatcher{agents: []string{"triage"}} p := newTestPoller(mc, router, Options{ @@ -1479,9 +1471,6 @@ func TestRunIgnoresLegacyLock(t *testing.T) { if got := string(mc.properties["PROJ-123"][legacyLockKey]); got != string(legacyLock) { t.Errorf("legacy lock = %s, want it untouched", got) } - if mc.propertyDeleteCalls["PROJ-123"] != 0 { - t.Errorf("deleted %d properties, want 0", mc.propertyDeleteCalls["PROJ-123"]) - } var checked string if err := json.Unmarshal(mc.properties["PROJ-123"][writeCheckPropertyKey("acme", "platform")], &checked); err != nil { t.Fatalf("write-check property: %v", err) diff --git a/internal/jirapoll/types.go b/internal/jirapoll/types.go index 42b74a53da..ad2c86ebdc 100644 --- a/internal/jirapoll/types.go +++ b/internal/jirapoll/types.go @@ -26,7 +26,6 @@ type JiraClient interface { ListChangelog(ctx context.Context, issueIDOrKey string) ([]jira.ChangelogEntry, error) GetEntityProperty(ctx context.Context, issueIDOrKey, propertyKey string) (json.RawMessage, error) SetEntityProperty(ctx context.Context, issueIDOrKey, propertyKey string, value any) error - DeleteEntityProperty(ctx context.Context, issueIDOrKey, propertyKey string) error GetMyself(ctx context.Context) (*jira.User, error) // GetProjectRoleActors returns direct users and group assignments per // role without enumerating group members (no pagination cap). From 5ffdb8ef4ec0d6bd0d2052b797d6c4f0171d0ac3 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 16:07:27 +0200 Subject: [PATCH 36/37] test(scaffold): pin the GitLab poll job's resource group The jira-poll driver keeps no per-issue lock, so on GitLab the poll job's resource group is what keeps two cycles apart. Nothing failed if the template lost it. Signed-off-by: guy oron --- internal/scaffold/gitlab_job_scripts_test.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/internal/scaffold/gitlab_job_scripts_test.go b/internal/scaffold/gitlab_job_scripts_test.go index 8a57dabf33..a57b240c6e 100644 --- a/internal/scaffold/gitlab_job_scripts_test.go +++ b/internal/scaffold/gitlab_job_scripts_test.go @@ -300,6 +300,18 @@ func TestRunPollJobScript_JiraModeRunsJiraPoller(t *testing.T) { assert.Contains(t, got, "WEBHOOK_SECRET=unset") } +// The jira-poll driver keeps no per-issue lock (ADR 0085), so on GitLab this +// resource group is what keeps two poll cycles of one mode from overlapping. +func TestPollJobResourceGroup(t *testing.T) { + var jobs map[string]struct { + ResourceGroup string `yaml:"resource_group"` + } + gitlabLastYAMLDocument(t, ".gitlab/ci/fullsend-poll.yml", &jobs) + job, ok := jobs["$[[ inputs.schedule_name | expand_vars ]]"] + require.True(t, ok, "the scheduled poll job must exist") + assert.Equal(t, "fullsend-poll-$FULLSEND_POLL_MODE", job.ResourceGroup) +} + // The same operator-supplied GitHub token used by the installer must survive // both shipped scripts and reach the Jira poll command. No GitLab credential // may be substituted when the operator leaves the GitHub token unset. From f821b6184d5492324ac600bdcab73d12154cbf9f Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 16:07:43 +0200 Subject: [PATCH 37/37] docs(jira-poll): say the lock is gone in two places that still expect it docs/architecture.md called the lock's removal a target state, and the normalized-entity spec listed an operational lock among the properties Fullsend keeps on an issue. The driver now writes a write-check property instead. Signed-off-by: guy oron --- docs/architecture.md | 4 ++-- docs/normative/normalized-entity/v1/README.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 80242addd4..aa9feef527 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -563,8 +563,8 @@ The existing design principle is that [the repo is the coordinator](problems/age input drivers to discover work from remote systems (Jira first), coordinates via source-native write-then-verify locks, and feeds the same dispatch pipeline as webhooks ([ADR 0063](ADRs/0063-polling-based-work-discovery.md)). Initial - scope is per-repo mode only. In the target state the `jira-poll` driver no - longer uses those locks (see the next item). + scope is per-repo mode only. The `jira-poll` driver no longer uses those + locks (see the next item). - Jira poll candidate selection (target state): one poller per repository reads every issue that changed within the backfill window (`tracker.jira.poll.backfill_window_hours`, default 24), oldest change diff --git a/docs/normative/normalized-entity/v1/README.md b/docs/normative/normalized-entity/v1/README.md index 9fcf0fc04e..fd387ac4e7 100644 --- a/docs/normative/normalized-entity/v1/README.md +++ b/docs/normative/normalized-entity/v1/README.md @@ -340,7 +340,7 @@ change attribution can retain it for host-side diagnostics, but binds its CEL can attribute selected field changes when its relevant history is complete; the issue and comment property read APIs return keys and values without a writer, so a property needs independent trusted provenance before becoming an -actionable known CEL value. Fullsend's operational lock, checkpoint, and +actionable known CEL value. Fullsend's operational write-check, checkpoint, and comment-marker properties stay in host-side coordination state by default; their API visibility does not establish trustworthy authorship or a dispatch grant.