From 527843f113cb5066be4947aa5fa2bf4d246b0b7c Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 25 Nov 2026 02:43:28 +0200 Subject: [PATCH 01/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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/60] 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 f84ccd899727ca97698c334ff42a44afca594f69 Mon Sep 17 00:00:00 2001 From: guy oron Date: Fri, 27 Nov 2026 03:49:21 +0200 Subject: [PATCH 19/60] feat(jirapoll)!: serve issues oldest first up to a per-cycle limit Implements the selection of ADR 0085 Decision item 3 and the max_dispatches_per_cycle key of item 4. - Run reads the active issues in the search's order, oldest change first by default, instead of picking five at random. It stops when the cycle holds tracker.jira.poll.max_dispatches_per_cycle dispatch records (default 100, from 1 to 250) and, on the GitHub target, before the issue whose records would take the matrix output past 768 KB. - All of an issue's records go out in the same cycle. An issue that does not fit in the room left waits for the next cycle, and the cycle does not skip ahead to a smaller one. An issue is always taken when the cycle holds no records, so an issue over the limit is dispatched alone. - processIssue returns its event counts with the issue, and Run counts them only for issues it takes, so an issue left for the next cycle does not count toward this cycle's all-dropped guard. - tracker.jira.poll.max_dispatches_per_cycle is validated wherever the Jira connection is: a whole number from 1 to 250. A value that is not a whole number is rejected at parse time, because yaml.v3 would round it down. - Options.N and selectRandom go. The "poll complete" line reports issues served instead of selected, and the all-failed error says "active" instead of "selected". - The Jira guide and the config reference describe the order, the limit and the new key. BREAKING CHANGE: the jira-poll driver no longer picks five issues at random each cycle. It serves every issue with new activity in the query's order, oldest change first by default, until the cycle holds 100 dispatch records. Set tracker.jira.poll.max_dispatches_per_cycle (1 to 250) to change that, after upgrading: an older fullsend rejects a config that sets the key. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 42 ++-- docs/reference/config-reference.md | 13 ++ internal/cli/poll.go | 7 + internal/cli/poll_jira_config_test.go | 4 + internal/config/issue_targets.go | 38 +++- internal/config/jira_tracking_test.go | 44 +++++ internal/jirapoll/auth_test.go | 1 - internal/jirapoll/limits.go | 12 +- internal/jirapoll/limits_test.go | 187 ++++++++++++++++++ internal/jirapoll/poller.go | 108 ++++++---- internal/jirapoll/poller_idle_test.go | 27 ++- internal/jirapoll/poller_invalid_id_test.go | 2 +- internal/jirapoll/poller_test.go | 23 +-- internal/jirapoll/types.go | 2 +- pkg/behaviourtest/steps/jirapoll.go | 1 - pkg/behaviourtest/steps/jirapoll_transport.go | 1 - 16 files changed, 408 insertions(+), 104 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 2aff22f6ea..4720142b4e 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1023,13 +1023,15 @@ omitted, the poller uses the default filter above. Unless `poll.enabled` is 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. +which is the recommended order. A query with its own `ORDER BY` is served +in that order. The order decides who waits when a cycle cannot serve every +issue (see [Poll coordination](#poll-coordination)): under a sustained +backlog an order other than oldest change first can leave older requests +waiting until they leave the window, where they are lost. A query that +sorts newest change first (`ORDER BY updated DESC`) logs a WARNING every +cycle that recommends oldest change first. Oldest change first has a cost +of its own: any change to a waiting issue, including a comment from anyone +allowed to comment, moves it to the back of the line. 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 @@ -1446,18 +1448,20 @@ 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 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, not a timestamp, 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 serves the rest in the search's order, oldest change first by default, until the cycle is full (see **Per-cycle limit** below). 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, not a timestamp, 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. 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. +- **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 issue it reads 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. -**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 issues it reads 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. -> **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`. +**Per-cycle limit.** The poller reads the issues with new activity one by one, in the search's order, and stops when the cycle holds `tracker.jira.poll.max_dispatches_per_cycle` dispatch records (default 100, from 1 to 250). All of an issue's records go out in the same cycle: an issue whose records do not fit in the room left waits for the next cycle, and so do the issues behind it, because the poller does not skip ahead to a smaller one. An issue is always taken when the cycle holds no records yet, so an issue with more records than the limit is dispatched alone and the cycle exceeds the limit by that one issue. On GitHub the cycle also stops before the issue whose records would take the `matrix` output past 768 KB. An issue that waits keeps its `lastCheck`, so nothing is lost by waiting unless its request leaves the 24-hour window first. The run log says how many issues wait: `the cycle holds dispatch records, at its limit of ; active issue(s) wait for the next cycle`. The limit sets how fast a backlog drains: raise it if requests wait too long, and lower it to start fewer agent runs per cycle. + +> **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, and so is the number of dispatch records in one cycle, to bound the blast radius. A rewind does not move an issue in the line, so an editor who keeps rewinding issues near the front can hold back the requests behind them. 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: @@ -1482,19 +1486,19 @@ 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 per-cycle limit (N = 5, see - below) compounds the problem — many issues may have accumulated new activity - simultaneously, and a cycle processes only N of them, picked at random. If + with no error anywhere. After a long gap many issues may have new activity + at once; the poller serves them oldest change first, up to the per-cycle + limit, so the newest requests wait for later cycles. 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. -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. +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 issue it reads 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. An issue's `lastCheck` is still read from the issue before it is processed. Each issue the poller reads costs one property write for the write-access check. 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. Narrow `tracker.jira.poll.query` (for example 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. @@ -1532,7 +1536,7 @@ The two repos checkpoint independently and can process the same Jira comment — ### Candidate search with multiple repos -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. +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 has its own per-cycle limit. 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: @@ -1565,8 +1569,8 @@ However, more pollers against the same Jira project means more API calls per cyc | 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 | -| The poll fails with `all N events this cycle were dropped before dispatch (… failed matching)` | Every event of the cycle was dropped before dispatch and at least one failed trigger matching — either the matcher errored on each event, or a mixed cycle where the remaining events failed validation; the error's counts say how many of each | No checkpoint was advanced, so the events are retried next cycle — with the same bound as failed validation: 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 …` and `WARNING: matching event …` lines above the error for the cause — when the error lists both counts, inspect both kinds of warning. A matcher that errors on every event is a harness trigger or execution-ref problem, not a Jira problem | +| 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 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 | +| The poll fails with `all N events this cycle were dropped before dispatch (… failed matching)` | Every event of the cycle was dropped before dispatch and at least one failed trigger matching — either the matcher errored on each event, or a mixed cycle where the remaining events failed validation; the error's counts say how many of each | No checkpoint was advanced, so the events are retried next cycle — with the same bound as failed validation: the red runs repeat until the events age past the first-poll backfill floor (24h by default) or another issue produces a valid event. Read the per-event `WARNING: skipping event …` and `WARNING: matching event …` lines above the error for the cause — when the error lists both counts, inspect both kinds of warning. A matcher that errors on every event is a harness trigger or execution-ref problem, not a Jira problem | | The poll fails with `all N events this cycle failed normalized-event validation` and the per-event warnings name `entity.key "P-1" is not a Jira work item key` (every cycle) | The Jira project's key is a single character, which exists only on legacy Server/Data Center deployments: the config gate accepts it (`jiraProjectKeyRe`), but a Jira work item key requires a two-or-more-character project part, so every event of the project fails validation | Such a project cannot be polled by this driver. No checkpoint advances, so the failure repeats every cycle; report it to fullsend with the log lines | | Triage or code results do not appear on the Jira issue | The built-in agents are pinned to a release that predates Jira result writes | Use built-in agents from the agents release that follows v0.52.0, or later. Re-pin a harness registered with `source:` or composed with `base:` with `fullsend agent update `. See [Where built-in agent results appear](#where-built-in-agent-results-appear) | | Code run skipped; the Jira issue has a comment starting `An open pull request already addresses — skipping automated implementation.` | An open pull request written by a person names the issue key in its title or description. Bot pull requests do not count | GitHub: comment `/fs-code --force` on the Jira issue. GitLab: close the merge request, then comment `/fs-code`. See [If the code agent skips the run](#if-the-code-agent-skips-the-run) | diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index 32ec17f00d..9cd3806862 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -82,6 +82,7 @@ tracker: # Issue tracker. At most one provider block # poll: # enabled: true # Managed poll workflow switch (see the tracker.jira section) # query: 'labels = "fullsend"' # JQL; always scoped to project + # max_dispatches_per_cycle: 100 # Dispatch records at which a poll cycle stops reading issues (1-250) # ── Authorization ──────────────────────────────────────────── authorization: # Extra sources of permission for triggering agents @@ -475,6 +476,7 @@ tracker: poll: enabled: true query: 'labels = "fullsend" AND statusCategory != Done' + max_dispatches_per_cycle: 100 ``` - **`tracker.jira.base_url`** — The Jira site URL. It must be an `https` URL @@ -542,6 +544,17 @@ tracker: 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). +- **`tracker.jira.poll.max_dispatches_per_cycle`** — The number of dispatch + records at which a poll cycle stops reading issues. A whole number from 1 + to 250; it defaults to 100. The poller serves issues in the query's order + and takes all of an issue's records or none, so an issue that does not fit + in the room left waits for the next cycle, and an issue with more records + than the limit is dispatched alone. The limit sets how fast a backlog + drains: a request that waits longer than the 24-hour backfill window is + lost. 250 is GitHub's limit of 256 jobs in a matrix less a small margin. + New in fullsend v0.58.0: an older CLI or reusable workflow rejects a + config that sets it, and stops polling, so set it after the upgrade. See + [Poll coordination](../guides/user/jira-integration.md#poll-coordination). `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.go b/internal/cli/poll.go index 06591f64ad..198adfad9d 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -344,6 +344,9 @@ type jiraPollSettings struct { project string // tracker.jira.project jql string // tracker.jira.poll.query (or the default) scoped to project enabled bool // tracker.jira.poll.enabled is true + // maxDispatches is tracker.jira.poll.max_dispatches_per_cycle, or its + // default. + maxDispatches int } // loadJiraPollSettings reads the Jira site, API gateway, project, and poll @@ -386,6 +389,8 @@ func loadJiraPollSettings(fullsendDir, jiraURL, jiraProject, jql string) (jiraPo project: jiraCfg.Project, jql: jiraCfg.PollJQL(), enabled: jiraCfg.PollEnabled(), + + maxDispatches: jiraCfg.PollMaxDispatchesPerCycle(), }, nil } @@ -575,6 +580,8 @@ func jiraPollOptions(args jiraPollArgs, matcher *celMatcher) jirapoll.Options { JQL: args.jira.jql, OutputPath: args.outputPath, + MaxDispatchesPerCycle: args.jira.maxDispatches, + Authorization: jiraPollAuthorization(matcher.jiraAuth), } } diff --git a/internal/cli/poll_jira_config_test.go b/internal/cli/poll_jira_config_test.go index fae54dd9d4..3845bab933 100644 --- a/internal/cli/poll_jira_config_test.go +++ b/internal/cli/poll_jira_config_test.go @@ -43,6 +43,7 @@ func TestLoadJiraPollSettings_ReadsConfig(t *testing.T) { poll: enabled: true query: 'labels = "fullsend" ORDER BY updated DESC' + max_dispatches_per_cycle: 40 `) got, err := loadJiraPollSettings(dir, "", "", "") require.NoError(t, err) @@ -52,6 +53,8 @@ func TestLoadJiraPollSettings_ReadsConfig(t *testing.T) { project: "PROJ", jql: `project = "PROJ" AND (labels = "fullsend") ORDER BY updated DESC`, enabled: true, + + maxDispatches: 40, }, got) } @@ -62,6 +65,7 @@ func TestLoadJiraPollSettings_Defaults(t *testing.T) { assert.Equal(t, config.DefaultJiraAPIURL, got.apiURL) assert.Equal(t, `project = "PROJ" AND (statusCategory != Done)`, got.jql) assert.False(t, got.enabled, "an omitted poll mapping leaves polling disabled") + assert.Equal(t, 100, got.maxDispatches) } func TestLoadJiraPollSettings_QueryWithoutOrderBy(t *testing.T) { diff --git a/internal/config/issue_targets.go b/internal/config/issue_targets.go index 9ae1c01c6a..757f7576ed 100644 --- a/internal/config/issue_targets.go +++ b/internal/config/issue_targets.go @@ -104,6 +104,15 @@ const DefaultJiraAPIURL = "https://api.atlassian.com" // poller serves the oldest change first (ADR 0085, Decision item 2). const DefaultJiraPollQuery = "statusCategory != Done" +// Bounds and default of tracker.jira.poll.max_dispatches_per_cycle (ADR 0085, +// Decision items 3 and 4). The maximum is GitHub's 256-job matrix limit less +// a small margin. +const ( + DefaultJiraPollMaxDispatchesPerCycle = 100 + MinJiraPollMaxDispatchesPerCycle = 1 + MaxJiraPollMaxDispatchesPerCycle = 250 +) + // JiraTrackingConfig holds Jira issue-tracking settings: the Jira site and // project this repository is connected to, the cross-project issue // destinations, and the poller settings. Credentials (the Jira token and @@ -133,6 +142,10 @@ type JiraPollConfig struct { // Query is the JQL the poller runs, before project scoping; empty // means DefaultJiraPollQuery. Query string `yaml:"query,omitempty"` + // MaxDispatchesPerCycle is the number of dispatch records at which a + // poll cycle stops reading issues; nil means + // DefaultJiraPollMaxDispatchesPerCycle. + MaxDispatchesPerCycle *int `yaml:"max_dispatches_per_cycle,omitempty"` } // jiraTrackingKeys, jiraPollKeys, and jiraAllowedTargetsKeys are the keys @@ -140,7 +153,7 @@ type JiraPollConfig struct { // tracker.jira.allowed_targets. var ( jiraTrackingKeys = map[string]bool{"base_url": true, "api_url": true, "run_label": true, "project": true, "allowed_targets": true, "poll": true} - jiraPollKeys = map[string]bool{"enabled": true, "query": true} + jiraPollKeys = map[string]bool{"enabled": true, "query": true, "max_dispatches_per_cycle": true} jiraAllowedTargetsKeys = map[string]bool{"projects": true} ) @@ -184,6 +197,13 @@ func (j *JiraTrackingConfig) UnmarshalYAML(n *yaml.Node) error { } } } + // yaml.v3 decodes 2.5 into an int field as 2, so a value that is not + // a whole number is rejected here instead of being rounded down. + if poll := mappingNode(r, "poll"); poll != nil && poll.Kind == yaml.MappingNode { + if limit := mappingNode(poll, "max_dispatches_per_cycle"); limit != nil && limit.ShortTag() != "!!int" && limit.ShortTag() != "!!null" { + return managedFieldError(limit, "tracker.jira.poll.max_dispatches_per_cycle must be a whole number") + } + } } return n.Decode((*jiraTrackingPlain)(j)) } @@ -210,6 +230,15 @@ func (j *JiraTrackingConfig) PollQuery() string { return j.Poll.Query } +// PollMaxDispatchesPerCycle returns poll.max_dispatches_per_cycle, or +// DefaultJiraPollMaxDispatchesPerCycle when it is unset. +func (j *JiraTrackingConfig) PollMaxDispatchesPerCycle() int { + if j == nil || j.Poll == nil || j.Poll.MaxDispatchesPerCycle == nil { + return DefaultJiraPollMaxDispatchesPerCycle + } + return *j.Poll.MaxDispatchesPerCycle +} + // PollJQL returns the poller's JQL: the configured (or default) query // scoped to the repository's project (see ScopeJQLToProject). func (j *JiraTrackingConfig) PollJQL() string { @@ -403,6 +432,10 @@ func cloneTracking(src *TrackingConfig) *TrackingConfig { enabled := *p.Enabled poll.Enabled = &enabled } + if p.MaxDispatchesPerCycle != nil { + limit := *p.MaxDispatchesPerCycle + poll.MaxDispatchesPerCycle = &limit + } out.Jira.Poll = poll } } @@ -514,6 +547,9 @@ func (j *JiraTrackingConfig) ValidateConnection() error { if j.Poll != nil && !jqlParensBalanced(j.Poll.Query) { return fmt.Errorf("tracker.jira: poll.query has unbalanced parentheses: the query is wrapped in parentheses to scope it to the project") } + if limit := j.PollMaxDispatchesPerCycle(); limit < MinJiraPollMaxDispatchesPerCycle || limit > MaxJiraPollMaxDispatchesPerCycle { + return fmt.Errorf("tracker.jira: poll.max_dispatches_per_cycle must be a whole number from %d to %d (got %d)", MinJiraPollMaxDispatchesPerCycle, MaxJiraPollMaxDispatchesPerCycle, limit) + } return nil } diff --git a/internal/config/jira_tracking_test.go b/internal/config/jira_tracking_test.go index c5534aed3a..35a3540c4f 100644 --- a/internal/config/jira_tracking_test.go +++ b/internal/config/jira_tracking_test.go @@ -1,6 +1,7 @@ package config import ( + "fmt" "testing" "github.com/stretchr/testify/assert" @@ -53,8 +54,10 @@ func TestJiraTracking_Defaults(t *testing.T) { 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)`, jira.PollJQL()) + assert.Equal(t, 100, jira.PollMaxDispatchesPerCycle()) var nilJira *JiraTrackingConfig + assert.Equal(t, DefaultJiraPollMaxDispatchesPerCycle, nilJira.PollMaxDispatchesPerCycle()) assert.Equal(t, DefaultJiraAPIURL, nilJira.EffectiveAPIURL()) assert.False(t, nilJira.PollEnabled()) assert.Equal(t, DefaultJiraPollQuery, nilJira.PollQuery()) @@ -154,6 +157,7 @@ func TestJiraTracking_ManagedConfigSurvivesMergeAndClone(t *testing.T) { poll: enabled: true query: labels = "fullsend" + max_dispatches_per_cycle: 40 `), &m)) require.True(t, m.IsSet()) want := m.Writer().IssueTracking() @@ -167,12 +171,15 @@ func TestJiraTracking_ManagedConfigSurvivesMergeAndClone(t *testing.T) { got := merged.IssueTracking() assert.Equal(t, want, got) assert.Equal(t, `project = "PROJ" AND (labels = "fullsend")`, got.Jira.PollJQL()) + assert.Equal(t, 40, got.Jira.PollMaxDispatchesPerCycle()) // The clone is deep: mutating it leaves the source untouched. copied := cloneTracking(want) *copied.Jira.Poll.Enabled = false + *copied.Jira.Poll.MaxDispatchesPerCycle = 7 copied.Jira.AllowedTargets.Projects[0] = "CHANGED" assert.True(t, want.Jira.PollEnabled()) + assert.Equal(t, 40, want.Jira.PollMaxDispatchesPerCycle()) assert.Equal(t, "OTHER", want.Jira.AllowedTargets.Projects[0]) // Re-marshal through the managed form keeps the settings. @@ -213,6 +220,43 @@ func TestScopeJQLToProject_QuotesReservedWordKey(t *testing.T) { } } +// poll.max_dispatches_per_cycle is a whole number from 1 to 250 (ADR 0085, +// Decision items 3 and 4); omitted, it is 100. +func TestJiraTracking_ValidatePollMaxDispatchesPerCycle(t *testing.T) { + for _, c := range []struct { + value int + wantErr bool + }{ + {value: 1}, + {value: 100}, + {value: 250}, + {value: 0, wantErr: true}, + {value: -5, wantErr: true}, + {value: 251, wantErr: true}, + } { + t.Run(fmt.Sprintf("%d", c.value), func(t *testing.T) { + yamlText := fmt.Sprintf("version: \"1\"\ntracker:\n jira:\n base_url: https://example.atlassian.net\n project: PROJ\n poll:\n max_dispatches_per_cycle: %d\n", c.value) + cfg, err := ParsePerRepoConfigWriter([]byte(yamlText)) + require.NoError(t, err) + err = cfg.Validate() + if c.wantErr { + require.Error(t, err) + assert.Contains(t, err.Error(), fmt.Sprintf("poll.max_dispatches_per_cycle must be a whole number from 1 to 250 (got %d)", c.value)) + return + } + require.NoError(t, err) + assert.Equal(t, c.value, cfg.IssueTracking().Jira.PollMaxDispatchesPerCycle()) + }) + } + + // A value that is not a whole number is rejected, not rounded down. + for _, value := range []string{"2.5", "3.0", "1e2", "many", `"7"`} { + _, err := ParsePerRepoConfigWriter([]byte("version: \"1\"\ntracker:\n jira:\n base_url: https://example.atlassian.net\n project: PROJ\n poll:\n max_dispatches_per_cycle: " + value + "\n")) + require.Error(t, err, value) + assert.Contains(t, err.Error(), "max_dispatches_per_cycle must be a whole number", value) + } +} + func TestJiraTracking_ValidatePollQueryParens(t *testing.T) { cases := []struct { name string diff --git a/internal/jirapoll/auth_test.go b/internal/jirapoll/auth_test.go index 16a2c44015..d82f578b76 100644 --- a/internal/jirapoll/auth_test.go +++ b/internal/jirapoll/auth_test.go @@ -114,7 +114,6 @@ func authTestPoller(mc *mockClient, m EventMatcher, auth Authorization) *Poller TargetRepo: "acme/platform", JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ", - N: 50, Authorization: auth, }) } diff --git a/internal/jirapoll/limits.go b/internal/jirapoll/limits.go index 6c749a40e7..69683e2cd1 100644 --- a/internal/jirapoll/limits.go +++ b/internal/jirapoll/limits.go @@ -49,12 +49,18 @@ func recordOutputSize(record DispatchRecord) int { // 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 { + return addedOutputSize(matrixEnvelopeSize, 0, records) +} + +// addedOutputSize returns the size of a matrix output that measures size and +// holds held records, after records are added to it. +func addedOutputSize(size, held int, records []DispatchRecord) int { + for _, record := range records { + if held > 0 { size += 2 // the comma between two records } size += recordOutputSize(record) + held++ } return size } diff --git a/internal/jirapoll/limits_test.go b/internal/jirapoll/limits_test.go index 84df91f643..8c33a25956 100644 --- a/internal/jirapoll/limits_test.go +++ b/internal/jirapoll/limits_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "path/filepath" "strings" "testing" "time" @@ -214,3 +215,189 @@ func TestProcessIssueWithinLimitsKeepsOrder(t *testing.T) { t.Errorf("logged a limit that was not reached:\n%s", logs) } } + +// cycleMatcher produces what each comment asks for with a body of the form +// "/fs-triage records=N pad=M": N records, each padded with M characters. +// A body of "/fs-triage fail" fails the match. +type cycleMatcher struct{} + +func (cycleMatcher) Match(_ context.Context, event *normevent.Event) ([]DispatchRecord, error) { + if event.Transition.Comment == nil { + return nil, nil + } + body := event.Transition.Comment.Body + if body == "/fs-triage fail" { + return nil, fmt.Errorf("no route") + } + var n, pad int + if _, err := fmt.Sscanf(body, "/fs-triage records=%d pad=%d", &n, &pad); err != nil { + return nil, err + } + payload, err := json.Marshal(map[string]string{"pad": strings.Repeat("x", pad)}) + if err != nil { + return nil, err + } + records := make([]DispatchRecord, n) + for i := range records { + records[i] = DispatchRecord{Agent: fmt.Sprintf("agent-%d", i), StatusNumber: fmt.Sprintf("%d", event.Entity.ID), EventPayload: payload} + } + return records, nil +} + +// cycleTestClient returns a client whose search lists one issue per entry of +// bodies, PROJ-1 first, each with those comments. +func cycleTestClient(bodies ...[]string) *mockClient { + now := time.Now().Truncate(time.Second) + mc := newMockClient() + mc.roleMembership = map[string]string{"dev-account": "Developers"} + for i, issueBodies := range bodies { + key := fmt.Sprintf("PROJ-%d", i+1) + mc.searchResult = append(mc.searchResult, idleTestIssue(i+1, now.Add(-48*time.Hour), now.Add(-time.Minute))) + for j, body := range issueBodies { + mc.comments[key] = append(mc.comments[key], jira.Comment{ + ID: fmt.Sprintf("%d%02d", i+1, j), + Body: body, + Created: now.Add(-time.Minute).Format(jiraTimeLayout), + Author: jira.User{AccountID: "dev-account", AccountType: "atlassian"}, + }) + } + } + return mc +} + +// runCycleWithLimit runs one cycle on mc with the given record limit and +// returns the issue ID of each dispatched record and the cycle's log. +func runCycleWithLimit(t *testing.T, mc *mockClient, targetForge string, limit int) ([]string, string) { + t.Helper() + logs := captureLog(t) + p := newTestPoller(mc, cycleMatcher{}, Options{ + TargetRepo: "acme/platform", + TargetForge: targetForge, + GitLabURL: "https://gitlab.example.com", + JiraBaseURL: "https://acme.atlassian.net", + JiraProject: "PROJ", + OutputPath: filepath.Join(t.TempDir(), "dispatches.json"), + MaxDispatchesPerCycle: limit, + }) + if err := p.Run(context.Background()); err != nil { + t.Fatalf("Run() error: %v", err) + } + return dispatchedKeys(p), logs.String() +} + +const oneRecord = "/fs-triage records=1 pad=0" + +// The active issues are served in the search's order, with no random pick +// and no limit of five issues (ADR 0085, Decision item 3). +func TestRunServesActiveIssuesInSearchOrder(t *testing.T) { + bodies := make([][]string, 8) + for i := range bodies { + bodies[i] = []string{oneRecord} + } + served, logs := runCycleWithLimit(t, cycleTestClient(bodies...), TargetForgeGitHub, 0) + + if got, want := strings.Join(served, ","), "10001,10002,10003,10004,10005,10006,10007,10008"; got != want { + t.Errorf("served %s, want all eight in search order: %s", got, want) + } + if want := "poll complete: 8 candidates, 8 active, 8 served, 8 dispatches"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } +} + +// A cycle stops reading issues once it holds max_dispatches_per_cycle +// records; the issues behind wait, unread, for the next cycle. +func TestRunStopsAtTheRecordLimit(t *testing.T) { + mc := cycleTestClient([]string{oneRecord}, []string{oneRecord}, []string{oneRecord}, []string{oneRecord}, []string{oneRecord}) + + served, logs := runCycleWithLimit(t, mc, TargetForgeGitHub, 3) + if got := strings.Join(served, ","); got != "10001,10002,10003" { + t.Errorf("cycle 1 served %s, want the first three", got) + } + if want := "the cycle holds 3 dispatch records, at its limit of 3; 2 active issue(s) wait for the next cycle"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + if mc.listCommentsCalls["PROJ-4"]+mc.listCommentsCalls["PROJ-5"]+mc.propertySetCalls["PROJ-4"]+mc.propertySetCalls["PROJ-5"] != 0 { + t.Error("cycle 1 read or wrote an issue behind the limit") + } + + served, _ = runCycleWithLimit(t, mc, TargetForgeGitHub, 3) + if got := strings.Join(served, ","); got != "10004,10005" { + t.Errorf("cycle 2 served %s, want the two that waited", got) + } +} + +// All of an issue's records go out in the same cycle. An issue that does +// not fit in the room left waits, and the cycle does not skip ahead to a +// smaller issue behind it. Its events are not counted in the cycle it sat +// out. +func TestRunIssueThatDoesNotFitWaits(t *testing.T) { + mc := cycleTestClient( + []string{"/fs-triage records=2 pad=0"}, + []string{"/fs-triage records=2 pad=0", "/fs-triage fail"}, + []string{oneRecord}, + ) + + served, logs := runCycleWithLimit(t, mc, TargetForgeGitHub, 3) + if got := strings.Join(served, ","); got != "10001,10001" { + t.Errorf("cycle 1 served %s, want only PROJ-1's two records", got) + } + if want := "the cycle holds 2 dispatch records and the 2 of PROJ-2 do not fit in the room left (limit: 3 records and 768 KB of GitHub job output); it and the 1 active issue(s) behind it wait for the next cycle"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + if !storedLastCheckAt(t, mc, "PROJ-2").IsZero() { + t.Error("cycle 1 advanced the lastCheck of the issue that did not fit") + } + if mc.listCommentsCalls["PROJ-3"] != 0 { + t.Error("cycle 1 skipped ahead to PROJ-3") + } + if strings.Contains(logs, "because matching them failed") { + t.Errorf("cycle 1 counted the events of an issue it did not take:\n%s", logs) + } + + served, logs = runCycleWithLimit(t, mc, TargetForgeGitHub, 3) + if got := strings.Join(served, ","); got != "10002,10002,10003" { + t.Errorf("cycle 2 served %s, want PROJ-2's two records and then PROJ-3", got) + } + if want := "dropped 1 of 3 events this cycle because matching them failed"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } +} + +// An issue with more records than the limit is taken when the cycle holds +// none, so it is dispatched alone and does not hold back the issues behind +// it. +func TestRunIssueOverTheLimitGoesAlone(t *testing.T) { + mc := cycleTestClient( + []string{oneRecord}, + []string{"/fs-triage records=3 pad=0"}, + []string{oneRecord}, + ) + + for cycle, want := range []string{"10001", "10002,10002,10002", "10003"} { + served, _ := runCycleWithLimit(t, mc, TargetForgeGitHub, 2) + if got := strings.Join(served, ","); got != want { + t.Errorf("cycle %d served %s, want %s", cycle+1, got, want) + } + } +} + +// On the GitHub target a cycle also stops before the issue whose records +// would take the matrix output past 768 KB. GitLab has no batch output, so +// the size limit does not apply there. +func TestRunStopsBeforeTheSizeLimit(t *testing.T) { + // Five issues with one record of about 200 KB each. + big := []string{"/fs-triage records=1 pad=100000"} + + served, logs := runCycleWithLimit(t, cycleTestClient(big, big, big, big, big), TargetForgeGitHub, 0) + if got := strings.Join(served, ","); got != "10001,10002,10003" { + t.Errorf("GitHub served %s, want the three issues that fit in 768 KB", got) + } + if want := "the 1 of PROJ-4 do not fit in the room left"; !strings.Contains(logs, want) { + t.Errorf("log lacks %q:\n%s", want, logs) + } + + served, _ = runCycleWithLimit(t, cycleTestClient(big, big, big, big, big), TargetForgeGitLab, 0) + if got := strings.Join(served, ","); got != "10001,10002,10003,10004,10005" { + t.Errorf("GitLab served %s, want all five", got) + } +} diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 20fff0881a..e087530686 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -20,7 +20,6 @@ import ( "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" ) // EventMatcher evaluates a normalized event against harness CEL triggers @@ -76,8 +75,8 @@ type Poller struct { // New creates a Jira Poller with the given options. func New(client JiraClient, matcher EventMatcher, opts Options) *Poller { - if opts.N == 0 { - opts.N = 5 + if opts.MaxDispatchesPerCycle == 0 { + opts.MaxDispatchesPerCycle = 100 } if opts.FirstPollBackfillWindow == 0 { opts.FirstPollBackfillWindow = 24 * time.Hour @@ -149,13 +148,10 @@ 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. + // (ADR 0160), so an already-handled issue costs the cycle nothing more + // than its search row. active := p.filterActive(candidates) - // Step 3: Randomly select min(N, len(active)) candidates. - selected := selectRandom(active, p.opts.N) - // The project role roster (GET /project/{key}/role, which Jira Cloud // serves only with the Administer Projects permission) is not loaded // here. processIssue loads it on first use, only when an event needs @@ -165,25 +161,40 @@ func (p *Poller) Run(ctx context.Context) error { // cycle (see ensureRoleStructure), leaving checkpoints untouched so // the next cron run retries. - // Step 4: Process each selected issue. Checkpoint advances are not + // Step 3: Process the active issues in the search's order, oldest + // change first by default, until the cycle holds MaxDispatchesPerCycle + // records, the next issue's records do not fit, or a time limit ends + // the reading (ADR 0085, Decision item 3). 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) 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 + // loop adds the two to the cycle as one unit, and Step 5 below commits + // the checkpoint only after Step 4'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. + // anywhere. An issue that times out, that the cycle limit cuts off, or + // that does not fit contributes neither records nor a checkpoint, so + // its requests stay eligible next cycle. + sized := p.opts.TargetForge != TargetForgeGitLab + limits := fmt.Sprintf("%d records", p.opts.MaxDispatchesPerCycle) + if sized { + limits += fmt.Sprintf(" and %d KB of GitHub job output", maxMatrixOutputBytes/1024) + } var pending []pendingCheckpoint - var failed, tried int - for _, issue := range selected { + var failed int + batchSize := matrixEnvelopeSize + for i, issue := range active { if readCtx.Err() != nil { + if ctx.Err() == nil { + log.Printf("WARNING: the %s cycle time limit was reached with %d active issue(s) not read; they wait for the next cycle", p.opts.CycleTimeLimit, len(active)-i) + } + break + } + if len(p.dispatches) >= p.opts.MaxDispatchesPerCycle { + log.Printf("the cycle holds %d dispatch records, at its limit of %d; %d active issue(s) wait for the next cycle", len(p.dispatches), p.opts.MaxDispatchesPerCycle, len(active)-i) break } - tried++ issueCtx, cancelIssue := context.WithTimeout(readCtx, p.opts.IssueTimeLimit) pc, err := p.processIssue(issueCtx, issue) issueTimedOut := errors.Is(issueCtx.Err(), context.DeadlineExceeded) @@ -207,7 +218,27 @@ func (p *Poller) Run(ctx context.Context) error { } continue } + + // All of an issue's records go out in the same cycle. An issue + // that does not fit in the room left waits for the next cycle, + // and so do the issues behind it: the cycle does not skip ahead + // to a smaller one. An issue is always taken when the cycle holds + // no records yet, so a cycle can exceed the record limit by that + // one issue; capIssueRecords keeps it within GitHub's limits. + held := len(p.dispatches) + newSize := batchSize + if sized { + newSize = addedOutputSize(batchSize, held, pc.records) + } + if held > 0 && (held+len(pc.records) > p.opts.MaxDispatchesPerCycle || newSize > maxMatrixOutputBytes) { + log.Printf("the cycle holds %d dispatch records and the %d of %s do not fit in the room left (limit: %s); it and the %d active issue(s) behind it wait for the next cycle", held, len(pc.records), issue.Key, limits, len(active)-i-1) + break + } + batchSize = newSize p.dispatches = append(p.dispatches, pc.records...) + p.eventsSeen += pc.eventsSeen + p.eventsInvalid += pc.eventsInvalid + p.eventsMatchErrors += pc.eventsMatchErrors pending = append(pending, pc) } // The caller's context ended, not a time limit of this cycle: stop @@ -215,22 +246,19 @@ func (p *Poller) Run(ctx context.Context) error { 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) - } // 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) + if failed == len(active) { + return fmt.Errorf("all %d active issues failed to process", failed) } - 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) + return fmt.Errorf("all %d issues read before the %s cycle time limit failed or timed out; the other %d active issues wait for the next cycle", failed, p.opts.CycleTimeLimit, len(active)-failed) } - // Step 5: Write dispatch records. + // Step 4: Write dispatch records. if p.opts.OutputPath != "" { if err := p.writeDispatches(p.opts.OutputPath); err != nil { return fmt.Errorf("write dispatches: %w", err) @@ -244,7 +272,7 @@ func (p *Poller) Run(ctx context.Context) error { // real output driver replaces the shell-based dispatch step (tracked // follow-up), a failure in that downstream step will silently drop the // event instead of being retried. Local persistence of dispatches.json - // itself is durable before Step 6 below commits any checkpoint. + // itself is durable before Step 5 below commits any checkpoint. // // With an output driver (Options.Dispatcher, used for GitLab targets) // the records are scheduled here instead, and an issue's checkpoint is @@ -317,7 +345,7 @@ func (p *Poller) Run(ctx context.Context) error { return fmt.Errorf("all %d events this cycle were dropped before dispatch (%d failed normalized-event validation, %d failed matching); no checkpoint was advanced, so they are retried next cycle", dropped, p.eventsInvalid, p.eventsMatchErrors) } - // Step 6: Commit checkpoints now that the dispatch file is durably + // Step 5: Commit checkpoints now that the dispatch file is durably // written (or there was nothing to write). All advances are attempted; // any failure then fails the cycle so the operator sees it — the // dispatches are already persisted, so an uncommitted checkpoint means @@ -335,8 +363,8 @@ func (p *Poller) Run(ctx context.Context) error { } } - log.Printf("poll complete: %d candidates, %d active, %d selected, %d dispatches", - len(candidates), len(active), len(selected), len(p.dispatches)) + log.Printf("poll complete: %d candidates, %d active, %d served, %d dispatches", + len(candidates), len(active), len(pending), 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) } @@ -356,6 +384,13 @@ type pendingCheckpoint struct { t time.Time records []DispatchRecord dispatchFailed bool // set when Options.Dispatcher failed one of records + + // Event counts of this look. Run adds them to the cycle's counts only + // when it takes the issue, so an issue left for the next cycle does not + // count toward this cycle's all-dropped guard. + eventsSeen int // events converted + eventsInvalid int // events skipped because they failed validation + eventsMatchErrors int // events dropped because matcher.Match errored } // maxRolePriority is the highest value jira.RolePriority can return @@ -588,17 +623,6 @@ func (r clampReport) log() { log.Print(prefix + strings.Join(parts, "; ")) } -// selectRandom randomly selects min(n, len(items)) items. -func selectRandom(items []jira.Issue, n int) []jira.Issue { - if len(items) <= n { - return items - } - randutil.Shuffle(len(items), func(i, j int) { - items[i], items[j] = items[j], items[i] - }) - return items[:n] -} - // 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 @@ -704,14 +728,14 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (pendingChe var records []issueRecord for _, event := range events { ne := p.toNormalizedEvent(event) - p.eventsSeen++ + pc.eventsSeen++ // fullsend run cannot use an invalid embedded event, so an event // that fails validation is skipped here rather than dispatched. // An issue served without a labels array never reaches this skip: // toNormalizedEvent maps nil labels to an empty list. if err := ne.Validate(); err != nil { log.Printf("WARNING: skipping event %s for issue %s: %v (Jira issue id %q)", event.Key(), event.IssueKey, err, event.IssueID) - p.eventsInvalid++ + pc.eventsInvalid++ continue } @@ -737,7 +761,7 @@ func (p *Poller) processIssue(ctx context.Context, issue jira.Issue) (pendingChe // guard above instead of advancing behind a // green Run. log.Printf("WARNING: matching event %s: %v", event.Key(), matchErr) - p.eventsMatchErrors++ + pc.eventsMatchErrors++ continue } for _, record := range matched { diff --git a/internal/jirapoll/poller_idle_test.go b/internal/jirapoll/poller_idle_test.go index 9a1450232e..b3cb9dee8b 100644 --- a/internal/jirapoll/poller_idle_test.go +++ b/internal/jirapoll/poller_idle_test.go @@ -15,7 +15,7 @@ import ( ) // Tests for ADR 0160: the poller skips candidates with nothing new since -// their lastCheck before the random pick, and a look advances lastCheck to +// their lastCheck before processing, and a look advances lastCheck to // at least the issue's updated value. // idleTestIssue is a search row for key with the given created and updated @@ -82,7 +82,7 @@ func dispatchedKeys(p *Poller) []string { return keys } -// An idle candidate is dropped before the pick and costs no property write, +// An idle candidate is dropped before processing 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) @@ -119,7 +119,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, 3 active, 3 selected, 3 dispatches"; !strings.Contains(logs.String(), want) { + if want := "poll complete: 10 candidates, 3 active, 3 served, 3 dispatches"; !strings.Contains(logs.String(), want) { t.Errorf("log lacks %q:\n%s", want, logs.String()) } } @@ -205,7 +205,7 @@ func TestRunLogsOneClampLinePerCycle(t *testing.T) { } } if c := strings.Count(logs.String(), "lastCheck for PROJ-3 is in the future"); c != 1 { - t.Errorf("per-issue future WARNING for the picked PROJ-3 logged %d times, want 1", c) + t.Errorf("per-issue future WARNING for the processed PROJ-3 logged %d times, want 1", c) } }) @@ -358,9 +358,9 @@ func TestRunGarbageLastCheckTreatedAsUnset(t *testing.T) { } } -// A cycle whose every selected issue fails ends in an error. Here the one +// A cycle whose every active issue fails ends in an error. Here the one // active issue's lastCheck cannot be read. -func TestRunAllSelectedIssuesFailedFailsCycle(t *testing.T) { +func TestRunAllActiveIssuesFailedFailsCycle(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))} @@ -368,7 +368,7 @@ func TestRunAllSelectedIssuesFailedFailsCycle(t *testing.T) { p := idleTestPoller(mc, t) err := p.Run(context.Background()) - if err == nil || !strings.Contains(err.Error(), "all 1 selected issues failed to process") { + if err == nil || !strings.Contains(err.Error(), "all 1 active issues failed to process") { t.Fatalf("Run() error = %v, want the all-failed guard", err) } if len(p.dispatches) != 0 { @@ -659,8 +659,7 @@ func (c slowClient) SetEntityProperty(ctx context.Context, issueKey, propKey str } // 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. +// with a fresh triage comment. The poller reads them in that 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 { @@ -764,7 +763,7 @@ func TestRunTimeLimitOutcomes(t *testing.T) { if err := p.Run(context.Background()); err != nil { t.Fatalf("Run() error: %v", err) } - for _, want := range []string{"cycle time limit cut off reading PROJ-1", "1 selected issue(s) not read"} { + for _, want := range []string{"cycle time limit cut off reading PROJ-1", "1 active issue(s) not read"} { if !strings.Contains(logs.String(), want) { t.Errorf("log lacks %q:\n%s", want, logs) } @@ -781,7 +780,7 @@ func TestRunTimeLimitOutcomes(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") { + if err == nil || !strings.Contains(err.Error(), "all 1 issues read before the 450ms cycle time limit failed or timed out; the other 1 active issues wait") { t.Fatalf("Run() error = %v, want the failure of a cycle blocked by a slow issue", err) } }) @@ -790,7 +789,7 @@ func TestRunTimeLimitOutcomes(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") { + if err == nil || !strings.Contains(err.Error(), "all 2 active issues failed to process") { t.Fatalf("Run() error = %v, want the all-failed guard", err) } }) @@ -800,7 +799,7 @@ func TestRunTimeLimitOutcomes(t *testing.T) { 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" + want = "2 active issue(s) not read" } t.Run(name, func(t *testing.T) { logs := captureLog(t) @@ -831,7 +830,7 @@ func TestRunTimeLimitOutcomes(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 +// no property read (ADR 0085, Decision item 2); a processed issue's lastCheck // is still read from the issue before processing. func TestRunTakesLastCheckFromSearch(t *testing.T) { now := time.Now().Truncate(time.Second) diff --git a/internal/jirapoll/poller_invalid_id_test.go b/internal/jirapoll/poller_invalid_id_test.go index bf36b96755..0dc1a1dbad 100644 --- a/internal/jirapoll/poller_invalid_id_test.go +++ b/internal/jirapoll/poller_invalid_id_test.go @@ -460,7 +460,7 @@ func TestRun_MalformedKeyEventSkipped(t *testing.T) { // the next cycle re-detects the same event and fails again. The repeat is the // guard's intent (nothing is lost behind a green run) and is bounded: it ends // when the event ages past the first-poll backfill floor (24h by default) or -// another selected issue produces a valid event. Reviewed on PR #9191 +// another issue produces a valid event. Reviewed on PR #9191 // (thread 4526836669): this pins the one-issue-alone outcome as intended. func TestRun_LoneBadEventFailsEveryCycle(t *testing.T) { now := time.Now().Truncate(time.Second) diff --git a/internal/jirapoll/poller_test.go b/internal/jirapoll/poller_test.go index 23fc161d65..7095cf63d7 100644 --- a/internal/jirapoll/poller_test.go +++ b/internal/jirapoll/poller_test.go @@ -315,8 +315,8 @@ func TestNew(t *testing.T) { JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ", }) - if p.opts.N != 5 { - t.Errorf("N = %d, want default 5", p.opts.N) + if p.opts.MaxDispatchesPerCycle != 100 { + t.Errorf("MaxDispatchesPerCycle = %d, want default 100", p.opts.MaxDispatchesPerCycle) } 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) @@ -1583,7 +1583,7 @@ func TestRunWriteAccessCheck(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") { + if err == nil || !strings.Contains(err.Error(), "all 2 active issues failed to process") { t.Fatalf("Run() error = %v, want the all-failed guard", err) } if len(p.dispatches) != 0 { @@ -1847,23 +1847,6 @@ func TestRunMultipleEvents(t *testing.T) { } } -func TestSelectRandom(t *testing.T) { - issues := make([]jira.Issue, 10) - for i := range issues { - issues[i] = jira.Issue{Key: "PROJ-" + string(rune('0'+i))} - } - - selected := selectRandom(issues, 3) - if len(selected) != 3 { - t.Errorf("selected %d, want 3", len(selected)) - } - - all := selectRandom(make([]jira.Issue, 2), 5) - if len(all) != 2 { - t.Errorf("selected %d, want 2", len(all)) - } -} - func TestDeduplicate(t *testing.T) { now := time.Now() events := []JiraEvent{ diff --git a/internal/jirapoll/types.go b/internal/jirapoll/types.go index a2117ebb2b..adaa04697f 100644 --- a/internal/jirapoll/types.go +++ b/internal/jirapoll/types.go @@ -66,7 +66,7 @@ type Options struct { JiraProject string // Jira project key for default JQL JQL string // Custom JQL override OutputPath string // Path to write dispatch records JSON - N int // Max issues to process per cycle (default: 5) + MaxDispatchesPerCycle int // Dispatch records at which a cycle stops reading issues (default: 100, ADR 0085) 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) diff --git a/pkg/behaviourtest/steps/jirapoll.go b/pkg/behaviourtest/steps/jirapoll.go index adf095813b..5a5fc115e3 100644 --- a/pkg/behaviourtest/steps/jirapoll.go +++ b/pkg/behaviourtest/steps/jirapoll.go @@ -236,7 +236,6 @@ func whenJiraPollerRuns(ctx context.Context, w *world.World) error { JiraBaseURL: w.JiraMockServer.URL, JiraProject: "PROJ", OutputPath: outputPath, - N: 50, // process all candidates } poller := jirapoll.New(jiraClient, matcher, opts) diff --git a/pkg/behaviourtest/steps/jirapoll_transport.go b/pkg/behaviourtest/steps/jirapoll_transport.go index 212694e4fa..6b34eef71d 100644 --- a/pkg/behaviourtest/steps/jirapoll_transport.go +++ b/pkg/behaviourtest/steps/jirapoll_transport.go @@ -330,7 +330,6 @@ func whenJiraGitLabPollerRuns(ctx context.Context, w *world.World) error { // jira_lifecycle_test.go uses). JiraBaseURL: "https://acme.atlassian.net", JiraProject: "PROJ", - N: 50, // process all candidates TargetForge: jirapoll.TargetForgeGitLab, GitLabURL: "https://gitlab.example.com", Dispatcher: jiradispatch.GitLabDispatcher{Poller: glPoller}, From ce247e9905f3f5372456ae259f6d68765cbba896 Mon Sep 17 00:00:00 2001 From: guy oron Date: Fri, 27 Nov 2026 04:10:48 +0200 Subject: [PATCH 20/60] docs(jira-poll): drop two leftovers of the pick and the filter's property read The time limits no longer need to name the activity filter, which makes no Jira call since it reads lastCheck from the search rows, and the resume-after-a-gap text still said an issue is selected. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 4720142b4e..30da0d652c 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1455,7 +1455,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 issues it reads 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 and the issues it reads 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. @@ -1475,7 +1475,7 @@ Three edge cases of checkpoint tracking are worth knowing: 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, and only for an issue that changed again within the - window: when it is selected it logs + window: when it is processed 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 From f32dd09ba59863532df8fceeca1368b33dc099af Mon Sep 17 00:00:00 2001 From: guy oron Date: Fri, 27 Nov 2026 04:31:44 +0200 Subject: [PATCH 21/60] 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 22/60] 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 6d551155ea9a63da0bcd1857c189bc7bf46c3346 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 03:08:26 +0200 Subject: [PATCH 23/60] ci(jira-poll): add a full-size batch check for the GitHub hand-off On GitHub the managed poll workflow passes a cycle's batch to the dispatch job as one job output and runs each record as a matrix job. A batch over GitHub's 1 MB output limit or 256-job matrix limit is lost whole, which is why the driver stops a cycle at 250 records and 768 KB (ADR 0085). Nothing showed on GitHub that a batch at those limits arrives. The Jira poll batch check workflow does. It builds the batch with the real driver reading a fake Jira (hack/prove-jira-poll-batch), returns it through a reusable workflow's job output with the production "Build dispatch matrix" step, hands it to a second reusable workflow under the managed caller's condition, and runs one job per record. Each job compares the record it received with the batch, and a last job checks that every record got a job. It is started by hand and needs no Jira site, secrets or mint. There are three cases: 250 records, the largest plain-text records up to 768 KB, and the largest records of three-byte characters. The last batch is within 768 KB in UTF-16, the encoding GitHub documents for the limit, and over 1 MB in UTF-8. make script-test fails when the hand-off in the real workflows stops matching the copy in the check. Signed-off-by: guy oron --- .../scripts/jira-poll-record-digest-test.sh | 90 ++++++++ .github/scripts/jira-poll-record-digest.sh | 15 ++ .../jira-poll-batch-check-dispatch.yml | 53 +++++ .../workflows/jira-poll-batch-check-poll.yml | 116 ++++++++++ .github/workflows/jira-poll-batch-check.yml | 90 ++++++++ Makefile | 1 + docs/guides/dev/testing-workflows.md | 47 ++++ hack/prove-jira-poll-batch/main.go | 203 ++++++++++++++++++ hack/prove-jira-poll-batch/main_test.go | 90 ++++++++ 9 files changed, 705 insertions(+) create mode 100755 .github/scripts/jira-poll-record-digest-test.sh create mode 100755 .github/scripts/jira-poll-record-digest.sh create mode 100644 .github/workflows/jira-poll-batch-check-dispatch.yml create mode 100644 .github/workflows/jira-poll-batch-check-poll.yml create mode 100644 .github/workflows/jira-poll-batch-check.yml create mode 100644 hack/prove-jira-poll-batch/main.go create mode 100644 hack/prove-jira-poll-batch/main_test.go diff --git a/.github/scripts/jira-poll-record-digest-test.sh b/.github/scripts/jira-poll-record-digest-test.sh new file mode 100755 index 0000000000..ceb4825e45 --- /dev/null +++ b/.github/scripts/jira-poll-record-digest-test.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# jira-poll-record-digest-test.sh — digest and workflow-contract tests for the +# Jira poll batch check. +# +# The batch check is only evidence while its stand-in workflows hand the +# batch over the way the real ones do. The contract cases below fail when the +# real hand-off changes and the stand-ins do not follow. +# +# Run from the repo root: +# bash .github/scripts/jira-poll-record-digest-test.sh + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT="${SCRIPT_DIR}/jira-poll-record-digest.sh" +WORKFLOWS="${SCRIPT_DIR}/../workflows" +TEMPLATE="${SCRIPT_DIR}/../../internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml" + +fail() { echo "FAIL: $*" >&2; exit 1; } +contains() { grep -Fq -- "$2" "$1" || fail "${1} does not contain ${2}"; } +digest() { printf '%s' "$1" | "${SCRIPT}"; } + +# The digest is of the content, not of how the JSON is written. +want="$(digest '{"agent":"triage","event_payload":{"body":"a/dev/null 2>&1; then + fail "input that is not JSON produced a digest" +fi + +# The poll stand-in builds the matrix output with the real workflow's step. +matrix_step() { + awk ' + /^ - name: Build dispatch matrix$/ { on = 1 } + on && seen && /^ - / { exit } + on { + seen = 1 + if ($0 ~ /^[[:space:]]*$/) { blank = blank $0 "\n"; next } + printf "%s%s\n", blank, $0 + blank = "" + } + ' "$1" +} +real_step="$(matrix_step "${WORKFLOWS}/reusable-poll-jira.yml")" +[[ -n "${real_step}" ]] || fail "reusable-poll-jira.yml has no Build dispatch matrix step" +[[ "$(matrix_step "${WORKFLOWS}/jira-poll-batch-check-poll.yml")" == "${real_step}" ]] || + fail "the Build dispatch matrix step of jira-poll-batch-check-poll.yml differs from reusable-poll-jira.yml" + +# Both return the matrix as the poll job's output. +for workflow in reusable-poll-jira.yml jira-poll-batch-check-poll.yml; do + contains "${WORKFLOWS}/${workflow}" 'value: ${{ jobs.poll.outputs.matrix }}' + contains "${WORKFLOWS}/${workflow}" 'matrix: ${{ steps.matrix.outputs.matrix }}' +done + +# The caller hands the matrix on under the managed caller's condition. +condition() { grep -F 'fromJSON(needs.poll.outputs.matrix)' "$1" | sed 's/^[[:space:]]*//'; } +real_condition="$(condition "${TEMPLATE}")" +[[ -n "${real_condition}" ]] || fail "jira-poll-per-repo.yaml has no dispatch condition" +[[ "$(condition "${WORKFLOWS}/jira-poll-batch-check.yml")" == "${real_condition}" ]] || + fail "the dispatch condition of jira-poll-batch-check.yml differs from jira-poll-per-repo.yaml" +for caller in "${TEMPLATE}" "${WORKFLOWS}/jira-poll-batch-check.yml"; do + contains "${caller}" 'matrix: ${{ needs.poll.outputs.matrix }}' +done + +# The real dispatch workflow still takes the matrix as a string input and +# makes one job of each record, which the dispatch stand-in copies. +contains "${WORKFLOWS}/reusable-dispatch.yml" 'matrix: ${{ fromJSON(inputs.matrix != '"''"' && inputs.matrix || ' +contains "${WORKFLOWS}/reusable-dispatch.yml" 'EVENT_PAYLOAD: ${{ toJSON(matrix.event_payload) }}' +contains "${WORKFLOWS}/jira-poll-batch-check-dispatch.yml" 'matrix: ${{ fromJSON(inputs.matrix) }}' +contains "${WORKFLOWS}/jira-poll-batch-check-dispatch.yml" 'RECORD: ${{ toJSON(matrix) }}' + +echo "jira poll record digest and workflow-contract tests passed" diff --git a/.github/scripts/jira-poll-record-digest.sh b/.github/scripts/jira-poll-record-digest.sh new file mode 100755 index 0000000000..e975b50273 --- /dev/null +++ b/.github/scripts/jira-poll-record-digest.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# jira-poll-record-digest.sh — Print the SHA-256 of one dispatch record +# +# Reads a JSON value on stdin and hashes its canonical form: keys sorted, no +# insignificant whitespace, strings written the way jq writes them. The Jira +# poll batch check (.github/workflows/jira-poll-batch-check.yml) hashes each +# record when it builds the batch and again in the matrix job that receives +# it. GitHub parses and re-serializes the record on the way, so the bytes +# differ, and the two digests agree only when the content is the same. +# +# Usage: jira-poll-record-digest.sh < record.json + +set -euo pipefail + +jq -cSj . | sha256sum | awk '{print $1}' diff --git a/.github/workflows/jira-poll-batch-check-dispatch.yml b/.github/workflows/jira-poll-batch-check-dispatch.yml new file mode 100644 index 0000000000..ccdd576078 --- /dev/null +++ b/.github/workflows/jira-poll-batch-check-dispatch.yml @@ -0,0 +1,53 @@ +# Dispatch side of the Jira poll batch check (jira-poll-batch-check.yml). +# +# Stands in for the harness-run job of reusable-dispatch.yml. It takes the +# matrix as a string input and turns it into one job per record with +# fromJSON(inputs.matrix), as that job does. Each job hashes the record it +# received and looks the digest up among the digests of the batch, where the +# real job would run an agent. +name: Jira poll batch check (dispatch) + +on: + workflow_call: + inputs: + matrix: + description: Dispatch matrix, as reusable-dispatch.yml takes it. + type: string + required: true + digests: + description: JSON array with the digest of every record of the batch. + type: string + required: true + +jobs: + record: + name: Record ${{ strategy.job-index }} + strategy: + fail-fast: false + matrix: ${{ fromJSON(inputs.matrix) }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Checkout the digest script + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + sparse-checkout: | + .github/scripts/jira-poll-record-digest.sh + sparse-checkout-cone-mode: false + + - name: Compare the record with the batch + env: + RECORD: ${{ toJSON(matrix) }} + DIGESTS: ${{ inputs.digests }} + INDEX: ${{ strategy.job-index }} + run: | + set -euo pipefail + digest=$(printf '%s' "${RECORD}" | .github/scripts/jira-poll-record-digest.sh) + if ! jq -e --arg digest "${digest}" 'index($digest) != null' <<<"${DIGESTS}" > /dev/null; then + echo "::error::record ${INDEX} (${digest}) is not a record of the batch" + exit 1 + fi + echo "Record ${INDEX} arrived unchanged (${digest})." diff --git a/.github/workflows/jira-poll-batch-check-poll.yml b/.github/workflows/jira-poll-batch-check-poll.yml new file mode 100644 index 0000000000..bf0832b4b7 --- /dev/null +++ b/.github/workflows/jira-poll-batch-check-poll.yml @@ -0,0 +1,116 @@ +# Poll side of the Jira poll batch check (jira-poll-batch-check.yml). +# +# Stands in for reusable-poll-jira.yml. The poll job has that workflow's +# "Build dispatch matrix" step word for word and returns the matrix the same +# way: a step output, then the job's only output, then this workflow's output. +# What differs is where dispatches.json comes from: the batch job builds it +# with the real driver reading a fake Jira (hack/prove-jira-poll-batch). +# +# The record count, the digests and the sizes are outputs of the batch job, +# not of the poll job, so they still arrive when GitHub drops the matrix. +name: Jira poll batch check (poll) + +on: + workflow_call: + inputs: + case: + description: Batch to build (a case of hack/prove-jira-poll-batch). + type: string + required: true + outputs: + matrix: + description: Dispatch matrix, returned as reusable-poll-jira.yml returns it. + value: ${{ jobs.poll.outputs.matrix }} + count: + description: Number of records in the batch. + value: ${{ jobs.batch.outputs.count }} + digests: + description: JSON array with the digest of every record (jira-poll-record-digest.sh). + value: ${{ jobs.batch.outputs.digests }} + utf8_bytes: + description: Size of the matrix in UTF-8. + value: ${{ jobs.batch.outputs.utf8_bytes }} + utf16_bytes: + description: Size of the matrix in UTF-16, which is how GitHub approximates output size. + value: ${{ jobs.batch.outputs.utf16_bytes }} + +jobs: + batch: + name: Build the batch + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + outputs: + count: ${{ steps.describe.outputs.count }} + digests: ${{ steps.describe.outputs.digests }} + utf8_bytes: ${{ steps.describe.outputs.utf8_bytes }} + utf16_bytes: ${{ steps.describe.outputs.utf16_bytes }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: go.mod + + - name: Run one poll cycle against a fake Jira + env: + CASE: ${{ inputs.case }} + TARGET_REPO: ${{ github.repository }} + run: go run ./hack/prove-jira-poll-batch -case "${CASE}" -target-repo "${TARGET_REPO}" -out dispatches.json + + - name: Describe the batch + id: describe + run: | + set -euo pipefail + matrix=$(jq -c '{include: .}' dispatches.json) + digests=$(jq -c '.[]' dispatches.json | while IFS= read -r record; do + printf '%s' "${record}" | .github/scripts/jira-poll-record-digest.sh + done | jq -Rcs 'split("\n") | map(select(. != ""))') + { + echo "count=$(jq 'length' dispatches.json)" + echo "digests=${digests}" + echo "utf8_bytes=$(printf '%s' "${matrix}" | wc -c)" + echo "utf16_bytes=$(printf '%s' "${matrix}" | iconv -f UTF-8 -t UTF-16LE | wc -c)" + } >> "${GITHUB_OUTPUT}" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dispatches + path: dispatches.json + retention-days: 7 + + poll: + name: Poll Jira + needs: batch + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dispatches + + - name: Build dispatch matrix + id: matrix + run: | + set -euo pipefail + jq -e 'type == "array"' dispatches.json > /dev/null + if jq -e 'length == 0' dispatches.json > /dev/null; then + echo "No dispatches." + echo 'matrix={"include":[]}' >> "${GITHUB_OUTPUT}" + exit 0 + fi + MATRIX=$(jq -c '{include: .}' dispatches.json) + DELIM="MATRIX_$(openssl rand -hex 8)" + { + echo "matrix<<${DELIM}" + printf '%s\n' "${MATRIX}" + echo "${DELIM}" + } >> "${GITHUB_OUTPUT}" diff --git a/.github/workflows/jira-poll-batch-check.yml b/.github/workflows/jira-poll-batch-check.yml new file mode 100644 index 0000000000..620b8b0d98 --- /dev/null +++ b/.github/workflows/jira-poll-batch-check.yml @@ -0,0 +1,90 @@ +# Full-size batch check for the Jira poll hand-off on GitHub (ADR 0085). +# +# The managed poll workflow passes a cycle's whole batch from the poll job to +# the dispatch job as one job output, and runs each record as one job of a +# matrix. GitHub limits a job's outputs to 1 MB and a matrix to 256 jobs, and +# a batch over either limit is lost whole. The jira-poll driver therefore +# stops a cycle at 250 records and 768 KB. This workflow shows, on GitHub, +# that a batch at those limits arrives whole. +# +# It has the shape of the managed caller +# (internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml): a poll +# job that returns a matrix through a reusable workflow's output, and a +# dispatch job, under the same condition, that hands the matrix to a second +# reusable workflow as an input. Two things differ. The batch comes from the +# real driver reading a fake Jira (hack/prove-jira-poll-batch) instead of +# from a Jira site, and each record's job compares the record it received +# with the one the batch held instead of running an agent. +# +# Run it once per case when a change touches the limits, the record format or +# the hand-off. See "Jira poll batch check" in +# docs/guides/dev/testing-workflows.md. +name: Jira poll batch check + +on: + workflow_dispatch: + inputs: + case: + description: Batch to send through the hand-off + type: choice + required: true + options: + - records + - size + - wide + +permissions: {} + +jobs: + poll: + permissions: + contents: read + uses: ./.github/workflows/jira-poll-batch-check-poll.yml + with: + case: ${{ inputs.case }} + + dispatch: + needs: poll + if: ${{ needs.poll.outputs.matrix != '' && fromJSON(needs.poll.outputs.matrix).include[0] != null }} + permissions: + contents: read + uses: ./.github/workflows/jira-poll-batch-check-dispatch.yml + with: + matrix: ${{ needs.poll.outputs.matrix }} + digests: ${{ needs.poll.outputs.digests }} + + verify: + name: Verify the batch arrived whole + needs: [poll, dispatch] + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + actions: read + steps: + - name: Count the records that reached their own job + env: + GH_TOKEN: ${{ github.token }} + CASE: ${{ inputs.case }} + EXPECTED: ${{ needs.poll.outputs.count }} + UTF8_BYTES: ${{ needs.poll.outputs.utf8_bytes }} + UTF16_BYTES: ${{ needs.poll.outputs.utf16_bytes }} + DISPATCH_RESULT: ${{ needs.dispatch.result }} + run: | + set -euo pipefail + echo "Case ${CASE}: ${EXPECTED} records, ${UTF16_BYTES} bytes in UTF-16, ${UTF8_BYTES} bytes in UTF-8." + if [[ -z "${EXPECTED}" || "${EXPECTED}" -eq 0 ]]; then + echo "::error::the batch holds no records" + exit 1 + fi + if [[ "${DISPATCH_RESULT}" != "success" ]]; then + echo "::error::the dispatch job ended as '${DISPATCH_RESULT}': the batch did not arrive whole" + exit 1 + fi + arrived=$(gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs?per_page=100" \ + --jq '.jobs[] | select(.name | contains("/ Record ")) | select(.conclusion == "success") | .name' | wc -l) + if [[ "${arrived}" -ne "${EXPECTED}" ]]; then + echo "::error::${arrived} records reached their own job unchanged, want ${EXPECTED}" + exit 1 + fi + echo "All ${EXPECTED} records reached their own job unchanged." diff --git a/Makefile b/Makefile index e4e9e0f2e1..94ce1fadca 100644 --- a/Makefile +++ b/Makefile @@ -195,6 +195,7 @@ script-test: $(call run-timed,bash scripts/run-with-infra-retry-test.sh) $(call run-timed,bash .github/scripts/check-fix-eligibility-test.sh) $(call run-timed,bash .github/scripts/count-fix-commits-test.sh) + $(call run-timed,bash .github/scripts/jira-poll-record-digest-test.sh) $(call run-timed,bash .github/scripts/pre-fetch-review-body-test.sh) $(call run-timed,bash .github/scripts/review-diff-hash-test.sh) $(call run-timed,bash .github/scripts/report-agent-startup-failure-test.sh) diff --git a/docs/guides/dev/testing-workflows.md b/docs/guides/dev/testing-workflows.md index e815a766ae..b732d37a60 100644 --- a/docs/guides/dev/testing-workflows.md +++ b/docs/guides/dev/testing-workflows.md @@ -72,6 +72,53 @@ Push the change and trigger a fullsend action on the test repository: `/fs-triage`, `/fs-code`, or another agent command. Revert the references to the desired release or branch before deleting or rewriting the test ref. +## Jira poll batch check + +On GitHub, the managed Jira poll workflow passes a cycle's dispatch records +from the poll job to the dispatch job as one job output, and runs each record +as one job of a matrix. GitHub limits a job's outputs to 1 MB and a matrix to +256 jobs. A batch over either limit is lost whole, so the jira-poll driver +stops a cycle at 250 records and 768 KB (ADR 0085). + +The `Jira poll batch check` workflow +(`.github/workflows/jira-poll-batch-check.yml`) shows on GitHub that a batch +at those limits arrives whole. It runs one real poll cycle against a fake Jira +(`hack/prove-jira-poll-batch`), so the batch is as large as the driver allows, +and sends it along the same path as the managed workflow: a job output of a +reusable workflow, then an input of a second reusable workflow, then one +matrix job per record. Each matrix job compares the record it received with +the one the batch held, and a last job checks that every record got a job. No +agent runs, and the check needs no Jira site, secrets or mint. + +Run it once per case when a change touches the driver's limits, the dispatch +record format, or how `reusable-poll-jira.yml`, the managed caller or +`reusable-dispatch.yml` hand the matrix over: + +```bash +gh workflow run jira-poll-batch-check.yml -f case=records +``` + +| Case | Batch | +|------|-------| +| `records` | 250 records, the record limit, with comments as long as still fit in 768 KB | +| `size` | The largest plain-text records, up to 768 KB | +| `wide` | The largest records of three-byte characters, up to 768 KB | + +GitHub approximates output size from the UTF-16 encoding, and the driver +measures the same way. The `wide` batch is within 768 KB by that measure and +over 1 MB in UTF-8, so it passes only while GitHub counts as documented. + +A run passes when its `Verify the batch arrived whole` job passes. That job +prints the batch's record count and its size in both encodings. When the poll +job's output is over GitHub's limit, the output arrives empty, the dispatch +job is skipped and the verify job fails. + +The check covers the hand-off only. It does not run agents, so it says +nothing about runner capacity or about how long 250 agent runs take. + +`make script-test` fails when the hand-off in the real workflows no longer +matches the copy in the check (`.github/scripts/jira-poll-record-digest-test.sh`). + ## Running CI checks locally On macOS, or a Linux distribution other than Ubuntu, `ci-local` runs the PR diff --git a/hack/prove-jira-poll-batch/main.go b/hack/prove-jira-poll-batch/main.go new file mode 100644 index 0000000000..cc7990d1ae --- /dev/null +++ b/hack/prove-jira-poll-batch/main.go @@ -0,0 +1,203 @@ +// Command prove-jira-poll-batch writes the dispatch file a jira-poll cycle +// produces when a Jira project holds more work than one cycle may take, so +// the batch is as large as the driver's limits allow (ADR 0085, Decision +// items 3 and 4). The full-size batch check +// (.github/workflows/jira-poll-batch-check.yml) passes that file through the +// same hand-off as the managed poll workflow, on GitHub. +// +// The driver is the real one: a jirapoll.Poller reads a fake Jira over HTTP +// and each record is projected as the CLI projects it. Only the Jira content +// and the single agent every comment matches are made up. +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "io" + "log" + "os" + "sort" + "strings" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/harnessdispatch" + "github.com/fullsend-ai/fullsend/internal/jirapoll" + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/pkg/behaviourtest/drivers/jiramock" +) + +const ( + // command starts every comment, so each one is an authorized request. + command = "/fs-triage " + // maxBody is the number of code points of a comment body the driver + // carries on the GitHub target. + maxBody = 4096 +) + +// batchCase describes the Jira content of one case. Every issue holds one +// comment of the command followed by filler. +type batchCase struct { + about string + issues int // more than a cycle can take + filler string // one code point, repeated after the command + // fillerLen is the number of filler code points, or -1 for the most that + // still lets a cycle take the record limit. + fillerLen int +} + +var cases = map[string]batchCase{ + "records": { + about: "250 records, the record limit, with comments as long as still fit in the size limit", + issues: 300, + filler: "a", + fillerLen: -1, + }, + "size": { + about: "the largest plain-text records, up to the size limit", + issues: 60, + filler: "a", + fillerLen: maxBody - len(command), + }, + "wide": { + about: "the largest records of three-byte characters, up to the size limit: the same size in UTF-16 as the size case and half as much again in UTF-8", + issues: 60, + filler: "語", + fillerLen: maxBody - len(command), + }, +} + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +// run builds the batch the arguments name and returns the exit code. +func run(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("prove-jira-poll-batch", flag.ContinueOnError) + fs.SetOutput(stderr) + name := fs.String("case", "", "batch to build: "+strings.Join(caseNames(), ", ")) + out := fs.String("out", "dispatches.json", "path of the dispatch file to write") + targetRepo := fs.String("target-repo", "fullsend-ai/fullsend", "owner/repo the records name as their target") + if err := fs.Parse(args); err != nil { + return 2 + } + + // The poller logs every warning of a cycle; only the result matters here. + log.SetOutput(io.Discard) + + records, err := build(*name, *targetRepo, *out) + if err != nil { + fmt.Fprintln(stderr, "prove-jira-poll-batch:", err) + return 1 + } + fmt.Fprintf(stdout, "case %s: %d records in %s (%s)\n", *name, records, *out, cases[*name].about) + return 0 +} + +func caseNames() []string { + names := make([]string, 0, len(cases)) + for name := range cases { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// build writes the dispatch file of the named case to out and returns the +// number of records in it. +func build(name, targetRepo, out string) (int, error) { + c, ok := cases[name] + if !ok { + return 0, fmt.Errorf("unknown case %q: want one of %s", name, strings.Join(caseNames(), ", ")) + } + if c.fillerLen >= 0 { + return runCycle(c, c.fillerLen, targetRepo, out) + } + + // Find the longest comment with which a cycle still takes the record + // limit: a longer one makes the size limit stop the cycle first. + limit := config.MaxJiraPollMaxDispatchesPerCycle + lo, hi := 0, maxBody-len(command) + for lo < hi { + mid := (lo + hi + 1) / 2 + records, err := runCycle(c, mid, targetRepo, out) + if err != nil { + return 0, err + } + if records >= limit { + lo = mid + } else { + hi = mid - 1 + } + } + return runCycle(c, lo, targetRepo, out) +} + +// runCycle fills a fake Jira with the case's issues, runs one poll cycle at +// the highest configurable record limit, and returns the number of records +// the cycle wrote to out. +func runCycle(c batchCase, fillerLen int, targetRepo, out string) (int, error) { + srv, state := jiramock.NewServer() + defer srv.Close() + + body := command + strings.Repeat(c.filler, fillerLen) + for i := 1; i <= c.issues; i++ { + key := fmt.Sprintf("PROJ-%d", i) + state.AddIssue(key, nil) + state.AddComment(key, body) + } + + client, err := jira.New("test-token", jira.WithBaseURL(srv.URL)) + if err != nil { + return 0, fmt.Errorf("create Jira client: %w", err) + } + poller := jirapoll.New(client, oneAgent{}, jirapoll.Options{ + TargetRepo: targetRepo, + // A fixed site name, so a record's size does not depend on the + // fake server's port. + JiraBaseURL: "https://example.atlassian.net", + JiraProject: "PROJ", + OutputPath: out, + MaxDispatchesPerCycle: config.MaxJiraPollMaxDispatchesPerCycle, + }) + if err := poller.Run(context.Background()); err != nil { + return 0, fmt.Errorf("poll cycle: %w", err) + } + + data, err := os.ReadFile(out) + if err != nil { + return 0, err + } + var records []json.RawMessage + if err := json.Unmarshal(data, &records); err != nil { + return 0, fmt.Errorf("read %s: %w", out, err) + } + return len(records), nil +} + +// oneAgent matches every authorized event to one agent and projects the +// record with harnessdispatch.ProjectExecutionRef, as the CLI's matcher does +// for each harness an event triggers. +type oneAgent struct{} + +func (oneAgent) Match(_ context.Context, event *normevent.Event) ([]jirapoll.DispatchRecord, error) { + if !harnessdispatch.IsAuthorized(event) { + return nil, nil + } + ref, err := harnessdispatch.ProjectExecutionRef("triage", "triage", event) + if err != nil { + return nil, err + } + return []jirapoll.DispatchRecord{{ + Agent: ref.Agent, + Role: ref.Role, + SourceRepo: ref.SourceRepo, + EventType: ref.EventType, + EventPayload: ref.EventPayload, + TriggerSource: ref.TriggerSource, + StatusRepo: ref.StatusRepo, + StatusNumber: ref.StatusNumber, + }}, nil +} diff --git a/hack/prove-jira-poll-batch/main_test.go b/hack/prove-jira-poll-batch/main_test.go new file mode 100644 index 0000000000..e61be2bc27 --- /dev/null +++ b/hack/prove-jira-poll-batch/main_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + "unicode/utf16" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/config" +) + +// sizeLimit is the driver's limit on the matrix output of one cycle on the +// GitHub target: three quarters of GitHub's 1 MB limit on a job's outputs. +const sizeLimit = 768 * 1024 + +// matrix returns the poll job's matrix output for the dispatch file at path, +// as the managed workflow builds it with jq -c '{include: .}', and the number +// of records in it. +func matrix(t *testing.T, path string) (string, int) { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err) + var records []json.RawMessage + require.NoError(t, json.Unmarshal(data, &records)) + out, err := json.Marshal(map[string][]json.RawMessage{"include": records}) + require.NoError(t, err) + return string(out), len(records) +} + +// utf16Bytes is the size GitHub counts for a job output: it approximates +// output size from the UTF-16 encoding. +func utf16Bytes(s string) int { + return 2 * len(utf16.Encode([]rune(s))) +} + +// Every case is a batch the real driver stopped at one of its limits, with +// no room left for another record. +func TestRunFillsABatchToTheLimits(t *testing.T) { + for name, want := range map[string]struct { + records int + overOneM bool // larger than 1 MB in UTF-8 + }{ + "records": {records: config.MaxJiraPollMaxDispatchesPerCycle}, + "size": {records: 30}, + "wide": {records: 30, overOneM: true}, + } { + t.Run(name, func(t *testing.T) { + out := filepath.Join(t.TempDir(), "dispatches.json") + var stdout, stderr strings.Builder + require.Zero(t, run([]string{"-case", name, "-out", out}, &stdout, &stderr), stderr.String()) + + m, n := matrix(t, out) + assert.Equal(t, want.records, n) + assert.Contains(t, stdout.String(), fmt.Sprintf("case %s: %d records in ", name, n), "run reports the records it wrote") + + size := utf16Bytes(m) + assert.LessOrEqual(t, size, sizeLimit, "the driver keeps the batch within its size limit") + // One more record of the average size would not fit, so the batch + // is at the size limit as well as, for the records case, at the + // record limit. + assert.Greater(t, size+size/n, sizeLimit, "the batch has no room for another record") + + if want.overOneM { + assert.Greater(t, len(m), 1<<20, "the wide batch is over 1 MB in UTF-8 while within the limit in UTF-16") + } else { + assert.Less(t, len(m), 1<<20) + } + }) + } +} + +func TestRunRejectsAnUnknownCaseOrFlag(t *testing.T) { + out := filepath.Join(t.TempDir(), "dispatches.json") + + var stderr strings.Builder + assert.Equal(t, 1, run([]string{"-case", "huge", "-out", out}, io.Discard, &stderr)) + assert.Contains(t, stderr.String(), `unknown case "huge": want one of records, size, wide`) + assert.NoFileExists(t, out) + + stderr.Reset() + assert.Equal(t, 2, run([]string{"-cases", "size"}, io.Discard, &stderr)) + assert.Contains(t, stderr.String(), "flag provided but not defined: -cases") +} From acbb149e1daf7587fc2f22b1d711c74ff6396082 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 07:18:47 +0200 Subject: [PATCH 24/60] 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 f76283753767cfa3f28519a7a692ee4d76fac4dd Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 07:24:34 +0200 Subject: [PATCH 25/60] ci(jira-poll): size the batch check by what GitHub counts The first runs of the check on GitHub passed for the 250-record and plain-text batches and failed for the batch of three-byte characters: it was within the driver's 768 KB limit, and GitHub failed the poll job with "Job outputs exceed 1,048,576 bytes". The driver now counts as GitHub does, two bytes for each byte of UTF-8, so that batch holds 10 of the largest records where it held 30. Report the batch's size in bytes of UTF-8 and as GitHub counts it, in place of the UTF-16 size, and say in the guide what the check found. Signed-off-by: guy oron --- .../workflows/jira-poll-batch-check-poll.yml | 15 +++------ .github/workflows/jira-poll-batch-check.yml | 5 ++- docs/guides/dev/testing-workflows.md | 15 +++++---- hack/prove-jira-poll-batch/main.go | 2 +- hack/prove-jira-poll-batch/main_test.go | 32 +++++++------------ 5 files changed, 29 insertions(+), 40 deletions(-) diff --git a/.github/workflows/jira-poll-batch-check-poll.yml b/.github/workflows/jira-poll-batch-check-poll.yml index bf0832b4b7..03cccfd898 100644 --- a/.github/workflows/jira-poll-batch-check-poll.yml +++ b/.github/workflows/jira-poll-batch-check-poll.yml @@ -27,12 +27,9 @@ on: digests: description: JSON array with the digest of every record (jira-poll-record-digest.sh). value: ${{ jobs.batch.outputs.digests }} - utf8_bytes: - description: Size of the matrix in UTF-8. - value: ${{ jobs.batch.outputs.utf8_bytes }} - utf16_bytes: - description: Size of the matrix in UTF-16, which is how GitHub approximates output size. - value: ${{ jobs.batch.outputs.utf16_bytes }} + bytes: + description: Size of the matrix in bytes of UTF-8. GitHub counts each one as two. + value: ${{ jobs.batch.outputs.bytes }} jobs: batch: @@ -44,8 +41,7 @@ jobs: outputs: count: ${{ steps.describe.outputs.count }} digests: ${{ steps.describe.outputs.digests }} - utf8_bytes: ${{ steps.describe.outputs.utf8_bytes }} - utf16_bytes: ${{ steps.describe.outputs.utf16_bytes }} + bytes: ${{ steps.describe.outputs.bytes }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -73,8 +69,7 @@ jobs: { echo "count=$(jq 'length' dispatches.json)" echo "digests=${digests}" - echo "utf8_bytes=$(printf '%s' "${matrix}" | wc -c)" - echo "utf16_bytes=$(printf '%s' "${matrix}" | iconv -f UTF-8 -t UTF-16LE | wc -c)" + echo "bytes=$(printf '%s' "${matrix}" | wc -c)" } >> "${GITHUB_OUTPUT}" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/.github/workflows/jira-poll-batch-check.yml b/.github/workflows/jira-poll-batch-check.yml index 620b8b0d98..9f06a45237 100644 --- a/.github/workflows/jira-poll-batch-check.yml +++ b/.github/workflows/jira-poll-batch-check.yml @@ -67,12 +67,11 @@ jobs: GH_TOKEN: ${{ github.token }} CASE: ${{ inputs.case }} EXPECTED: ${{ needs.poll.outputs.count }} - UTF8_BYTES: ${{ needs.poll.outputs.utf8_bytes }} - UTF16_BYTES: ${{ needs.poll.outputs.utf16_bytes }} + BYTES: ${{ needs.poll.outputs.bytes }} DISPATCH_RESULT: ${{ needs.dispatch.result }} run: | set -euo pipefail - echo "Case ${CASE}: ${EXPECTED} records, ${UTF16_BYTES} bytes in UTF-16, ${UTF8_BYTES} bytes in UTF-8." + echo "Case ${CASE}: ${EXPECTED} records in ${BYTES} bytes of UTF-8, which GitHub counts as $((2 * BYTES)) of the 1048576 a job's outputs may hold." if [[ -z "${EXPECTED}" || "${EXPECTED}" -eq 0 ]]; then echo "::error::the batch holds no records" exit 1 diff --git a/docs/guides/dev/testing-workflows.md b/docs/guides/dev/testing-workflows.md index b732d37a60..f05dbcb23c 100644 --- a/docs/guides/dev/testing-workflows.md +++ b/docs/guides/dev/testing-workflows.md @@ -104,14 +104,17 @@ gh workflow run jira-poll-batch-check.yml -f case=records | `size` | The largest plain-text records, up to 768 KB | | `wide` | The largest records of three-byte characters, up to 768 KB | -GitHub approximates output size from the UTF-16 encoding, and the driver -measures the same way. The `wide` batch is within 768 KB by that measure and -over 1 MB in UTF-8, so it passes only while GitHub counts as documented. +GitHub counts two bytes for each byte of an output's UTF-8 text, so a batch +at the 768 KB limit is about 384 KB of JSON. Its documentation says only that +the size is "approximated based on UTF-16 encoding". The `wide` case holds the +difference: a count of two bytes per UTF-16 code unit puts three times as many +of its records in a batch, and GitHub rejects that batch with +`Job outputs exceed 1,048,576 bytes`. A run passes when its `Verify the batch arrived whole` job passes. That job -prints the batch's record count and its size in both encodings. When the poll -job's output is over GitHub's limit, the output arrives empty, the dispatch -job is skipped and the verify job fails. +prints the batch's record count and size. When the poll job's output is over +GitHub's limit, GitHub fails the poll job, the dispatch job is skipped and +the verify job fails. The check covers the hand-off only. It does not run agents, so it says nothing about runner capacity or about how long 250 agent runs take. diff --git a/hack/prove-jira-poll-batch/main.go b/hack/prove-jira-poll-batch/main.go index cc7990d1ae..eab279e295 100644 --- a/hack/prove-jira-poll-batch/main.go +++ b/hack/prove-jira-poll-batch/main.go @@ -62,7 +62,7 @@ var cases = map[string]batchCase{ fillerLen: maxBody - len(command), }, "wide": { - about: "the largest records of three-byte characters, up to the size limit: the same size in UTF-16 as the size case and half as much again in UTF-8", + about: "the largest records of three-byte characters, up to the size limit", issues: 60, filler: "語", fillerLen: maxBody - len(command), diff --git a/hack/prove-jira-poll-batch/main_test.go b/hack/prove-jira-poll-batch/main_test.go index e61be2bc27..2319020d05 100644 --- a/hack/prove-jira-poll-batch/main_test.go +++ b/hack/prove-jira-poll-batch/main_test.go @@ -8,7 +8,6 @@ import ( "path/filepath" "strings" "testing" - "unicode/utf16" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -34,22 +33,21 @@ func matrix(t *testing.T, path string) (string, int) { return string(out), len(records) } -// utf16Bytes is the size GitHub counts for a job output: it approximates -// output size from the UTF-16 encoding. -func utf16Bytes(s string) int { - return 2 * len(utf16.Encode([]rune(s))) +// counted is the size GitHub counts for a job output: two bytes for each +// byte of its UTF-8 text. +func counted(s string) int { + return 2 * len(s) } // Every case is a batch the real driver stopped at one of its limits, with // no room left for another record. func TestRunFillsABatchToTheLimits(t *testing.T) { - for name, want := range map[string]struct { - records int - overOneM bool // larger than 1 MB in UTF-8 - }{ - "records": {records: config.MaxJiraPollMaxDispatchesPerCycle}, - "size": {records: 30}, - "wide": {records: 30, overOneM: true}, + for name, wantRecords := range map[string]int{ + "records": config.MaxJiraPollMaxDispatchesPerCycle, + "size": 30, + // A three-byte character counts three times an ASCII one, so a + // third as many of the largest records fit. + "wide": 10, } { t.Run(name, func(t *testing.T) { out := filepath.Join(t.TempDir(), "dispatches.json") @@ -57,21 +55,15 @@ func TestRunFillsABatchToTheLimits(t *testing.T) { require.Zero(t, run([]string{"-case", name, "-out", out}, &stdout, &stderr), stderr.String()) m, n := matrix(t, out) - assert.Equal(t, want.records, n) + assert.Equal(t, wantRecords, n) assert.Contains(t, stdout.String(), fmt.Sprintf("case %s: %d records in ", name, n), "run reports the records it wrote") - size := utf16Bytes(m) + size := counted(m) assert.LessOrEqual(t, size, sizeLimit, "the driver keeps the batch within its size limit") // One more record of the average size would not fit, so the batch // is at the size limit as well as, for the records case, at the // record limit. assert.Greater(t, size+size/n, sizeLimit, "the batch has no room for another record") - - if want.overOneM { - assert.Greater(t, len(m), 1<<20, "the wide batch is over 1 MB in UTF-8 while within the limit in UTF-16") - } else { - assert.Less(t, len(m), 1<<20) - } }) } } From 28eb759eda9d1aa9db74e8b40d9f537a012f710d Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 07:18:47 +0200 Subject: [PATCH 26/60] 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 dfaec9da504ae708acf368ad49cb8be947f086d5 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 03:08:26 +0200 Subject: [PATCH 27/60] ci(jira-poll): add a full-size batch check for the GitHub hand-off On GitHub the managed poll workflow passes a cycle's batch to the dispatch job as one job output and runs each record as a matrix job. A batch over GitHub's 1 MB output limit or 256-job matrix limit is lost whole, which is why the driver stops a cycle at 250 records and 768 KB (ADR 0085). Nothing showed on GitHub that a batch at those limits arrives. The Jira poll batch check workflow does. It builds the batch with the real driver reading a fake Jira (hack/prove-jira-poll-batch), returns it through a reusable workflow's job output with the production "Build dispatch matrix" step, hands it to a second reusable workflow under the managed caller's condition, and runs one job per record. Each job compares the record it received with the batch, and a last job checks that every record got a job. It is started by hand and needs no Jira site, secrets or mint. There are three cases: 250 records, the largest plain-text records up to 768 KB, and the largest records of three-byte characters. The last batch is within 768 KB in UTF-16, the encoding GitHub documents for the limit, and over 1 MB in UTF-8. make script-test fails when the hand-off in the real workflows stops matching the copy in the check. Signed-off-by: guy oron --- .../scripts/jira-poll-record-digest-test.sh | 90 ++++++++ .github/scripts/jira-poll-record-digest.sh | 15 ++ .../jira-poll-batch-check-dispatch.yml | 53 +++++ .../workflows/jira-poll-batch-check-poll.yml | 116 ++++++++++ .github/workflows/jira-poll-batch-check.yml | 90 ++++++++ Makefile | 1 + docs/guides/dev/testing-workflows.md | 47 ++++ hack/prove-jira-poll-batch/main.go | 203 ++++++++++++++++++ hack/prove-jira-poll-batch/main_test.go | 90 ++++++++ 9 files changed, 705 insertions(+) create mode 100755 .github/scripts/jira-poll-record-digest-test.sh create mode 100755 .github/scripts/jira-poll-record-digest.sh create mode 100644 .github/workflows/jira-poll-batch-check-dispatch.yml create mode 100644 .github/workflows/jira-poll-batch-check-poll.yml create mode 100644 .github/workflows/jira-poll-batch-check.yml create mode 100644 hack/prove-jira-poll-batch/main.go create mode 100644 hack/prove-jira-poll-batch/main_test.go diff --git a/.github/scripts/jira-poll-record-digest-test.sh b/.github/scripts/jira-poll-record-digest-test.sh new file mode 100755 index 0000000000..ceb4825e45 --- /dev/null +++ b/.github/scripts/jira-poll-record-digest-test.sh @@ -0,0 +1,90 @@ +#!/usr/bin/env bash +# jira-poll-record-digest-test.sh — digest and workflow-contract tests for the +# Jira poll batch check. +# +# The batch check is only evidence while its stand-in workflows hand the +# batch over the way the real ones do. The contract cases below fail when the +# real hand-off changes and the stand-ins do not follow. +# +# Run from the repo root: +# bash .github/scripts/jira-poll-record-digest-test.sh + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +SCRIPT="${SCRIPT_DIR}/jira-poll-record-digest.sh" +WORKFLOWS="${SCRIPT_DIR}/../workflows" +TEMPLATE="${SCRIPT_DIR}/../../internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml" + +fail() { echo "FAIL: $*" >&2; exit 1; } +contains() { grep -Fq -- "$2" "$1" || fail "${1} does not contain ${2}"; } +digest() { printf '%s' "$1" | "${SCRIPT}"; } + +# The digest is of the content, not of how the JSON is written. +want="$(digest '{"agent":"triage","event_payload":{"body":"a/dev/null 2>&1; then + fail "input that is not JSON produced a digest" +fi + +# The poll stand-in builds the matrix output with the real workflow's step. +matrix_step() { + awk ' + /^ - name: Build dispatch matrix$/ { on = 1 } + on && seen && /^ - / { exit } + on { + seen = 1 + if ($0 ~ /^[[:space:]]*$/) { blank = blank $0 "\n"; next } + printf "%s%s\n", blank, $0 + blank = "" + } + ' "$1" +} +real_step="$(matrix_step "${WORKFLOWS}/reusable-poll-jira.yml")" +[[ -n "${real_step}" ]] || fail "reusable-poll-jira.yml has no Build dispatch matrix step" +[[ "$(matrix_step "${WORKFLOWS}/jira-poll-batch-check-poll.yml")" == "${real_step}" ]] || + fail "the Build dispatch matrix step of jira-poll-batch-check-poll.yml differs from reusable-poll-jira.yml" + +# Both return the matrix as the poll job's output. +for workflow in reusable-poll-jira.yml jira-poll-batch-check-poll.yml; do + contains "${WORKFLOWS}/${workflow}" 'value: ${{ jobs.poll.outputs.matrix }}' + contains "${WORKFLOWS}/${workflow}" 'matrix: ${{ steps.matrix.outputs.matrix }}' +done + +# The caller hands the matrix on under the managed caller's condition. +condition() { grep -F 'fromJSON(needs.poll.outputs.matrix)' "$1" | sed 's/^[[:space:]]*//'; } +real_condition="$(condition "${TEMPLATE}")" +[[ -n "${real_condition}" ]] || fail "jira-poll-per-repo.yaml has no dispatch condition" +[[ "$(condition "${WORKFLOWS}/jira-poll-batch-check.yml")" == "${real_condition}" ]] || + fail "the dispatch condition of jira-poll-batch-check.yml differs from jira-poll-per-repo.yaml" +for caller in "${TEMPLATE}" "${WORKFLOWS}/jira-poll-batch-check.yml"; do + contains "${caller}" 'matrix: ${{ needs.poll.outputs.matrix }}' +done + +# The real dispatch workflow still takes the matrix as a string input and +# makes one job of each record, which the dispatch stand-in copies. +contains "${WORKFLOWS}/reusable-dispatch.yml" 'matrix: ${{ fromJSON(inputs.matrix != '"''"' && inputs.matrix || ' +contains "${WORKFLOWS}/reusable-dispatch.yml" 'EVENT_PAYLOAD: ${{ toJSON(matrix.event_payload) }}' +contains "${WORKFLOWS}/jira-poll-batch-check-dispatch.yml" 'matrix: ${{ fromJSON(inputs.matrix) }}' +contains "${WORKFLOWS}/jira-poll-batch-check-dispatch.yml" 'RECORD: ${{ toJSON(matrix) }}' + +echo "jira poll record digest and workflow-contract tests passed" diff --git a/.github/scripts/jira-poll-record-digest.sh b/.github/scripts/jira-poll-record-digest.sh new file mode 100755 index 0000000000..e975b50273 --- /dev/null +++ b/.github/scripts/jira-poll-record-digest.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# jira-poll-record-digest.sh — Print the SHA-256 of one dispatch record +# +# Reads a JSON value on stdin and hashes its canonical form: keys sorted, no +# insignificant whitespace, strings written the way jq writes them. The Jira +# poll batch check (.github/workflows/jira-poll-batch-check.yml) hashes each +# record when it builds the batch and again in the matrix job that receives +# it. GitHub parses and re-serializes the record on the way, so the bytes +# differ, and the two digests agree only when the content is the same. +# +# Usage: jira-poll-record-digest.sh < record.json + +set -euo pipefail + +jq -cSj . | sha256sum | awk '{print $1}' diff --git a/.github/workflows/jira-poll-batch-check-dispatch.yml b/.github/workflows/jira-poll-batch-check-dispatch.yml new file mode 100644 index 0000000000..ccdd576078 --- /dev/null +++ b/.github/workflows/jira-poll-batch-check-dispatch.yml @@ -0,0 +1,53 @@ +# Dispatch side of the Jira poll batch check (jira-poll-batch-check.yml). +# +# Stands in for the harness-run job of reusable-dispatch.yml. It takes the +# matrix as a string input and turns it into one job per record with +# fromJSON(inputs.matrix), as that job does. Each job hashes the record it +# received and looks the digest up among the digests of the batch, where the +# real job would run an agent. +name: Jira poll batch check (dispatch) + +on: + workflow_call: + inputs: + matrix: + description: Dispatch matrix, as reusable-dispatch.yml takes it. + type: string + required: true + digests: + description: JSON array with the digest of every record of the batch. + type: string + required: true + +jobs: + record: + name: Record ${{ strategy.job-index }} + strategy: + fail-fast: false + matrix: ${{ fromJSON(inputs.matrix) }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + steps: + - name: Checkout the digest script + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + sparse-checkout: | + .github/scripts/jira-poll-record-digest.sh + sparse-checkout-cone-mode: false + + - name: Compare the record with the batch + env: + RECORD: ${{ toJSON(matrix) }} + DIGESTS: ${{ inputs.digests }} + INDEX: ${{ strategy.job-index }} + run: | + set -euo pipefail + digest=$(printf '%s' "${RECORD}" | .github/scripts/jira-poll-record-digest.sh) + if ! jq -e --arg digest "${digest}" 'index($digest) != null' <<<"${DIGESTS}" > /dev/null; then + echo "::error::record ${INDEX} (${digest}) is not a record of the batch" + exit 1 + fi + echo "Record ${INDEX} arrived unchanged (${digest})." diff --git a/.github/workflows/jira-poll-batch-check-poll.yml b/.github/workflows/jira-poll-batch-check-poll.yml new file mode 100644 index 0000000000..bf0832b4b7 --- /dev/null +++ b/.github/workflows/jira-poll-batch-check-poll.yml @@ -0,0 +1,116 @@ +# Poll side of the Jira poll batch check (jira-poll-batch-check.yml). +# +# Stands in for reusable-poll-jira.yml. The poll job has that workflow's +# "Build dispatch matrix" step word for word and returns the matrix the same +# way: a step output, then the job's only output, then this workflow's output. +# What differs is where dispatches.json comes from: the batch job builds it +# with the real driver reading a fake Jira (hack/prove-jira-poll-batch). +# +# The record count, the digests and the sizes are outputs of the batch job, +# not of the poll job, so they still arrive when GitHub drops the matrix. +name: Jira poll batch check (poll) + +on: + workflow_call: + inputs: + case: + description: Batch to build (a case of hack/prove-jira-poll-batch). + type: string + required: true + outputs: + matrix: + description: Dispatch matrix, returned as reusable-poll-jira.yml returns it. + value: ${{ jobs.poll.outputs.matrix }} + count: + description: Number of records in the batch. + value: ${{ jobs.batch.outputs.count }} + digests: + description: JSON array with the digest of every record (jira-poll-record-digest.sh). + value: ${{ jobs.batch.outputs.digests }} + utf8_bytes: + description: Size of the matrix in UTF-8. + value: ${{ jobs.batch.outputs.utf8_bytes }} + utf16_bytes: + description: Size of the matrix in UTF-16, which is how GitHub approximates output size. + value: ${{ jobs.batch.outputs.utf16_bytes }} + +jobs: + batch: + name: Build the batch + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + outputs: + count: ${{ steps.describe.outputs.count }} + digests: ${{ steps.describe.outputs.digests }} + utf8_bytes: ${{ steps.describe.outputs.utf8_bytes }} + utf16_bytes: ${{ steps.describe.outputs.utf16_bytes }} + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version-file: go.mod + + - name: Run one poll cycle against a fake Jira + env: + CASE: ${{ inputs.case }} + TARGET_REPO: ${{ github.repository }} + run: go run ./hack/prove-jira-poll-batch -case "${CASE}" -target-repo "${TARGET_REPO}" -out dispatches.json + + - name: Describe the batch + id: describe + run: | + set -euo pipefail + matrix=$(jq -c '{include: .}' dispatches.json) + digests=$(jq -c '.[]' dispatches.json | while IFS= read -r record; do + printf '%s' "${record}" | .github/scripts/jira-poll-record-digest.sh + done | jq -Rcs 'split("\n") | map(select(. != ""))') + { + echo "count=$(jq 'length' dispatches.json)" + echo "digests=${digests}" + echo "utf8_bytes=$(printf '%s' "${matrix}" | wc -c)" + echo "utf16_bytes=$(printf '%s' "${matrix}" | iconv -f UTF-8 -t UTF-16LE | wc -c)" + } >> "${GITHUB_OUTPUT}" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dispatches + path: dispatches.json + retention-days: 7 + + poll: + name: Poll Jira + needs: batch + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + outputs: + matrix: ${{ steps.matrix.outputs.matrix }} + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dispatches + + - name: Build dispatch matrix + id: matrix + run: | + set -euo pipefail + jq -e 'type == "array"' dispatches.json > /dev/null + if jq -e 'length == 0' dispatches.json > /dev/null; then + echo "No dispatches." + echo 'matrix={"include":[]}' >> "${GITHUB_OUTPUT}" + exit 0 + fi + MATRIX=$(jq -c '{include: .}' dispatches.json) + DELIM="MATRIX_$(openssl rand -hex 8)" + { + echo "matrix<<${DELIM}" + printf '%s\n' "${MATRIX}" + echo "${DELIM}" + } >> "${GITHUB_OUTPUT}" diff --git a/.github/workflows/jira-poll-batch-check.yml b/.github/workflows/jira-poll-batch-check.yml new file mode 100644 index 0000000000..620b8b0d98 --- /dev/null +++ b/.github/workflows/jira-poll-batch-check.yml @@ -0,0 +1,90 @@ +# Full-size batch check for the Jira poll hand-off on GitHub (ADR 0085). +# +# The managed poll workflow passes a cycle's whole batch from the poll job to +# the dispatch job as one job output, and runs each record as one job of a +# matrix. GitHub limits a job's outputs to 1 MB and a matrix to 256 jobs, and +# a batch over either limit is lost whole. The jira-poll driver therefore +# stops a cycle at 250 records and 768 KB. This workflow shows, on GitHub, +# that a batch at those limits arrives whole. +# +# It has the shape of the managed caller +# (internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml): a poll +# job that returns a matrix through a reusable workflow's output, and a +# dispatch job, under the same condition, that hands the matrix to a second +# reusable workflow as an input. Two things differ. The batch comes from the +# real driver reading a fake Jira (hack/prove-jira-poll-batch) instead of +# from a Jira site, and each record's job compares the record it received +# with the one the batch held instead of running an agent. +# +# Run it once per case when a change touches the limits, the record format or +# the hand-off. See "Jira poll batch check" in +# docs/guides/dev/testing-workflows.md. +name: Jira poll batch check + +on: + workflow_dispatch: + inputs: + case: + description: Batch to send through the hand-off + type: choice + required: true + options: + - records + - size + - wide + +permissions: {} + +jobs: + poll: + permissions: + contents: read + uses: ./.github/workflows/jira-poll-batch-check-poll.yml + with: + case: ${{ inputs.case }} + + dispatch: + needs: poll + if: ${{ needs.poll.outputs.matrix != '' && fromJSON(needs.poll.outputs.matrix).include[0] != null }} + permissions: + contents: read + uses: ./.github/workflows/jira-poll-batch-check-dispatch.yml + with: + matrix: ${{ needs.poll.outputs.matrix }} + digests: ${{ needs.poll.outputs.digests }} + + verify: + name: Verify the batch arrived whole + needs: [poll, dispatch] + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + actions: read + steps: + - name: Count the records that reached their own job + env: + GH_TOKEN: ${{ github.token }} + CASE: ${{ inputs.case }} + EXPECTED: ${{ needs.poll.outputs.count }} + UTF8_BYTES: ${{ needs.poll.outputs.utf8_bytes }} + UTF16_BYTES: ${{ needs.poll.outputs.utf16_bytes }} + DISPATCH_RESULT: ${{ needs.dispatch.result }} + run: | + set -euo pipefail + echo "Case ${CASE}: ${EXPECTED} records, ${UTF16_BYTES} bytes in UTF-16, ${UTF8_BYTES} bytes in UTF-8." + if [[ -z "${EXPECTED}" || "${EXPECTED}" -eq 0 ]]; then + echo "::error::the batch holds no records" + exit 1 + fi + if [[ "${DISPATCH_RESULT}" != "success" ]]; then + echo "::error::the dispatch job ended as '${DISPATCH_RESULT}': the batch did not arrive whole" + exit 1 + fi + arrived=$(gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs?per_page=100" \ + --jq '.jobs[] | select(.name | contains("/ Record ")) | select(.conclusion == "success") | .name' | wc -l) + if [[ "${arrived}" -ne "${EXPECTED}" ]]; then + echo "::error::${arrived} records reached their own job unchanged, want ${EXPECTED}" + exit 1 + fi + echo "All ${EXPECTED} records reached their own job unchanged." diff --git a/Makefile b/Makefile index 6e8d860500..b4b2dae8ac 100644 --- a/Makefile +++ b/Makefile @@ -195,6 +195,7 @@ script-test: $(call run-timed,bash scripts/run-with-infra-retry-test.sh) $(call run-timed,bash .github/scripts/check-fix-eligibility-test.sh) $(call run-timed,bash .github/scripts/count-fix-commits-test.sh) + $(call run-timed,bash .github/scripts/jira-poll-record-digest-test.sh) $(call run-timed,bash .github/scripts/pre-fetch-review-body-test.sh) $(call run-timed,bash .github/scripts/report-agent-startup-failure-test.sh) $(call run-timed,bash .github/scripts/retry-with-backoff-test.sh) diff --git a/docs/guides/dev/testing-workflows.md b/docs/guides/dev/testing-workflows.md index e815a766ae..b732d37a60 100644 --- a/docs/guides/dev/testing-workflows.md +++ b/docs/guides/dev/testing-workflows.md @@ -72,6 +72,53 @@ Push the change and trigger a fullsend action on the test repository: `/fs-triage`, `/fs-code`, or another agent command. Revert the references to the desired release or branch before deleting or rewriting the test ref. +## Jira poll batch check + +On GitHub, the managed Jira poll workflow passes a cycle's dispatch records +from the poll job to the dispatch job as one job output, and runs each record +as one job of a matrix. GitHub limits a job's outputs to 1 MB and a matrix to +256 jobs. A batch over either limit is lost whole, so the jira-poll driver +stops a cycle at 250 records and 768 KB (ADR 0085). + +The `Jira poll batch check` workflow +(`.github/workflows/jira-poll-batch-check.yml`) shows on GitHub that a batch +at those limits arrives whole. It runs one real poll cycle against a fake Jira +(`hack/prove-jira-poll-batch`), so the batch is as large as the driver allows, +and sends it along the same path as the managed workflow: a job output of a +reusable workflow, then an input of a second reusable workflow, then one +matrix job per record. Each matrix job compares the record it received with +the one the batch held, and a last job checks that every record got a job. No +agent runs, and the check needs no Jira site, secrets or mint. + +Run it once per case when a change touches the driver's limits, the dispatch +record format, or how `reusable-poll-jira.yml`, the managed caller or +`reusable-dispatch.yml` hand the matrix over: + +```bash +gh workflow run jira-poll-batch-check.yml -f case=records +``` + +| Case | Batch | +|------|-------| +| `records` | 250 records, the record limit, with comments as long as still fit in 768 KB | +| `size` | The largest plain-text records, up to 768 KB | +| `wide` | The largest records of three-byte characters, up to 768 KB | + +GitHub approximates output size from the UTF-16 encoding, and the driver +measures the same way. The `wide` batch is within 768 KB by that measure and +over 1 MB in UTF-8, so it passes only while GitHub counts as documented. + +A run passes when its `Verify the batch arrived whole` job passes. That job +prints the batch's record count and its size in both encodings. When the poll +job's output is over GitHub's limit, the output arrives empty, the dispatch +job is skipped and the verify job fails. + +The check covers the hand-off only. It does not run agents, so it says +nothing about runner capacity or about how long 250 agent runs take. + +`make script-test` fails when the hand-off in the real workflows no longer +matches the copy in the check (`.github/scripts/jira-poll-record-digest-test.sh`). + ## Running CI checks locally On macOS, or a Linux distribution other than Ubuntu, `ci-local` runs the PR diff --git a/hack/prove-jira-poll-batch/main.go b/hack/prove-jira-poll-batch/main.go new file mode 100644 index 0000000000..cc7990d1ae --- /dev/null +++ b/hack/prove-jira-poll-batch/main.go @@ -0,0 +1,203 @@ +// Command prove-jira-poll-batch writes the dispatch file a jira-poll cycle +// produces when a Jira project holds more work than one cycle may take, so +// the batch is as large as the driver's limits allow (ADR 0085, Decision +// items 3 and 4). The full-size batch check +// (.github/workflows/jira-poll-batch-check.yml) passes that file through the +// same hand-off as the managed poll workflow, on GitHub. +// +// The driver is the real one: a jirapoll.Poller reads a fake Jira over HTTP +// and each record is projected as the CLI projects it. Only the Jira content +// and the single agent every comment matches are made up. +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "io" + "log" + "os" + "sort" + "strings" + + "github.com/fullsend-ai/fullsend/internal/config" + "github.com/fullsend-ai/fullsend/internal/forge/jira" + "github.com/fullsend-ai/fullsend/internal/harnessdispatch" + "github.com/fullsend-ai/fullsend/internal/jirapoll" + "github.com/fullsend-ai/fullsend/internal/normevent" + "github.com/fullsend-ai/fullsend/pkg/behaviourtest/drivers/jiramock" +) + +const ( + // command starts every comment, so each one is an authorized request. + command = "/fs-triage " + // maxBody is the number of code points of a comment body the driver + // carries on the GitHub target. + maxBody = 4096 +) + +// batchCase describes the Jira content of one case. Every issue holds one +// comment of the command followed by filler. +type batchCase struct { + about string + issues int // more than a cycle can take + filler string // one code point, repeated after the command + // fillerLen is the number of filler code points, or -1 for the most that + // still lets a cycle take the record limit. + fillerLen int +} + +var cases = map[string]batchCase{ + "records": { + about: "250 records, the record limit, with comments as long as still fit in the size limit", + issues: 300, + filler: "a", + fillerLen: -1, + }, + "size": { + about: "the largest plain-text records, up to the size limit", + issues: 60, + filler: "a", + fillerLen: maxBody - len(command), + }, + "wide": { + about: "the largest records of three-byte characters, up to the size limit: the same size in UTF-16 as the size case and half as much again in UTF-8", + issues: 60, + filler: "語", + fillerLen: maxBody - len(command), + }, +} + +func main() { + os.Exit(run(os.Args[1:], os.Stdout, os.Stderr)) +} + +// run builds the batch the arguments name and returns the exit code. +func run(args []string, stdout, stderr io.Writer) int { + fs := flag.NewFlagSet("prove-jira-poll-batch", flag.ContinueOnError) + fs.SetOutput(stderr) + name := fs.String("case", "", "batch to build: "+strings.Join(caseNames(), ", ")) + out := fs.String("out", "dispatches.json", "path of the dispatch file to write") + targetRepo := fs.String("target-repo", "fullsend-ai/fullsend", "owner/repo the records name as their target") + if err := fs.Parse(args); err != nil { + return 2 + } + + // The poller logs every warning of a cycle; only the result matters here. + log.SetOutput(io.Discard) + + records, err := build(*name, *targetRepo, *out) + if err != nil { + fmt.Fprintln(stderr, "prove-jira-poll-batch:", err) + return 1 + } + fmt.Fprintf(stdout, "case %s: %d records in %s (%s)\n", *name, records, *out, cases[*name].about) + return 0 +} + +func caseNames() []string { + names := make([]string, 0, len(cases)) + for name := range cases { + names = append(names, name) + } + sort.Strings(names) + return names +} + +// build writes the dispatch file of the named case to out and returns the +// number of records in it. +func build(name, targetRepo, out string) (int, error) { + c, ok := cases[name] + if !ok { + return 0, fmt.Errorf("unknown case %q: want one of %s", name, strings.Join(caseNames(), ", ")) + } + if c.fillerLen >= 0 { + return runCycle(c, c.fillerLen, targetRepo, out) + } + + // Find the longest comment with which a cycle still takes the record + // limit: a longer one makes the size limit stop the cycle first. + limit := config.MaxJiraPollMaxDispatchesPerCycle + lo, hi := 0, maxBody-len(command) + for lo < hi { + mid := (lo + hi + 1) / 2 + records, err := runCycle(c, mid, targetRepo, out) + if err != nil { + return 0, err + } + if records >= limit { + lo = mid + } else { + hi = mid - 1 + } + } + return runCycle(c, lo, targetRepo, out) +} + +// runCycle fills a fake Jira with the case's issues, runs one poll cycle at +// the highest configurable record limit, and returns the number of records +// the cycle wrote to out. +func runCycle(c batchCase, fillerLen int, targetRepo, out string) (int, error) { + srv, state := jiramock.NewServer() + defer srv.Close() + + body := command + strings.Repeat(c.filler, fillerLen) + for i := 1; i <= c.issues; i++ { + key := fmt.Sprintf("PROJ-%d", i) + state.AddIssue(key, nil) + state.AddComment(key, body) + } + + client, err := jira.New("test-token", jira.WithBaseURL(srv.URL)) + if err != nil { + return 0, fmt.Errorf("create Jira client: %w", err) + } + poller := jirapoll.New(client, oneAgent{}, jirapoll.Options{ + TargetRepo: targetRepo, + // A fixed site name, so a record's size does not depend on the + // fake server's port. + JiraBaseURL: "https://example.atlassian.net", + JiraProject: "PROJ", + OutputPath: out, + MaxDispatchesPerCycle: config.MaxJiraPollMaxDispatchesPerCycle, + }) + if err := poller.Run(context.Background()); err != nil { + return 0, fmt.Errorf("poll cycle: %w", err) + } + + data, err := os.ReadFile(out) + if err != nil { + return 0, err + } + var records []json.RawMessage + if err := json.Unmarshal(data, &records); err != nil { + return 0, fmt.Errorf("read %s: %w", out, err) + } + return len(records), nil +} + +// oneAgent matches every authorized event to one agent and projects the +// record with harnessdispatch.ProjectExecutionRef, as the CLI's matcher does +// for each harness an event triggers. +type oneAgent struct{} + +func (oneAgent) Match(_ context.Context, event *normevent.Event) ([]jirapoll.DispatchRecord, error) { + if !harnessdispatch.IsAuthorized(event) { + return nil, nil + } + ref, err := harnessdispatch.ProjectExecutionRef("triage", "triage", event) + if err != nil { + return nil, err + } + return []jirapoll.DispatchRecord{{ + Agent: ref.Agent, + Role: ref.Role, + SourceRepo: ref.SourceRepo, + EventType: ref.EventType, + EventPayload: ref.EventPayload, + TriggerSource: ref.TriggerSource, + StatusRepo: ref.StatusRepo, + StatusNumber: ref.StatusNumber, + }}, nil +} diff --git a/hack/prove-jira-poll-batch/main_test.go b/hack/prove-jira-poll-batch/main_test.go new file mode 100644 index 0000000000..e61be2bc27 --- /dev/null +++ b/hack/prove-jira-poll-batch/main_test.go @@ -0,0 +1,90 @@ +package main + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "testing" + "unicode/utf16" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/fullsend-ai/fullsend/internal/config" +) + +// sizeLimit is the driver's limit on the matrix output of one cycle on the +// GitHub target: three quarters of GitHub's 1 MB limit on a job's outputs. +const sizeLimit = 768 * 1024 + +// matrix returns the poll job's matrix output for the dispatch file at path, +// as the managed workflow builds it with jq -c '{include: .}', and the number +// of records in it. +func matrix(t *testing.T, path string) (string, int) { + t.Helper() + data, err := os.ReadFile(path) + require.NoError(t, err) + var records []json.RawMessage + require.NoError(t, json.Unmarshal(data, &records)) + out, err := json.Marshal(map[string][]json.RawMessage{"include": records}) + require.NoError(t, err) + return string(out), len(records) +} + +// utf16Bytes is the size GitHub counts for a job output: it approximates +// output size from the UTF-16 encoding. +func utf16Bytes(s string) int { + return 2 * len(utf16.Encode([]rune(s))) +} + +// Every case is a batch the real driver stopped at one of its limits, with +// no room left for another record. +func TestRunFillsABatchToTheLimits(t *testing.T) { + for name, want := range map[string]struct { + records int + overOneM bool // larger than 1 MB in UTF-8 + }{ + "records": {records: config.MaxJiraPollMaxDispatchesPerCycle}, + "size": {records: 30}, + "wide": {records: 30, overOneM: true}, + } { + t.Run(name, func(t *testing.T) { + out := filepath.Join(t.TempDir(), "dispatches.json") + var stdout, stderr strings.Builder + require.Zero(t, run([]string{"-case", name, "-out", out}, &stdout, &stderr), stderr.String()) + + m, n := matrix(t, out) + assert.Equal(t, want.records, n) + assert.Contains(t, stdout.String(), fmt.Sprintf("case %s: %d records in ", name, n), "run reports the records it wrote") + + size := utf16Bytes(m) + assert.LessOrEqual(t, size, sizeLimit, "the driver keeps the batch within its size limit") + // One more record of the average size would not fit, so the batch + // is at the size limit as well as, for the records case, at the + // record limit. + assert.Greater(t, size+size/n, sizeLimit, "the batch has no room for another record") + + if want.overOneM { + assert.Greater(t, len(m), 1<<20, "the wide batch is over 1 MB in UTF-8 while within the limit in UTF-16") + } else { + assert.Less(t, len(m), 1<<20) + } + }) + } +} + +func TestRunRejectsAnUnknownCaseOrFlag(t *testing.T) { + out := filepath.Join(t.TempDir(), "dispatches.json") + + var stderr strings.Builder + assert.Equal(t, 1, run([]string{"-case", "huge", "-out", out}, io.Discard, &stderr)) + assert.Contains(t, stderr.String(), `unknown case "huge": want one of records, size, wide`) + assert.NoFileExists(t, out) + + stderr.Reset() + assert.Equal(t, 2, run([]string{"-cases", "size"}, io.Discard, &stderr)) + assert.Contains(t, stderr.String(), "flag provided but not defined: -cases") +} From 1d5efef3871541976d6685dfb9acf16a4a80b6d9 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 07:24:34 +0200 Subject: [PATCH 28/60] ci(jira-poll): size the batch check by what GitHub counts The first runs of the check on GitHub passed for the 250-record and plain-text batches and failed for the batch of three-byte characters: it was within the driver's 768 KB limit, and GitHub failed the poll job with "Job outputs exceed 1,048,576 bytes". The driver now counts as GitHub does, two bytes for each byte of UTF-8, so that batch holds 10 of the largest records where it held 30. Report the batch's size in bytes of UTF-8 and as GitHub counts it, in place of the UTF-16 size, and say in the guide what the check found. Signed-off-by: guy oron --- .../workflows/jira-poll-batch-check-poll.yml | 15 +++------ .github/workflows/jira-poll-batch-check.yml | 5 ++- docs/guides/dev/testing-workflows.md | 15 +++++---- hack/prove-jira-poll-batch/main.go | 2 +- hack/prove-jira-poll-batch/main_test.go | 32 +++++++------------ 5 files changed, 29 insertions(+), 40 deletions(-) diff --git a/.github/workflows/jira-poll-batch-check-poll.yml b/.github/workflows/jira-poll-batch-check-poll.yml index bf0832b4b7..03cccfd898 100644 --- a/.github/workflows/jira-poll-batch-check-poll.yml +++ b/.github/workflows/jira-poll-batch-check-poll.yml @@ -27,12 +27,9 @@ on: digests: description: JSON array with the digest of every record (jira-poll-record-digest.sh). value: ${{ jobs.batch.outputs.digests }} - utf8_bytes: - description: Size of the matrix in UTF-8. - value: ${{ jobs.batch.outputs.utf8_bytes }} - utf16_bytes: - description: Size of the matrix in UTF-16, which is how GitHub approximates output size. - value: ${{ jobs.batch.outputs.utf16_bytes }} + bytes: + description: Size of the matrix in bytes of UTF-8. GitHub counts each one as two. + value: ${{ jobs.batch.outputs.bytes }} jobs: batch: @@ -44,8 +41,7 @@ jobs: outputs: count: ${{ steps.describe.outputs.count }} digests: ${{ steps.describe.outputs.digests }} - utf8_bytes: ${{ steps.describe.outputs.utf8_bytes }} - utf16_bytes: ${{ steps.describe.outputs.utf16_bytes }} + bytes: ${{ steps.describe.outputs.bytes }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -73,8 +69,7 @@ jobs: { echo "count=$(jq 'length' dispatches.json)" echo "digests=${digests}" - echo "utf8_bytes=$(printf '%s' "${matrix}" | wc -c)" - echo "utf16_bytes=$(printf '%s' "${matrix}" | iconv -f UTF-8 -t UTF-16LE | wc -c)" + echo "bytes=$(printf '%s' "${matrix}" | wc -c)" } >> "${GITHUB_OUTPUT}" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/.github/workflows/jira-poll-batch-check.yml b/.github/workflows/jira-poll-batch-check.yml index 620b8b0d98..9f06a45237 100644 --- a/.github/workflows/jira-poll-batch-check.yml +++ b/.github/workflows/jira-poll-batch-check.yml @@ -67,12 +67,11 @@ jobs: GH_TOKEN: ${{ github.token }} CASE: ${{ inputs.case }} EXPECTED: ${{ needs.poll.outputs.count }} - UTF8_BYTES: ${{ needs.poll.outputs.utf8_bytes }} - UTF16_BYTES: ${{ needs.poll.outputs.utf16_bytes }} + BYTES: ${{ needs.poll.outputs.bytes }} DISPATCH_RESULT: ${{ needs.dispatch.result }} run: | set -euo pipefail - echo "Case ${CASE}: ${EXPECTED} records, ${UTF16_BYTES} bytes in UTF-16, ${UTF8_BYTES} bytes in UTF-8." + echo "Case ${CASE}: ${EXPECTED} records in ${BYTES} bytes of UTF-8, which GitHub counts as $((2 * BYTES)) of the 1048576 a job's outputs may hold." if [[ -z "${EXPECTED}" || "${EXPECTED}" -eq 0 ]]; then echo "::error::the batch holds no records" exit 1 diff --git a/docs/guides/dev/testing-workflows.md b/docs/guides/dev/testing-workflows.md index b732d37a60..f05dbcb23c 100644 --- a/docs/guides/dev/testing-workflows.md +++ b/docs/guides/dev/testing-workflows.md @@ -104,14 +104,17 @@ gh workflow run jira-poll-batch-check.yml -f case=records | `size` | The largest plain-text records, up to 768 KB | | `wide` | The largest records of three-byte characters, up to 768 KB | -GitHub approximates output size from the UTF-16 encoding, and the driver -measures the same way. The `wide` batch is within 768 KB by that measure and -over 1 MB in UTF-8, so it passes only while GitHub counts as documented. +GitHub counts two bytes for each byte of an output's UTF-8 text, so a batch +at the 768 KB limit is about 384 KB of JSON. Its documentation says only that +the size is "approximated based on UTF-16 encoding". The `wide` case holds the +difference: a count of two bytes per UTF-16 code unit puts three times as many +of its records in a batch, and GitHub rejects that batch with +`Job outputs exceed 1,048,576 bytes`. A run passes when its `Verify the batch arrived whole` job passes. That job -prints the batch's record count and its size in both encodings. When the poll -job's output is over GitHub's limit, the output arrives empty, the dispatch -job is skipped and the verify job fails. +prints the batch's record count and size. When the poll job's output is over +GitHub's limit, GitHub fails the poll job, the dispatch job is skipped and +the verify job fails. The check covers the hand-off only. It does not run agents, so it says nothing about runner capacity or about how long 250 agent runs take. diff --git a/hack/prove-jira-poll-batch/main.go b/hack/prove-jira-poll-batch/main.go index cc7990d1ae..eab279e295 100644 --- a/hack/prove-jira-poll-batch/main.go +++ b/hack/prove-jira-poll-batch/main.go @@ -62,7 +62,7 @@ var cases = map[string]batchCase{ fillerLen: maxBody - len(command), }, "wide": { - about: "the largest records of three-byte characters, up to the size limit: the same size in UTF-16 as the size case and half as much again in UTF-8", + about: "the largest records of three-byte characters, up to the size limit", issues: 60, filler: "語", fillerLen: maxBody - len(command), diff --git a/hack/prove-jira-poll-batch/main_test.go b/hack/prove-jira-poll-batch/main_test.go index e61be2bc27..2319020d05 100644 --- a/hack/prove-jira-poll-batch/main_test.go +++ b/hack/prove-jira-poll-batch/main_test.go @@ -8,7 +8,6 @@ import ( "path/filepath" "strings" "testing" - "unicode/utf16" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -34,22 +33,21 @@ func matrix(t *testing.T, path string) (string, int) { return string(out), len(records) } -// utf16Bytes is the size GitHub counts for a job output: it approximates -// output size from the UTF-16 encoding. -func utf16Bytes(s string) int { - return 2 * len(utf16.Encode([]rune(s))) +// counted is the size GitHub counts for a job output: two bytes for each +// byte of its UTF-8 text. +func counted(s string) int { + return 2 * len(s) } // Every case is a batch the real driver stopped at one of its limits, with // no room left for another record. func TestRunFillsABatchToTheLimits(t *testing.T) { - for name, want := range map[string]struct { - records int - overOneM bool // larger than 1 MB in UTF-8 - }{ - "records": {records: config.MaxJiraPollMaxDispatchesPerCycle}, - "size": {records: 30}, - "wide": {records: 30, overOneM: true}, + for name, wantRecords := range map[string]int{ + "records": config.MaxJiraPollMaxDispatchesPerCycle, + "size": 30, + // A three-byte character counts three times an ASCII one, so a + // third as many of the largest records fit. + "wide": 10, } { t.Run(name, func(t *testing.T) { out := filepath.Join(t.TempDir(), "dispatches.json") @@ -57,21 +55,15 @@ func TestRunFillsABatchToTheLimits(t *testing.T) { require.Zero(t, run([]string{"-case", name, "-out", out}, &stdout, &stderr), stderr.String()) m, n := matrix(t, out) - assert.Equal(t, want.records, n) + assert.Equal(t, wantRecords, n) assert.Contains(t, stdout.String(), fmt.Sprintf("case %s: %d records in ", name, n), "run reports the records it wrote") - size := utf16Bytes(m) + size := counted(m) assert.LessOrEqual(t, size, sizeLimit, "the driver keeps the batch within its size limit") // One more record of the average size would not fit, so the batch // is at the size limit as well as, for the records case, at the // record limit. assert.Greater(t, size+size/n, sizeLimit, "the batch has no room for another record") - - if want.overOneM { - assert.Greater(t, len(m), 1<<20, "the wide batch is over 1 MB in UTF-8 while within the limit in UTF-16") - } else { - assert.Less(t, len(m), 1<<20) - } }) } } From e531a508ddd2670aee858f56abe9792fc6054210 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 07:28:49 +0200 Subject: [PATCH 29/60] ci(jira-poll): follow the poll workflow's matrix job in the batch check The real poll workflow now builds the matrix in a job of its own, which reads the dispatch file from an artifact of the poll job. Give the stand-in that job word for word, save the batch under the same artifact name, and compare the whole job in the contract test. The poller takes its projects as a list. Signed-off-by: guy oron --- .../scripts/jira-poll-record-digest-test.sh | 32 +++---- .../workflows/jira-poll-batch-check-poll.yml | 85 +++++++++++-------- docs/guides/dev/testing-workflows.md | 7 +- hack/prove-jira-poll-batch/main.go | 2 +- 4 files changed, 66 insertions(+), 60 deletions(-) diff --git a/.github/scripts/jira-poll-record-digest-test.sh b/.github/scripts/jira-poll-record-digest-test.sh index ceb4825e45..31ccaa9ab1 100755 --- a/.github/scripts/jira-poll-record-digest-test.sh +++ b/.github/scripts/jira-poll-record-digest-test.sh @@ -46,28 +46,20 @@ if digest '{"agent":' >/dev/null 2>&1; then fail "input that is not JSON produced a digest" fi -# The poll stand-in builds the matrix output with the real workflow's step. -matrix_step() { - awk ' - /^ - name: Build dispatch matrix$/ { on = 1 } - on && seen && /^ - / { exit } - on { - seen = 1 - if ($0 ~ /^[[:space:]]*$/) { blank = blank $0 "\n"; next } - printf "%s%s\n", blank, $0 - blank = "" - } - ' "$1" -} -real_step="$(matrix_step "${WORKFLOWS}/reusable-poll-jira.yml")" -[[ -n "${real_step}" ]] || fail "reusable-poll-jira.yml has no Build dispatch matrix step" -[[ "$(matrix_step "${WORKFLOWS}/jira-poll-batch-check-poll.yml")" == "${real_step}" ]] || - fail "the Build dispatch matrix step of jira-poll-batch-check-poll.yml differs from reusable-poll-jira.yml" +# The poll stand-in builds the matrix output in the real workflow's matrix +# job, which differs only in taking its runner and timeout from inputs. +matrix_job() { awk '/^ matrix:$/ { on = 1 } on && !/^ (runs-on|timeout-minutes): /' "$1"; } +real_job="$(matrix_job "${WORKFLOWS}/reusable-poll-jira.yml")" +[[ -n "${real_job}" ]] || fail "reusable-poll-jira.yml has no matrix job" +[[ "$(matrix_job "${WORKFLOWS}/jira-poll-batch-check-poll.yml")" == "${real_job}" ]] || + fail "the matrix job of jira-poll-batch-check-poll.yml differs from reusable-poll-jira.yml" -# Both return the matrix as the poll job's output. +# Both return that job's output, and feed the job from the poll job's +# artifact under the same name. for workflow in reusable-poll-jira.yml jira-poll-batch-check-poll.yml; do - contains "${WORKFLOWS}/${workflow}" 'value: ${{ jobs.poll.outputs.matrix }}' - contains "${WORKFLOWS}/${workflow}" 'matrix: ${{ steps.matrix.outputs.matrix }}' + contains "${WORKFLOWS}/${workflow}" "value: \${{ jobs.matrix.outputs.matrix || '{\"include\":[]}' }}" + contains "${WORKFLOWS}/${workflow}" 'dispatch_count: ${{ steps.check.outputs.count }}' + contains "${WORKFLOWS}/${workflow}" 'name: fullsend-jira-dispatches-${{ steps.check.outputs.artifact_suffix }}' done # The caller hands the matrix on under the managed caller's condition. diff --git a/.github/workflows/jira-poll-batch-check-poll.yml b/.github/workflows/jira-poll-batch-check-poll.yml index 03cccfd898..d315308256 100644 --- a/.github/workflows/jira-poll-batch-check-poll.yml +++ b/.github/workflows/jira-poll-batch-check-poll.yml @@ -1,13 +1,14 @@ # Poll side of the Jira poll batch check (jira-poll-batch-check.yml). # -# Stands in for reusable-poll-jira.yml. The poll job has that workflow's -# "Build dispatch matrix" step word for word and returns the matrix the same -# way: a step output, then the job's only output, then this workflow's output. -# What differs is where dispatches.json comes from: the batch job builds it -# with the real driver reading a fake Jira (hack/prove-jira-poll-batch). +# Stands in for reusable-poll-jira.yml. The matrix job is that workflow's +# matrix job word for word, and the matrix is returned the same way: a step +# output, then that job's only output, then this workflow's output. What +# differs is the poll job, which builds dispatches.json with the real driver +# reading a fake Jira (hack/prove-jira-poll-batch) and saves it under the +# artifact name the real poll job uses. # -# The record count, the digests and the sizes are outputs of the batch job, -# not of the poll job, so they still arrive when GitHub drops the matrix. +# The record count, the digests and the size are outputs of the poll job, not +# of the matrix job, so they still arrive when GitHub rejects the matrix. name: Jira poll batch check (poll) on: @@ -20,28 +21,29 @@ on: outputs: matrix: description: Dispatch matrix, returned as reusable-poll-jira.yml returns it. - value: ${{ jobs.poll.outputs.matrix }} + value: ${{ jobs.matrix.outputs.matrix || '{"include":[]}' }} count: description: Number of records in the batch. - value: ${{ jobs.batch.outputs.count }} + value: ${{ jobs.poll.outputs.dispatch_count }} digests: description: JSON array with the digest of every record (jira-poll-record-digest.sh). - value: ${{ jobs.batch.outputs.digests }} + value: ${{ jobs.poll.outputs.digests }} bytes: description: Size of the matrix in bytes of UTF-8. GitHub counts each one as two. - value: ${{ jobs.batch.outputs.bytes }} + value: ${{ jobs.poll.outputs.bytes }} jobs: - batch: - name: Build the batch + poll: + name: Poll a fake Jira runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: contents: read outputs: - count: ${{ steps.describe.outputs.count }} - digests: ${{ steps.describe.outputs.digests }} - bytes: ${{ steps.describe.outputs.bytes }} + dispatch_count: ${{ steps.check.outputs.count }} + artifact_suffix: ${{ steps.check.outputs.artifact_suffix }} + digests: ${{ steps.check.outputs.digests }} + bytes: ${{ steps.check.outputs.bytes }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -58,8 +60,8 @@ jobs: TARGET_REPO: ${{ github.repository }} run: go run ./hack/prove-jira-poll-batch -case "${CASE}" -target-repo "${TARGET_REPO}" -out dispatches.json - - name: Describe the batch - id: describe + - name: Check dispatches + id: check run: | set -euo pipefail matrix=$(jq -c '{include: .}' dispatches.json) @@ -67,41 +69,52 @@ jobs: printf '%s' "${record}" | .github/scripts/jira-poll-record-digest.sh done | jq -Rcs 'split("\n") | map(select(. != ""))') { - echo "count=$(jq 'length' dispatches.json)" + echo "artifact_suffix=$(openssl rand -hex 8)" + echo "count=$(jq length dispatches.json)" echo "digests=${digests}" echo "bytes=$(printf '%s' "${matrix}" | wc -c)" } >> "${GITHUB_OUTPUT}" - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + - name: Save dispatches + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: dispatches + name: fullsend-jira-dispatches-${{ steps.check.outputs.artifact_suffix }} path: dispatches.json - retention-days: 7 + if-no-files-found: error + retention-days: 1 - poll: - name: Poll Jira - needs: batch + matrix: + name: Build dispatch matrix + needs: poll + # "!= '0'", not "> 0": an empty (dropped) count still runs this job. + if: ${{ needs.poll.outputs.dispatch_count != '0' }} runs-on: ubuntu-24.04 - timeout-minutes: 5 - permissions: - contents: read + timeout-minutes: 15 + permissions: {} outputs: matrix: ${{ steps.matrix.outputs.matrix }} steps: - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + # If both tries fail, "Re-run failed jobs" reads the artifact again + # while it is kept (1 day). "Re-run all jobs" would poll again and find + # nothing. + - name: Read dispatches + id: read + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: fullsend-jira-dispatches-${{ needs.poll.outputs.artifact_suffix }} + + - name: Read dispatches (second try) + if: ${{ steps.read.outcome == 'failure' }} + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - name: dispatches + name: fullsend-jira-dispatches-${{ needs.poll.outputs.artifact_suffix }} - name: Build dispatch matrix id: matrix run: | set -euo pipefail - jq -e 'type == "array"' dispatches.json > /dev/null - if jq -e 'length == 0' dispatches.json > /dev/null; then - echo "No dispatches." - echo 'matrix={"include":[]}' >> "${GITHUB_OUTPUT}" - exit 0 - fi + jq -e 'type == "array" and length > 0' dispatches.json > /dev/null MATRIX=$(jq -c '{include: .}' dispatches.json) DELIM="MATRIX_$(openssl rand -hex 8)" { diff --git a/docs/guides/dev/testing-workflows.md b/docs/guides/dev/testing-workflows.md index f05dbcb23c..b87937195e 100644 --- a/docs/guides/dev/testing-workflows.md +++ b/docs/guides/dev/testing-workflows.md @@ -84,9 +84,10 @@ The `Jira poll batch check` workflow (`.github/workflows/jira-poll-batch-check.yml`) shows on GitHub that a batch at those limits arrives whole. It runs one real poll cycle against a fake Jira (`hack/prove-jira-poll-batch`), so the batch is as large as the driver allows, -and sends it along the same path as the managed workflow: a job output of a -reusable workflow, then an input of a second reusable workflow, then one -matrix job per record. Each matrix job compares the record it received with +and sends it along the same path as the managed workflow: an artifact from +the poll job to the matrix job, that job's output returned by a reusable +workflow, then an input of a second reusable workflow, then one matrix job +per record. Each matrix job compares the record it received with the one the batch held, and a last job checks that every record got a job. No agent runs, and the check needs no Jira site, secrets or mint. diff --git a/hack/prove-jira-poll-batch/main.go b/hack/prove-jira-poll-batch/main.go index eab279e295..7928b0f530 100644 --- a/hack/prove-jira-poll-batch/main.go +++ b/hack/prove-jira-poll-batch/main.go @@ -158,7 +158,7 @@ func runCycle(c batchCase, fillerLen int, targetRepo, out string) (int, error) { // A fixed site name, so a record's size does not depend on the // fake server's port. JiraBaseURL: "https://example.atlassian.net", - JiraProject: "PROJ", + JiraProjects: []string{"PROJ"}, OutputPath: out, MaxDispatchesPerCycle: config.MaxJiraPollMaxDispatchesPerCycle, }) From 1c62fe178dd5848455588a6f4bd26be9b98d5b92 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 08:06:36 +0200 Subject: [PATCH 30/60] docs(jira-poll): say what changes when an adopter upgrades the poller The poller's selection, search, lock and limits change in one release (ADR 0085), and three of the commits are breaking. The guide described the new behaviour but not the step from the old one. Add "Upgrading the Jira poller" to the Jira guide: a before-and-after table, what to do before the upgrade (a scheduler other than the managed ones must run one cycle at a time; the new setting waits until after the upgrade), and what to expect after it (more agent runs per cycle, the ORDER BY updated DESC warning, changed log lines, the lock and write-check properties, and what a long stop no longer logs). Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 65 ++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 33e0505354..02304f7074 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1446,6 +1446,71 @@ entry's default `labels: jira_editors`, anyone with Edit Issues on the project c add a label such as `ready-to-code` and dispatch the agent whose trigger matches it. Use `labels: allowlist` if that group is broader than you want. +## Upgrading the Jira poller + +Fullsend v0.58.0 changes which issues the poller serves in a cycle and how +two cycles are kept apart (ADR 0085). It affects every repository that polls +Jira, on GitHub and on GitLab. The Jira credential and the permissions the +poller needs do not change. + +| | Before v0.58.0 | From v0.58.0 | +|---|---|---| +| Issues served in a cycle | Five, picked at random from the first 50 the query returned | Every issue with new activity, in the query's order, until the cycle holds 100 dispatch records | +| What the search covers | The first 50 issues of the query, newest change first by default | Every issue that matches the query and changed within the last 24 hours, oldest change first by default | +| Default `poll.query` | `statusCategory != Done ORDER BY updated DESC` | `statusCategory != Done` | +| Two cycles at the same time | Kept apart by a lock on each issue | Not kept apart: the scheduler runs one cycle at a time | +| Time a cycle may take | Limited only by the job's timeout | Reading stops after five minutes, and after two minutes on one issue; what is left waits for the next cycle | +| Dispatch records from one issue | No limit beyond 100 events per look | Also at most 250 records and, on GitHub, 768 KB; the oldest are kept | + +A repository on the managed poll workflow or the managed GitLab schedule +needs no change before the upgrade: both already run one cycle at a time. + +**Before you upgrade:** + +- **Your own scheduler.** If anything other than the managed workflow or the + managed GitLab schedule runs `fullsend poll --input-driver jira-poll`, make + sure it never runs two cycles for one repository at the same time, and that + only one workflow or job polls a repository. On GitHub Actions, give the + poll job a concurrency group with `cancel-in-progress: false`, as the + [custom poller example](custom-poller-example.md) does. The workflow that + earlier versions of this guide had you copy has one. Without the lock, + overlapping cycles dispatch the same requests twice. +- **The new setting.** Leave `tracker.jira.poll.max_dispatches_per_cycle` out + of the configuration until the upgrade is in place. A fullsend older than + v0.58.0 rejects a configuration that sets it, and stops polling. For the + same reason, remove the setting before you go back to an older version. + +**After you upgrade:** + +- **More agent runs per cycle.** A cycle starts up to 100 agent runs where it + used to read five issues, and more than 100 when a single issue produces + more. The first cycles also serve the requests from the last 24 hours + that were still waiting to be picked. To start fewer runs per cycle, set + `tracker.jira.poll.max_dispatches_per_cycle` to a lower number, from 1 to + 250. Requests then wait longer, and one that waits more than 24 hours is + lost. +- **`ORDER BY updated DESC`.** If `poll.query` ends in that clause, remove it. + The query still runs, and the poller logs a WARNING every cycle: when a + cycle cannot serve every issue, newest change first leaves the older + requests waiting until they leave the 24-hour window. See + [Custom JQL](#custom-jql). +- **Log lines.** If you search the run logs for the poller's lines, the + summary now reads + `poll complete: candidates, active, served, dispatches`, + where it reported `unlocked` and `selected`. A cycle in which every issue + failed ends with `all active issues failed to process`, where it said + `selected`. +- **Issue properties.** The poller no longer reads or removes a lock + property that an earlier version left on an issue + (`fullsend.poll.{owner}.{repo}.lock`, or its `fullsend.poll.gitlab.*` + counterpart). Delete it or leave it. The poller writes a new property, + `writeCheck`, beside `lastCheck` on each issue it reads. +- **After a long stop.** Requests more than 24 hours old were already lost + when polling stopped for that long. They now leave no WARNING in the run + log unless the issue changed again within the last 24 hours. + +[Poll coordination](#poll-coordination) describes each of these in full. + ## 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 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 serves the rest in the search's order, oldest change first by default, until the cycle is full (see **Per-cycle limit** below). 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, not a timestamp, or in the future) or no usable `updated` time counts as new. Two properties are stored on each processed issue: From f9b935c60b4d0d4d100621f96bc797525689ada2 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 08:06:36 +0200 Subject: [PATCH 31/60] docs(jira-poll): say what changes when an adopter upgrades the poller The poller's selection, search, lock and limits change in one release (ADR 0085), and three of the commits are breaking. The guide described the new behaviour but not the step from the old one. Add "Upgrading the Jira poller" to the Jira guide: a before-and-after table, what to do before the upgrade (a scheduler other than the managed ones must run one cycle at a time; the new setting waits until after the upgrade), and what to expect after it (more agent runs per cycle, the ORDER BY updated DESC warning, changed log lines, the lock and write-check properties, and what a long stop no longer logs). Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 65 ++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 3433d94a16..6179ee73c6 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1637,6 +1637,71 @@ entry's default `labels: jira_editors`, anyone with Edit Issues on the project c add a label such as `ready-to-code` and dispatch the agent whose trigger matches it. Use `labels: allowlist` if that group is broader than you want. +## Upgrading the Jira poller + +Fullsend v0.58.0 changes which issues the poller serves in a cycle and how +two cycles are kept apart (ADR 0085). It affects every repository that polls +Jira, on GitHub and on GitLab. The Jira credential and the permissions the +poller needs do not change. + +| | Before v0.58.0 | From v0.58.0 | +|---|---|---| +| Issues served in a cycle | Five, picked at random from the first 50 the query returned | Every issue with new activity, in the query's order, until the cycle holds 100 dispatch records | +| What the search covers | The first 50 issues of the query, newest change first by default | Every issue that matches the query and changed within the last 24 hours, oldest change first by default | +| Default `poll.query` | `statusCategory != Done ORDER BY updated DESC` | `statusCategory != Done` | +| Two cycles at the same time | Kept apart by a lock on each issue | Not kept apart: the scheduler runs one cycle at a time | +| Time a cycle may take | Limited only by the job's timeout | Reading stops after five minutes, and after two minutes on one issue; what is left waits for the next cycle | +| Dispatch records from one issue | No limit beyond 100 events per look | Also at most 250 records and, on GitHub, 768 KB; the oldest are kept | + +A repository on the managed poll workflow or the managed GitLab schedule +needs no change before the upgrade: both already run one cycle at a time. + +**Before you upgrade:** + +- **Your own scheduler.** If anything other than the managed workflow or the + managed GitLab schedule runs `fullsend poll --input-driver jira-poll`, make + sure it never runs two cycles for one repository at the same time, and that + only one workflow or job polls a repository. On GitHub Actions, give the + poll job a concurrency group with `cancel-in-progress: false`, as the + [custom poller example](custom-poller-example.md) does. The workflow that + earlier versions of this guide had you copy has one. Without the lock, + overlapping cycles dispatch the same requests twice. +- **The new setting.** Leave `tracker.jira.poll.max_dispatches_per_cycle` out + of the configuration until the upgrade is in place. A fullsend older than + v0.58.0 rejects a configuration that sets it, and stops polling. For the + same reason, remove the setting before you go back to an older version. + +**After you upgrade:** + +- **More agent runs per cycle.** A cycle starts up to 100 agent runs where it + used to read five issues, and more than 100 when a single issue produces + more. The first cycles also serve the requests from the last 24 hours + that were still waiting to be picked. To start fewer runs per cycle, set + `tracker.jira.poll.max_dispatches_per_cycle` to a lower number, from 1 to + 250. Requests then wait longer, and one that waits more than 24 hours is + lost. +- **`ORDER BY updated DESC`.** If `poll.query` ends in that clause, remove it. + The query still runs, and the poller logs a WARNING every cycle: when a + cycle cannot serve every issue, newest change first leaves the older + requests waiting until they leave the 24-hour window. See + [Custom JQL](#custom-jql). +- **Log lines.** If you search the run logs for the poller's lines, the + summary now reads + `poll complete: candidates, active, served, dispatches`, + where it reported `unlocked` and `selected`. A cycle in which every issue + failed ends with `all active issues failed to process`, where it said + `selected`. +- **Issue properties.** The poller no longer reads or removes a lock + property that an earlier version left on an issue + (`fullsend.poll.{owner}.{repo}.lock`, or its `fullsend.poll.gitlab.*` + counterpart). Delete it or leave it. The poller writes a new property, + `writeCheck`, beside `lastCheck` on each issue it reads. +- **After a long stop.** Requests more than 24 hours old were already lost + when polling stopped for that long. They now leave no WARNING in the run + log unless the issue changed again within the last 24 hours. + +[Poll coordination](#poll-coordination) describes each of these in full. + ## 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 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 serves the rest in the search's order, oldest change first by default, until the cycle is full (see **Per-cycle limit** below). 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, not a timestamp, or in the future) or no usable `updated` time counts as new. Two properties are stored on each processed issue: From f96a41893b59b192f74da5e61daf1df9facacb16 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 09:26:51 +0200 Subject: [PATCH 32/60] docs(jira-poll): say the driver keeps a cycle to at most 250 records The batch check's guide section and its workflow header said the driver stops a cycle at 250 records. 250 is the most a cycle can be set to hold; the default is 100. Signed-off-by: guy oron --- .github/workflows/jira-poll-batch-check.yml | 4 ++-- docs/guides/dev/testing-workflows.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/jira-poll-batch-check.yml b/.github/workflows/jira-poll-batch-check.yml index 9f06a45237..6354d54c46 100644 --- a/.github/workflows/jira-poll-batch-check.yml +++ b/.github/workflows/jira-poll-batch-check.yml @@ -4,8 +4,8 @@ # the dispatch job as one job output, and runs each record as one job of a # matrix. GitHub limits a job's outputs to 1 MB and a matrix to 256 jobs, and # a batch over either limit is lost whole. The jira-poll driver therefore -# stops a cycle at 250 records and 768 KB. This workflow shows, on GitHub, -# that a batch at those limits arrives whole. +# keeps a cycle to at most 250 records and 768 KB. This workflow shows, on +# GitHub, that a batch at those limits arrives whole. # # It has the shape of the managed caller # (internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml): a poll diff --git a/docs/guides/dev/testing-workflows.md b/docs/guides/dev/testing-workflows.md index f05dbcb23c..b7c13f0581 100644 --- a/docs/guides/dev/testing-workflows.md +++ b/docs/guides/dev/testing-workflows.md @@ -78,7 +78,7 @@ On GitHub, the managed Jira poll workflow passes a cycle's dispatch records from the poll job to the dispatch job as one job output, and runs each record as one job of a matrix. GitHub limits a job's outputs to 1 MB and a matrix to 256 jobs. A batch over either limit is lost whole, so the jira-poll driver -stops a cycle at 250 records and 768 KB (ADR 0085). +keeps a cycle to at most 250 records and 768 KB (ADR 0085). The `Jira poll batch check` workflow (`.github/workflows/jira-poll-batch-check.yml`) shows on GitHub that a batch From fbcf0829c22e83502063a0b00db3d38ba6d34888 Mon Sep 17 00:00:00 2001 From: guy oron Date: Sat, 28 Nov 2026 09:26:51 +0200 Subject: [PATCH 33/60] docs(jira-poll): say the driver keeps a cycle to at most 250 records The batch check's guide section and its workflow header said the driver stops a cycle at 250 records. 250 is the most a cycle can be set to hold; the default is 100. Signed-off-by: guy oron --- .github/workflows/jira-poll-batch-check.yml | 4 ++-- docs/guides/dev/testing-workflows.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/jira-poll-batch-check.yml b/.github/workflows/jira-poll-batch-check.yml index 9f06a45237..6354d54c46 100644 --- a/.github/workflows/jira-poll-batch-check.yml +++ b/.github/workflows/jira-poll-batch-check.yml @@ -4,8 +4,8 @@ # the dispatch job as one job output, and runs each record as one job of a # matrix. GitHub limits a job's outputs to 1 MB and a matrix to 256 jobs, and # a batch over either limit is lost whole. The jira-poll driver therefore -# stops a cycle at 250 records and 768 KB. This workflow shows, on GitHub, -# that a batch at those limits arrives whole. +# keeps a cycle to at most 250 records and 768 KB. This workflow shows, on +# GitHub, that a batch at those limits arrives whole. # # It has the shape of the managed caller # (internal/scaffold/fullsend-repo/templates/jira-poll-per-repo.yaml): a poll diff --git a/docs/guides/dev/testing-workflows.md b/docs/guides/dev/testing-workflows.md index b87937195e..82e47894b2 100644 --- a/docs/guides/dev/testing-workflows.md +++ b/docs/guides/dev/testing-workflows.md @@ -78,7 +78,7 @@ On GitHub, the managed Jira poll workflow passes a cycle's dispatch records from the poll job to the dispatch job as one job output, and runs each record as one job of a matrix. GitHub limits a job's outputs to 1 MB and a matrix to 256 jobs. A batch over either limit is lost whole, so the jira-poll driver -stops a cycle at 250 records and 768 KB (ADR 0085). +keeps a cycle to at most 250 records and 768 KB (ADR 0085). The `Jira poll batch check` workflow (`.github/workflows/jira-poll-batch-check.yml`) shows on GitHub that a batch From 0a619f0f27eb30a9f650901530f0b822f80f3e9d Mon Sep 17 00:00:00 2001 From: guy oron Date: Mon, 30 Nov 2026 12:54:38 +0200 Subject: [PATCH 34/60] 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 6d040b0c3eaad1ee58b45c68eec03594da387d53 Mon Sep 17 00:00:00 2001 From: guy oron Date: Mon, 30 Nov 2026 12:58:40 +0200 Subject: [PATCH 35/60] ci(jira-poll): give the batch check's matrix job no token permissions Review follow-up. The stand-in poll job only downloads an artifact of its own run and builds the matrix with jq, so it does not need to read the repository. The matrix job of reusable-poll-jira.yml on main runs the same download with no permissions. Signed-off-by: guy oron --- .github/workflows/jira-poll-batch-check-poll.yml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/workflows/jira-poll-batch-check-poll.yml b/.github/workflows/jira-poll-batch-check-poll.yml index 03cccfd898..4c28fb9ca8 100644 --- a/.github/workflows/jira-poll-batch-check-poll.yml +++ b/.github/workflows/jira-poll-batch-check-poll.yml @@ -83,8 +83,7 @@ jobs: needs: batch runs-on: ubuntu-24.04 timeout-minutes: 5 - permissions: - contents: read + permissions: {} outputs: matrix: ${{ steps.matrix.outputs.matrix }} steps: From 7b311fafa1e9d46de9df5a06239eac0abe923ae1 Mon Sep 17 00:00:00 2001 From: guy oron Date: Mon, 30 Nov 2026 13:02:24 +0200 Subject: [PATCH 36/60] docs(jira-poll): describe the poller of ADR 0085 as built The architecture document called the lock removal and the candidate selection of ADR 0085 target state, and one row of the entity execution scope table still listed lock properties. Both now describe what the driver does. The backfill window stays at 24 hours: the setting tracker.jira.poll.backfill_window_hours is not built, so the architecture document keeps it as target state. Signed-off-by: guy oron --- docs/architecture.md | 15 ++++++++------- docs/normative/entity-execution-cli/v1/README.md | 2 +- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 5dc2838825..5b6f2dce5c 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -563,11 +563,10 @@ 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). -- 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 + scope is per-repo mode only. The `jira-poll` driver no longer uses those + locks (see the next item). +- Jira poll candidate selection: one poller per repository reads every issue + that changed within the 24-hour backfill window, oldest change first unless the configured query sets its own order, skips issues whose Jira `updated` is not newer than their per-repository checkpoint, and dispatches up to @@ -577,6 +576,8 @@ The existing design principle is that [the repo is the coordinator](problems/age ([ADR 0085](ADRs/0085-serve-every-changed-jira-issue.md), partially superseding [ADR 0063](ADRs/0063-polling-based-work-discovery.md) and [ADR 0160](ADRs/0160-spend-jira-poll-slots-only-on-candidates-with-new-activity.md)). + Target state: the window length becomes a setting, + `tracker.jira.poll.backfill_window_hours` (default 24). - Jira poll actor authorization does not require the poller to administer the Jira project once a repository adds a `jira` provider under `authorization:`. With no `jira` entry, every Jira event resolves through the @@ -809,8 +810,8 @@ The existing design principle is that [the repo is the coordinator](problems/age protocol. - 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, which ADR 0085 removes for the `jira-poll` driver in favor of + idempotency? (Jira polling per ADR 0063 used entity-property locks and runner + lock refresh, which ADR 0085 removed for the `jira-poll` driver in favor of one poller per repository; ADR 0165 chooses an operation journal for recoverable effects, while adapter implementation and external-system guarantees remain open.) 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 From 632838ea4ee98fce9f2a4deea945340881d87561 Mon Sep 17 00:00:00 2001 From: guy oron Date: Mon, 30 Nov 2026 13:34:19 +0200 Subject: [PATCH 37/60] fix(jirapoll): read the per-cycle limit when the config has no tracker block main resolves the Jira poll settings from the entity-source configuration (#9893), so loadJiraPollSettings can now return for a config that declares Jira sources and no tracker block. Reading tracker.jira.poll.max_dispatches_per_cycle there dereferenced a nil tracker. A config with no tracker block now gets the default limit. Signed-off-by: guy oron --- internal/cli/poll.go | 8 +++++++- internal/cli/poll_jira_config_test.go | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/internal/cli/poll.go b/internal/cli/poll.go index 5b9734b21a..c7ed665325 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -415,6 +415,12 @@ func loadJiraPollSettings(fullsendDir, jiraURL, jiraProject, jql string, diag .. } } } + // The per-cycle limit is read from tracker.jira.poll. A config with no + // tracker block gets the default. + var tracker *config.JiraTrackingConfig + if tracking := cfg.IssueTracking(); tracking != nil { + tracker = tracking.Jira + } return jiraPollSettings{ baseURL: scope.Connection.BaseURL, apiURL: scope.Connection.EffectiveAPIURL(), @@ -423,7 +429,7 @@ func loadJiraPollSettings(fullsendDir, jiraURL, jiraProject, jql string, diag .. enabled: scope.Enabled, sources: scope.Sources, - maxDispatches: cfg.IssueTracking().Jira.PollMaxDispatchesPerCycle(), + maxDispatches: tracker.PollMaxDispatchesPerCycle(), }, nil } diff --git a/internal/cli/poll_jira_config_test.go b/internal/cli/poll_jira_config_test.go index 9a3e01c4c1..021c68ffe5 100644 --- a/internal/cli/poll_jira_config_test.go +++ b/internal/cli/poll_jira_config_test.go @@ -427,6 +427,25 @@ agents: } } +// With no tracker block at all, the per-cycle limit is its default: an +// explicit Jira source that no agent binds leaves polling disabled and is +// not an error. +func TestLoadJiraPollSettings_NoTrackerBlock(t *testing.T) { + got, err := loadJiraPollSettings(writeJiraPollConfig(t, `connections: + ja: + kind: jira + base_url: https://example.atlassian.net +entity_sources: + sa: + connection: ja + projects: [A] + query: '' +`), "", "", "") + require.NoError(t, err) + assert.False(t, got.enabled) + assert.Equal(t, config.DefaultJiraPollMaxDispatchesPerCycle, got.maxDispatches) +} + func TestLoadJiraPollSettings_ShadowDiagnostics(t *testing.T) { dir := writeJiraPollConfig(t, enabledJiraPollConfig+`entity_sources: legacy_tracker: From c0d2d4c63292d20b8594030e5ad5d63e6e4e0d47 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 11:48:55 +0200 Subject: [PATCH 38/60] fix(jirapoll): validate tracker.jira when an explicit source replaces the translated one The jira-poll settings loader reads max_dispatches_per_cycle from tracker.jira.poll on every path. When an explicit entity source on the connection translated from tracker.jira replaces the translated source, the source is resolved without validating tracker.jira, so a limit outside 1 to 250 reached the poller. The loader now calls ValidateConnection itself, as the other commands that read tracker.jira do. Signed-off-by: guy oron --- internal/cli/poll.go | 7 ++++++- internal/cli/poll_jira_config_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/internal/cli/poll.go b/internal/cli/poll.go index c7ed665325..f889a0c539 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -416,11 +416,16 @@ func loadJiraPollSettings(fullsendDir, jiraURL, jiraProject, jql string, diag .. } } // The per-cycle limit is read from tracker.jira.poll. A config with no - // tracker block gets the default. + // tracker block gets the default. tracker.jira is validated here because + // an explicit source that replaces the translated one is resolved + // without it, and the limit is read on that path too. var tracker *config.JiraTrackingConfig if tracking := cfg.IssueTracking(); tracking != nil { tracker = tracking.Jira } + if err := tracker.ValidateConnection(); err != nil { + return jiraPollSettings{}, err + } return jiraPollSettings{ baseURL: scope.Connection.BaseURL, apiURL: scope.Connection.EffectiveAPIURL(), diff --git a/internal/cli/poll_jira_config_test.go b/internal/cli/poll_jira_config_test.go index 021c68ffe5..e97fd595af 100644 --- a/internal/cli/poll_jira_config_test.go +++ b/internal/cli/poll_jira_config_test.go @@ -446,6 +446,30 @@ entity_sources: assert.Equal(t, config.DefaultJiraPollMaxDispatchesPerCycle, got.maxDispatches) } +// The per-cycle limit comes from tracker.jira.poll whichever source the +// poller reads. An explicit source that replaces the one translated from +// tracker.jira is resolved without validating tracker.jira, so the loader +// validates it: an out-of-range limit is an error on that path too. +func TestLoadJiraPollSettings_ExplicitSourceKeepsLimitValidation(t *testing.T) { + _, err := loadJiraPollSettings(writeJiraPollConfig(t, `tracker: + jira: + base_url: https://example.atlassian.net + project: PROJ + poll: + enabled: true + max_dispatches_per_cycle: 9999 +entity_sources: + legacy_tracker: + projects: [PROJ1, PROJ2] + query: 'statusCategory != Done' +agents: + - name: triage + entities: + source: [legacy_tracker] +`), "", "", "") + require.ErrorContains(t, err, "poll.max_dispatches_per_cycle must be a whole number from 1 to 250 (got 9999)") +} + func TestLoadJiraPollSettings_ShadowDiagnostics(t *testing.T) { dir := writeJiraPollConfig(t, enabledJiraPollConfig+`entity_sources: legacy_tracker: From d226986f60fc68e9022f52b572ace669fa88a466 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 11:57:02 +0200 Subject: [PATCH 39/60] 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 40/60] 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 ae9e9deae9fab75a9ca4ee43db0f224f5d80b6a3 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 11:58:45 +0200 Subject: [PATCH 41/60] docs(jira-poll): quote the all-failed error as it now reads in the troubleshooting table The error names active issues where it named selected ones. 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 2294059569..cba4fcd908 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1775,7 +1775,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 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 | +| `WARNING: processing : check write access to : ...` in the poll log, or the poll fails with `all N active 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. 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) | From 8827fae63c1957057eccf076cc61b9a9a6f228b6 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 12:01:09 +0200 Subject: [PATCH 42/60] 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 83ab4627f7ee93cdac19b510e20206a73dc783c9 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 12:01:58 +0200 Subject: [PATCH 43/60] docs(jira-poll): link ADR 0085 from the upgrade notice The ADR file is on this branch now that the base carries main. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index ffd0d71311..0a263332f6 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1650,7 +1650,8 @@ matches it. Use `labels: allowlist` if that group is broader than you want. ## Upgrading the Jira poller Fullsend v0.58.0 changes which issues the poller serves in a cycle and how -two cycles are kept apart (ADR 0085). It affects every repository that polls +two cycles are kept apart +([ADR 0085](../../ADRs/0085-serve-every-changed-jira-issue.md)). It affects every repository that polls Jira, on GitHub and on GitLab. The Jira credential and the permissions the poller needs do not change. From df6db02c26fc85d07d6c05a86983b292cc14d6f8 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 12:17:54 +0200 Subject: [PATCH 44/60] fix(jirapoll): check only the per-cycle limit when an explicit source replaces the translated one The previous commit had the settings loader call ValidateConnection, which also requires tracker.jira.project and a balanced poll.query. An explicit source that replaces the lookup scope translated from tracker.jira does not use either, and entity-source resolution drops those errors on purpose, so the loader rejected a config that polls on main. The limit check moves to ValidatePollLimits, which ValidateConnection still runs and the loader now calls instead. Signed-off-by: guy oron --- internal/cli/poll.go | 10 ++++++---- internal/cli/poll_jira_config_test.go | 28 ++++++++++++++++++++++++++- internal/config/issue_targets.go | 10 ++++++++++ 3 files changed, 43 insertions(+), 5 deletions(-) diff --git a/internal/cli/poll.go b/internal/cli/poll.go index f889a0c539..dd1ae22773 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -416,14 +416,16 @@ func loadJiraPollSettings(fullsendDir, jiraURL, jiraProject, jql string, diag .. } } // The per-cycle limit is read from tracker.jira.poll. A config with no - // tracker block gets the default. tracker.jira is validated here because - // an explicit source that replaces the translated one is resolved - // without it, and the limit is read on that path too. + // tracker block gets the default. The limit is checked here because an + // explicit source that replaces the translated one is resolved without + // validating tracker.jira, and the limit is read on that path too. The + // project and query of tracker.jira do not apply to such a source, so + // they are not checked. var tracker *config.JiraTrackingConfig if tracking := cfg.IssueTracking(); tracking != nil { tracker = tracking.Jira } - if err := tracker.ValidateConnection(); err != nil { + if err := tracker.ValidatePollLimits(); err != nil { return jiraPollSettings{}, err } return jiraPollSettings{ diff --git a/internal/cli/poll_jira_config_test.go b/internal/cli/poll_jira_config_test.go index e97fd595af..9216f28c69 100644 --- a/internal/cli/poll_jira_config_test.go +++ b/internal/cli/poll_jira_config_test.go @@ -449,7 +449,7 @@ entity_sources: // The per-cycle limit comes from tracker.jira.poll whichever source the // poller reads. An explicit source that replaces the one translated from // tracker.jira is resolved without validating tracker.jira, so the loader -// validates it: an out-of-range limit is an error on that path too. +// checks the limit itself: out of range, it is an error on that path too. func TestLoadJiraPollSettings_ExplicitSourceKeepsLimitValidation(t *testing.T) { _, err := loadJiraPollSettings(writeJiraPollConfig(t, `tracker: jira: @@ -470,6 +470,32 @@ agents: require.ErrorContains(t, err, "poll.max_dispatches_per_cycle must be a whole number from 1 to 250 (got 9999)") } +// An explicit source replaces the lookup scope translated from tracker.jira, +// so the project and query errors of tracker.jira do not apply to it +// (config.translateLegacyTracker). The loader checks only the poller's own +// limit on that path, and such a config still polls. +func TestLoadJiraPollSettings_ExplicitSourceIgnoresTrackerScopeErrors(t *testing.T) { + got, err := loadJiraPollSettings(writeJiraPollConfig(t, `tracker: + jira: + base_url: https://example.atlassian.net + poll: + enabled: true + query: 'labels = a)' +entity_sources: + legacy_tracker: + projects: [PROJ1, PROJ2] + query: 'statusCategory != Done' +agents: + - name: triage + entities: + source: [legacy_tracker] +`), "", "", "") + require.NoError(t, err) + assert.True(t, got.enabled) + assert.Equal(t, []string{"PROJ1", "PROJ2"}, got.projects) + assert.Equal(t, config.DefaultJiraPollMaxDispatchesPerCycle, got.maxDispatches) +} + func TestLoadJiraPollSettings_ShadowDiagnostics(t *testing.T) { dir := writeJiraPollConfig(t, enabledJiraPollConfig+`entity_sources: legacy_tracker: diff --git a/internal/config/issue_targets.go b/internal/config/issue_targets.go index 899ec8a3ac..2e9ce7db6e 100644 --- a/internal/config/issue_targets.go +++ b/internal/config/issue_targets.go @@ -623,6 +623,16 @@ func (j *JiraTrackingConfig) ValidateConnection() error { if j.Poll != nil && !JQLParensBalanced(j.Poll.Query) { return fmt.Errorf("tracker.jira: poll.query has unbalanced parentheses: the query is wrapped in parentheses to scope it to the project") } + return j.ValidatePollLimits() +} + +// ValidatePollLimits checks poll.max_dispatches_per_cycle. It is part of +// ValidateConnection. The jira-poll driver also calls it directly, because +// the driver reads the limit from tracker.jira whichever entity source it +// polls, and an explicit source that replaces the translated one is +// resolved without ValidateConnection: the project and query checks do not +// apply to it, and this one still does. +func (j *JiraTrackingConfig) ValidatePollLimits() error { if limit := j.PollMaxDispatchesPerCycle(); limit < MinJiraPollMaxDispatchesPerCycle || limit > MaxJiraPollMaxDispatchesPerCycle { return fmt.Errorf("tracker.jira: poll.max_dispatches_per_cycle must be a whole number from %d to %d (got %d)", MinJiraPollMaxDispatchesPerCycle, MaxJiraPollMaxDispatchesPerCycle, limit) } From 07582e18854875d109ce22cb57e0786a08974e3e Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 13:38:40 +0200 Subject: [PATCH 45/60] 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 46/60] 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 9c8477ab236bff970527a6750c477b3621564c78 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 13:42:39 +0200 Subject: [PATCH 47/60] refactor(jirapoll): drop the count snapshot that per-issue counts replace The fix merged from the time-limits branch puts the cycle's event counts back when an issue's result is discarded. Here an issue's counts travel with its pendingCheckpoint and are added to the cycle only when the issue is taken, so there is nothing to put back. Signed-off-by: guy oron --- internal/jirapoll/poller.go | 7 ------- 1 file changed, 7 deletions(-) diff --git a/internal/jirapoll/poller.go b/internal/jirapoll/poller.go index 1714187ffe..d0dbe04f18 100644 --- a/internal/jirapoll/poller.go +++ b/internal/jirapoll/poller.go @@ -193,7 +193,6 @@ func (p *Poller) Run(ctx context.Context) error { break } 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() @@ -206,12 +205,6 @@ 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: From 46adaebb58a5ebe3f8e5086d818e8631c7c6efbb Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 13:44:00 +0200 Subject: [PATCH 48/60] test(jira-poll): report a missing dispatch condition in the contract test Under pipefail a grep that finds no dispatch condition ended the script at the assignment, before the check that names what is missing. The test still failed, without saying why. The helper now returns an empty condition and the checks after it report it. Signed-off-by: guy oron --- .github/scripts/jira-poll-record-digest-test.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/scripts/jira-poll-record-digest-test.sh b/.github/scripts/jira-poll-record-digest-test.sh index 31ccaa9ab1..3edf678209 100755 --- a/.github/scripts/jira-poll-record-digest-test.sh +++ b/.github/scripts/jira-poll-record-digest-test.sh @@ -63,7 +63,9 @@ for workflow in reusable-poll-jira.yml jira-poll-batch-check-poll.yml; do done # The caller hands the matrix on under the managed caller's condition. -condition() { grep -F 'fromJSON(needs.poll.outputs.matrix)' "$1" | sed 's/^[[:space:]]*//'; } +# A file without the line gives an empty condition, so the checks below +# report it; under pipefail a bare grep miss would end the script first. +condition() { grep -F 'fromJSON(needs.poll.outputs.matrix)' "$1" | sed 's/^[[:space:]]*//' || true; } real_condition="$(condition "${TEMPLATE}")" [[ -n "${real_condition}" ]] || fail "jira-poll-per-repo.yaml has no dispatch condition" [[ "$(condition "${WORKFLOWS}/jira-poll-batch-check.yml")" == "${real_condition}" ]] || From eb0498fe49790903feccf944e8d9a42c80060329 Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 2 Dec 2026 12:54:57 +0200 Subject: [PATCH 49/60] 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 50/60] 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 08f5134803fd1ebe2a0b551752c45707a934d355 Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 2 Dec 2026 13:08:43 +0200 Subject: [PATCH 51/60] refactor(jirapoll): drop the loader's own check of the per-cycle limit The settings loader checked poll.max_dispatches_per_cycle itself because an explicit entity source could replace the scope translated from tracker.jira, and that path skipped the block's validation. The base now rejects tracker.jira combined with entity sources, so the block is always validated and JiraDiscoveryScope returns the error. The direct call and the separate ValidatePollLimits method go; the loader's invalid-config test covers an out-of-range limit. Signed-off-by: guy oron --- internal/cli/poll.go | 12 +++--------- internal/cli/poll_jira_config_test.go | 1 + internal/config/issue_targets.go | 10 ---------- 3 files changed, 4 insertions(+), 19 deletions(-) diff --git a/internal/cli/poll.go b/internal/cli/poll.go index d06015ccbc..5f7bf12d60 100644 --- a/internal/cli/poll.go +++ b/internal/cli/poll.go @@ -409,19 +409,13 @@ func loadJiraPollSettings(fullsendDir, jiraURL, jiraProject, jql string) (jiraPo } } } - // The per-cycle limit is read from tracker.jira.poll. A config with no - // tracker block gets the default. The limit is checked here because an - // explicit source that replaces the translated one is resolved without - // validating tracker.jira, and the limit is read on that path too. The - // project and query of tracker.jira do not apply to such a source, so - // they are not checked. + // The per-cycle limit is read from tracker.jira.poll. It is validated + // with the rest of the block, and JiraDiscoveryScope above returns that + // error. A config with no tracker block gets the default. var tracker *config.JiraTrackingConfig if tracking := cfg.IssueTracking(); tracking != nil { tracker = tracking.Jira } - if err := tracker.ValidatePollLimits(); err != nil { - return jiraPollSettings{}, err - } return jiraPollSettings{ baseURL: scope.Connection.BaseURL, apiURL: scope.Connection.EffectiveAPIURL(), diff --git a/internal/cli/poll_jira_config_test.go b/internal/cli/poll_jira_config_test.go index 8de77e8ed8..2f4143acf7 100644 --- a/internal/cli/poll_jira_config_test.go +++ b/internal/cli/poll_jira_config_test.go @@ -147,6 +147,7 @@ func TestLoadJiraPollSettings_InvalidConfig(t *testing.T) { "missing project": {"tracker:\n jira:\n base_url: https://example.atlassian.net\n", "project is required"}, "missing base_url": {"tracker:\n jira:\n project: PROJ\n", "base_url is required"}, "unbalanced query": {"tracker:\n jira:\n base_url: https://example.atlassian.net\n project: PROJ\n poll:\n query: 'a = b)'\n", "unbalanced parentheses"}, + "limit too high": {"tracker:\n jira:\n base_url: https://example.atlassian.net\n project: PROJ\n poll:\n max_dispatches_per_cycle: 9999\n", "poll.max_dispatches_per_cycle must be a whole number from 1 to 250 (got 9999)"}, } { t.Run(name, func(t *testing.T) { _, err := loadJiraPollSettings(writeJiraPollConfig(t, tc.body), "", "", "") diff --git a/internal/config/issue_targets.go b/internal/config/issue_targets.go index 8fdcacfeaf..65cfa4e8e6 100644 --- a/internal/config/issue_targets.go +++ b/internal/config/issue_targets.go @@ -602,16 +602,6 @@ func (j *JiraTrackingConfig) ValidateConnection() error { if j.Poll != nil && !JQLParensBalanced(j.Poll.Query) { return fmt.Errorf("tracker.jira: poll.query has unbalanced parentheses: the query is wrapped in parentheses to scope it to the project") } - return j.ValidatePollLimits() -} - -// ValidatePollLimits checks poll.max_dispatches_per_cycle. It is part of -// ValidateConnection. The jira-poll driver also calls it directly, because -// the driver reads the limit from tracker.jira whichever entity source it -// polls, and an explicit source that replaces the translated one is -// resolved without ValidateConnection: the project and query checks do not -// apply to it, and this one still does. -func (j *JiraTrackingConfig) ValidatePollLimits() error { if limit := j.PollMaxDispatchesPerCycle(); limit < MinJiraPollMaxDispatchesPerCycle || limit > MaxJiraPollMaxDispatchesPerCycle { return fmt.Errorf("tracker.jira: poll.max_dispatches_per_cycle must be a whole number from %d to %d (got %d)", MinJiraPollMaxDispatchesPerCycle, MaxJiraPollMaxDispatchesPerCycle, limit) } From b66e01c1c5a96ee252c244372aa75aadfe92ddc7 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 00:40:51 +0200 Subject: [PATCH 52/60] 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 53/60] 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 54/60] 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 bf69ebdffe7bb8e43bca8c4e7891b1e3595c7a37 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 00:43:41 +0200 Subject: [PATCH 55/60] docs(jira-poll): wrap the per-cycle limit paragraph at 80 columns Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index ef1afde4f9..025ae63d7a 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1767,7 +1767,21 @@ 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-cycle limit.** The poller reads the issues with new activity one by one, in the search's order, and stops when the cycle holds `tracker.jira.poll.max_dispatches_per_cycle` dispatch records (default 100, from 1 to 250). All of an issue's records go out in the same cycle: an issue whose records do not fit in the room left waits for the next cycle, and so do the issues behind it, because the poller does not skip ahead to a smaller one. An issue is always taken when the cycle holds no records yet, so an issue with more records than the limit is dispatched alone and the cycle exceeds the limit by that one issue. On GitHub the cycle also stops before the issue whose records would take the `matrix` output past 768 KB. An issue that waits keeps its `lastCheck`, so nothing is lost by waiting unless its request leaves the 24-hour window first. The run log says how many issues wait: `the cycle holds dispatch records, at its limit of ; active issue(s) wait for the next cycle`. The limit sets how fast a backlog drains: raise it if requests wait too long, and lower it to start fewer agent runs per cycle. +**Per-cycle limit.** The poller reads the issues with new activity one by one, +in the search's order, and stops when the cycle holds +`tracker.jira.poll.max_dispatches_per_cycle` dispatch records (default 100, from +1 to 250). All of an issue's records go out in the same cycle: an issue whose +records do not fit in the room left waits for the next cycle, and so do the +issues behind it, because the poller does not skip ahead to a smaller one. An +issue is always taken when the cycle holds no records yet, so an issue with more +records than the limit is dispatched alone and the cycle exceeds the limit by +that one issue. On GitHub the cycle also stops before the issue whose records +would take the `matrix` output past 768 KB. An issue that waits keeps its +`lastCheck`, so nothing is lost by waiting unless its request leaves the 24-hour +window first. The run log says how many issues wait: +`the cycle holds dispatch records, at its limit of ; active issue(s) wait for the next cycle`. +The limit sets how fast a backlog drains: raise it if requests wait too long, +and lower it to start fewer agent runs per cycle. > **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, and so is the number of dispatch records in one cycle, to bound the blast radius. A rewind does not move an issue in the line, so an editor who keeps rewinding issues near the front can hold back the requests behind them. 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 8d4ed37ab3806589301791a9e5884f5abb218023 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 00:47:20 +0200 Subject: [PATCH 56/60] docs(jira-poll): say which limit a declared connections.jira polls with Signed-off-by: guy oron --- docs/reference/config-reference.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/reference/config-reference.md b/docs/reference/config-reference.md index f438497216..f3e2f9b30a 100644 --- a/docs/reference/config-reference.md +++ b/docs/reference/config-reference.md @@ -614,7 +614,9 @@ tracker: drains: a request that waits longer than the 24-hour backfill window is lost. 250 is GitHub's limit of 256 jobs in a matrix less a small margin. New in fullsend v0.58.0: an older CLI or reusable workflow rejects a - config that sets it, and stops polling, so set it after the upgrade. See + config that sets it, and stops polling, so set it after the upgrade. A + config that declares `connections.jira` directly has no `tracker.jira.poll` + block, so it polls with the default. See [Poll coordination](../guides/user/jira-integration.md#poll-coordination). `base_url` and `project` are required once `base_url`, `api_url`, `project`, From 20982f4eeb9227eb2e6f77e6642ec4ffb0040b22 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 16:03:54 +0200 Subject: [PATCH 57/60] 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 58/60] 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 59/60] 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 60/60] 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.