From 527843f113cb5066be4947aa5fa2bf4d246b0b7c Mon Sep 17 00:00:00 2001 From: guy oron Date: Wed, 25 Nov 2026 02:43:28 +0200 Subject: [PATCH 01/14] 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/14] 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/14] 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 c999caeb986672f311f7c6a81a76ad9c3716d3fc Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 26 Nov 2026 05:51:48 +0200 Subject: [PATCH 04/14] 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 05/14] 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 06/14] 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 f32dd09ba59863532df8fceeca1368b33dc099af Mon Sep 17 00:00:00 2001 From: guy oron Date: Fri, 27 Nov 2026 04:31:44 +0200 Subject: [PATCH 07/14] 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 d226986f60fc68e9022f52b572ace669fa88a466 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 11:57:02 +0200 Subject: [PATCH 08/14] 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 8827fae63c1957057eccf076cc61b9a9a6f228b6 Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 12:01:09 +0200 Subject: [PATCH 09/14] docs(jira-poll): name the token scope the write check needs Setting an issue property needs the Edit Issues permission and, for an OAuth or scoped token, the write:jira-work scope (Atlassian's REST API reference, "Set issue property"). A token can hold the permission and lack the scope, which is the case the write check exists to catch. Signed-off-by: guy oron --- docs/guides/user/jira-integration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guides/user/jira-integration.md b/docs/guides/user/jira-integration.md index 838bf52053..c346fe959b 100644 --- a/docs/guides/user/jira-integration.md +++ b/docs/guides/user/jira-integration.md @@ -1755,7 +1755,7 @@ However, more pollers against the same Jira project means more API calls per cyc | `Jira polling is disabled` and no dispatches | `tracker.jira.poll.enabled` is not `true` | Set `tracker.jira.poll.enabled: true` | | Duplicate dispatches | `lastCheck` was cleared or missing | The poller treats a missing `lastCheck` as "never polled" and processes all recent changes. This is self-correcting — the next cycle advances `lastCheck` past the duplicates | | Duplicate dispatches that keep happening | Two poll cycles for the same repository ran at the same time: a second workflow or job polls the repository, or a scheduler other than the managed one lets cycles overlap | The poller keeps no per-issue lock, so overlapping cycles dispatch the same requests twice. Run one poller per repository and keep its cycles from overlapping; on GitHub Actions the poll job needs a concurrency group with `cancel-in-progress: false`. See [Scheduled workflow](#scheduled-workflow) | -| `WARNING: processing : check write access to : ...` in the poll log, or the poll fails with `all N selected issues failed to process` | The Jira credential cannot write to the issue. Before it reads an issue the poller writes a property on it, which needs **Edit Issues** | Grant the poller account Edit Issues on the project — see [Minimum Jira permissions](#minimum-jira-permissions). An issue that fails the check is skipped: nothing is dispatched for it and its `lastCheck` does not move, so it is read again on the next cycle. The run fails only when every issue the cycle read failed; the `WARNING: processing : ...` lines above the error give each issue's cause, which can be other than write access | +| `WARNING: processing : check write access to : ...` in the poll log, or the poll fails with `all N selected issues failed to process` | The Jira credential cannot write to the issue. Before it reads an issue the poller writes a property on it, which needs **Edit Issues** and, with an OAuth or scoped token, the `write:jira-work` scope (granular: `write:issue.property:jira`) | Grant the poller account Edit Issues on the project — see [Minimum Jira permissions](#minimum-jira-permissions) — or add the scope to the token. An issue that fails the check is skipped: nothing is dispatched for it and its `lastCheck` does not move, so it is read again on the next cycle. The run fails only when every issue the cycle read failed; the `WARNING: processing : ...` lines above the error give each issue's cause, which can be other than write access | | Old comment or label change on a newly polled issue never dispatches | Activity predates the first-poll backfill window | On an issue's first poll, activity older than the 24-hour backfill window is permanently skipped (the checkpoint advances past it). To pick up older activity, scope the initial `tracker.jira.poll.query` to recently updated issues and widen it gradually, or have someone re-trigger by commenting again | | Activity during a long outage or disabled workflow is missing after resume | Poller gap exceeded the 24-hour backfill window | The same 24-hour window that bounds a first poll also bounds resumption — any `lastCheck` older than 24 hours is clamped forward. Check the run log for `predates the backfill window` — if present, events in the gap may have been permanently lost. Have affected users re-trigger by commenting again. See [Poll coordination](#poll-coordination) | | GitLab Jira dispatch fails with `does not accept Jira work items` | The project's scaffold predates Jira dispatch | Rerun `fullsend repos install` for the project and merge the scaffold update. See [GitLab runtime](#gitlab-runtime) | From 07582e18854875d109ce22cb57e0786a08974e3e Mon Sep 17 00:00:00 2001 From: guy oron Date: Tue, 1 Dec 2026 13:38:40 +0200 Subject: [PATCH 10/14] 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 20982f4eeb9227eb2e6f77e6642ec4ffb0040b22 Mon Sep 17 00:00:00 2001 From: guy oron Date: Thu, 3 Dec 2026 16:03:54 +0200 Subject: [PATCH 11/14] 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 12/14] 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 13/14] 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 14/14] 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.