Skip to content

Feat/polling watermark overlap - #1580

Closed
gdsavills wants to merge 48 commits into
mongrel-intelligence:devfrom
gdsavills:feat/polling-watermark-overlap
Closed

gdsavills wants to merge 48 commits into
mongrel-intelligence:devfrom
gdsavills:feat/polling-watermark-overlap

Conversation

@gdsavills

Copy link
Copy Markdown

Summary

Test Plan

  • Unit tests pass (npm test)
  • Linter passes (npm run lint)
  • Type check passes (npm run typecheck)
  • Tested manually (describe below)

Checklist

  • My code follows the project's code style
  • I have added tests for new functionality
  • I have updated documentation if needed
  • My commits follow Conventional Commits

gdsavills and others added 30 commits October 29, 2026 13:32
Add polling_watermarks table for tracking incremental polling state per
project/provider/resource. Add polling_processed_events table for event
deduplication with event_type support for 'ignored' events.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add POLLING_* environment variables for controlling polling behavior:
- POLLING_ENABLED: master switch
- POLLING_INTERVAL_MS: poll frequency
- POLLING_JIRA_OVERLAP_MINUTES: JQL time window overlap
- POLLING_GITHUB_LOOKBACK_MS: fixed lookback for workflow runs
- POLLING_GITHUB_PR_BATCH_SIZE: max PRs per repo for review polling
- POLLING_DEDUP_RETENTION_DAYS: ledger cleanup retention

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…esult

Add structured fields to ProcessRouterWebhookResult for polling to determine
whether to record events in the dedup ledger:
- deferred: true when dispatch was scheduled for later re-check
- skipReason: the handler name and message when a trigger self-skipped

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add types for GitHub API responses (workflow runs, PRs, reviews) and
synthetic event builders for check_suite, pull_request_review, and
merged PR events. Includes conclusion filtering logic per FINAL-PLAN-v2.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add dispatchAndRecord() that dispatches synthetic events through the
router pipeline and records them in the dedup ledger:
- deferred events: NOT recorded (will re-emit next cycle)
- skipped events: recorded (final decision)
- errors: NOT recorded, returns error

Includes batch ledger lookup and cold start seeding helpers.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add check-suite poller that:
1. Applies conclusion filter FIRST (before any API call)
2. Batch checks ledger SECOND
3. Resolves PR numbers THIRD (only for new, emittable runs)
4. Records ignored events (skipped conclusions, unresolvable PRs)

Uses 6-hour fixed lookback window per FINAL-PLAN-v2.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add pollers for GitHub PR reviews and merged PRs:
- PR review poller tracks reviews on open PRs using watermarks
- Merged PR poller tracks closed+merged PRs using watermarks
- Both use batch ledger lookup and watermark advancement

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Use hardcoded MAX_PAGINATION_PAGES constant instead of config value
- Fix PR resolution to distinguish transient errors from no PR found:
  - Transient errors (rate limit, network, 5xx): NOT recorded, retry next cycle
  - No PR found (API succeeded): recorded as 'ignored', no retry

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- adapter.ts: bridge to router platform adapters
- cold-start.ts: per-repo ledger seeding without dispatch
- scheduler.ts: BullMQ job scheduler with concurrency 1
- cleanup.ts: retention-based ledger cleanup
- index.ts: module exports for router integration

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add tests for:
- dispatchAndRecord: ledger dedup, deferred handling, error handling
- recordWithoutDispatch: ledger recording without dispatch
- batchCheckLedger: batch existence check
- pollCheckSuitesForRepo: conclusion filtering, PR resolution error handling

Tests verify that transient errors leave runs unrecorded for retry,
while successful no-PR-found results are recorded as ignored.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Wire polling scheduler to router lifecycle:
- Start polling scheduler after cancel listener (no-op if POLLING_ENABLED=false)
- Stop polling scheduler on shutdown before other services

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Tests cover:
- Reviews older than watermark are skipped
- New reviews (after watermark) are emitted
- Watermark is updated after successful poll
- review.user.login is set in synthetic payload (loop protection)
- Dedup key format: github:{owner}/{repo}:pr_review:{pr_number}:{review_id}
- PENDING reviews are skipped
- Ledger deduplication works correctly

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Tests cover:
- Only merged PRs (merged_at set) are emitted
- Closed-but-not-merged PRs (merged_at null) are skipped
- Watermark update after successful poll
- PRs merged before watermark are skipped
- Synthetic payload has pull_request.merged: true
- Dedup key format: github:{owner}/{repo}:merged_pr:{pr_number}
- Ledger deduplication works correctly

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Tests cover:
- Per-repo cold start inserts dedup keys for each repo
- Empty-insert guard: no inserts if ledger already has entries for repo
- Same conclusion mapping as check-suite poller (success/failure vs ignored)
- Cold start uses same dedup key format as regular polling
- Watermark initialization for pr_reviews and merged_prs

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Tests cover:
- Single-runner guarantee: only one poll cycle runs at a time (concurrency 1)
- Scheduler starts when POLLING_ENABLED=true
- Scheduler does not start when POLLING_ENABLED=false
- upsertJobScheduler is called with correct interval
- runPollCycle logs when no projects configured
- pollProject skips project without GitHub token

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Tests cover:
- Cleanup job deletes records older than retention period
- Cleanup preserves records within retention period
- Cleanup uses pollingConfig.dedupRetentionDays
- Logs start and completion with appropriate metrics
- Handles null/undefined rowCount gracefully

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Contract test verifies synthetic polling events contain all JSON paths
the router adapter reads from real webhook payloads:

- check_suite: _eventType, _deliveryId, action, check_suite.id,
  check_suite.status, check_suite.conclusion, check_suite.head_sha,
  check_suite.head_branch, check_suite.pull_requests, repository.full_name,
  sender.login

- pull_request_review: _eventType, _deliveryId, action, review.id,
  review.state, review.user.login (for loop protection), pull_request.number,
  pull_request.head, pull_request.base, repository.full_name, sender.login

- pull_request closed+merged: _eventType, _deliveryId, action: closed,
  number, pull_request.merged: true, pull_request.state, pull_request.head,
  pull_request.base, pull_request.user.login, repository.full_name, sender.login

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add types for Jira polling implementation:
- JiraIssue, JiraSearchResponse for API responses
- JiraChangelogHistory, JiraChangelogItem for changelog entries
- SyntheticJiraWebhookPayload matching JiraRouterAdapter expectations
- buildJiraStatusChangedDedupKey for dedup key generation
- buildSyntheticJiraStatusChangedPayload for synthetic event creation
- filterStatusChangeHistories for changelog processing

Dedup key format: jira:{projectKey}:status_changed:{issueKey}:{historyId}

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implement watermark-based polling for Jira status changes:
- Uses GET /rest/api/3/search/jql with nextPageToken/isLast pagination
- JQL: project = "<KEY>" AND updated >= -Nm ORDER BY updated ASC
- Lookback calculated from watermark with overlap window (jiraOverlapMinutes)
- Caps lookback at 24 hours (1440 minutes) with warning log
- Filters changelog histories for status field changes
- Loop protection: skips changes made by bot account
- Watermark advancement rule: NOT updated if ANY dispatch failed
- Batch ledger check before dispatch
- MAX_PAGINATION_PAGES = 20 safety limit

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Tests cover:
- Watermark update after successful poll
- Watermark NOT updated if errors occurred (per FINAL-PLAN-v2)
- Overlap window applied to JQL query
- Bot account filtering (loop protection)
- Dedup key format: jira:{projectKey}:status_changed:{issueKey}:{historyId}
- Synthetic payload structure matches JiraRouterAdapter expectations
- Watermark filtering skips old changes
- Ledger deduplication works correctly

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Update getPollingAdapter to support Jira provider by returning
JiraRouterAdapter for Jira synthetic events.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Update scheduler to poll Jira projects in addition to GitHub:
- Add imports for Jira credentials and bot identity resolvers
- Create createJiraApiClient() wrapper for Jira Search API
- Add pollJiraProject() function that:
  - Resolves Jira credentials and bot account ID
  - Creates Jira API client
  - Calls pollJiraStatusChanges for projects with Jira integration
- Update runPollCycle to call both GitHub and Jira polling
- Rename pollProject to pollGitHubProject for clarity

Update scheduler tests with required mocks for Jira dependencies.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
…ller

Cascade uses the user's own Jira account, so filtering by author would
drop every manual status move. Remove the botAccountId parameter and all
author self-filtering logic. Status changes by any author are now emitted.

Per FINAL-PLAN-v2 corrections: Task 14 (bot account resolver) was removed.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When listReviews() fails for a PR (e.g., rate limit), the error counter
must be incremented so the watermark does NOT advance. Previously,
failures were only logged, allowing the watermark to advance and
potentially miss reviews forever.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Only call listReviews() for PRs whose updated_at is newer than the
watermark. A PR that hasn't been updated cannot have new reviews, so
skipping stale PRs reduces API calls significantly.

Before: 10,200 req/hr worst-case (exceeds GitHub's 5,000/hr limit)
After: 2,040 req/hr worst-case (59% headroom)
Typical: 240 req/hr (95% headroom)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add maybeRunLedgerCleanup() to poll cycle that runs cleanupPollingLedger()
once per 24 hours. Uses in-memory tracking (single instance per CLAUDE.md).
Cleanup errors are logged but don't fail the poll cycle.

Prevents unbounded growth of polling_processed_events table.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
On first poll of a Jira project (no watermarks), seed the ledger with
existing status change history IDs WITHOUT dispatching. This prevents
historical events from triggering agents on first startup.

Same behavior as GitHub cold start: fetch recent data, record to ledger,
initialize watermark to NOW.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Document the official API documentation sources for test fixture helpers:
- GitHub: workflow runs, pull requests, reviews
- Jira: issue search, changelog

This clarifies that fixtures are based on real API response schemas.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Replace inline fixture constants with JSON files from official docs:
- GitHub check_suite: https://docs.github.com/en/webhooks/webhook-events-and-payloads#check_suite
- GitHub pull_request_review: https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request_review
- GitHub pull_request: https://docs.github.com/en/webhooks/webhook-events-and-payloads#pull_request
- Jira jira:issue_updated: https://developer.atlassian.com/cloud/jira/platform/webhooks/#webhook-payload-for-issue-events

Add path comparison tests that verify:
1. Synthetic events have all JSON paths adapters/triggers read
2. Real fixtures have those same paths (validates fixtures)
3. Reports paths in real but missing in synthetic (informational)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
gdsavills and others added 18 commits October 29, 2026 16:03
When all listReviews API calls fail, allReviews is empty but errors > 0.
The early return was incorrectly advancing the watermark, causing missed
reviews. Now checks result.errors === 0 before updating watermark.

Scenario: 3 PRs, all listReviews fail -> errors=3, allReviews=[].
Before: watermark advances, reviews permanently missed.
After: watermark stays, next cycle retries.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Restore 0062_polling_tables.sql to hand-written style (was overwritten
  by drizzle-kit generate with auto-generated format)
- Add IF NOT EXISTS to all CREATE statements for idempotency
- Add missing idx_polling_watermarks_project_provider index (was in
  schema but not in committed SQL)
- Add drizzle.config.ts registration of polling.ts schema
- Delete stale meta/0063_snapshot.json (repo does not track snapshots)
- Restore _journal.json formatting

Schema now matches src/db/schema/polling.ts exactly:
- polling_watermarks: UNIQUE(project_id, provider, resource_type, resource_id)
- polling_processed_events: UNIQUE(project_id, provider, dedup_key)
- Both tables: FK to projects(id) ON DELETE CASCADE
- idx_polling_processed_events_processed_at
- idx_polling_watermarks_project_provider

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
BullMQ throws "Queue name cannot contain :" at runtime. The router
crashed on start because QUEUE_NAME was 'polling:scheduler'.

Changes:
- Rename QUEUE_NAME from 'polling:scheduler' to 'polling-scheduler'
- Update scheduler.test.ts assertions to match
- Add queue-name.test.ts regression test that reads the source and
  verifies the name contains no colon

Searched src/polling for other BullMQ names with colons - none found.
The 'polling:check-suite' in check-suite-poller.ts is a logging
identifier, not a BullMQ queue/worker/scheduler name.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Extend the PollingEventType union with:
- 'pr_conflict': conflict detected, synthetic event dispatched
- 'pr_conflict_checked': PR checked clean, recorded to prevent re-check

No migration needed - the DB column is TEXT.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add optional mergeableState field to PRDetails, extracted from GitHub's
mergeable_state API response. Values: 'clean', 'dirty', 'unstable',
'blocked', 'behind', 'unknown', or null.

'dirty' indicates merge conflicts, which the pr-conflict-poller will use.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add pr-conflict-poller.ts that detects merge conflicts on open PRs:

- Receives openPRs list from PR review poller (no duplicate API call)
- Fetches base branch SHA once per distinct base branch per cycle
- Checks each (pr, head_sha, base_sha) tuple against ledger
- Only fetches PR details for unchecked tuples
- On mergeable_state === 'dirty': dispatch immediately, record as pr_conflict
- On mergeable === null or state === 'unknown': skip, retry next cycle
- On clean: batch record as pr_conflict_checked at end

Adds types for SyntheticPRConflictPayload and buildPRConflictCheckDedupKey.
Uses 'synchronize' action to trigger PRConflictDetectedTrigger without
matching other pull_request triggers.

12 unit tests covering all scenarios.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Make draft field optional (draft?: boolean) in GitHubPullRequest
- Use pr.draft ?? false in buildSyntheticPRConflictPayload
- Add test asserting draft: true flows through conflict poller payload

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Reduce the function to return only { mergeable, mergeableState } instead
of constructing a full PRDetails object. The conflict poller only needs
these two fields to decide whether to dispatch.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- pr-review-poller: Return openPRs in result for conflict poller
- pr-review-poller: Add draft: pr.draft ?? false mapping
- pr-review-poller: Increment errors on open-PR fetch failure
- scheduler: Call conflict poller with openPRs after review poller
- scheduler: Skip conflict poller when review poller failed (errors > 0)
- scheduler: Catch conflict poller exceptions to isolate failures

Tests verify openPRs passing, draft mapping, skip on failure, exception
isolation, and error counting on fetch failure.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Verifies that buildSyntheticPRConflictPayload produces payloads that
correctly dispatch through the real TriggerRegistry and reach
PRConflictDetectedTrigger without earlier triggers claiming the event.

Tests cover:
- Registry dispatch order (synchronize action, not claimed by PROpened)
- Successful dispatch with correct PR number, refs, and repo
- Gate: author mode (own) - external author skipped
- Gate: base branch mismatch - skipped
- Gate: trigger disabled - returns null
- Gate: fork PR - skipped
- Mergeable null after retries - deferred result, not agent run
- Draft PR behavior - processed normally (not skipped)

Fixtures are handwritten from documented GitHub Pull Request Event schema.
Mocks only edges: githubClient.getPR, trigger config, work-item resolver.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add a "settled head" check that defers conflict dispatch until the PR's
head SHA has remained unchanged for two consecutive poll cycles. This
prevents burning the attempt counter when a PR is being actively pushed
to (the worker rejects stale SHAs).

Implementation:
- Module-level lastSeenHeadSha map tracks head SHA per PR across cycles
- Tracking updated at top of per-PR loop (before any skip/continue)
- Dirty PRs only dispatch if previousHeadSha === current headSha
- Entries cleaned when PRs no longer in openPRs list
- Export resetSettledHeadTracking() for testing

This fixes the live bug where rapid pushes burned the conflict attempt
counter without any agent actually running.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Fixes S-1 from challenger review: the settled-head map key was
`${repoFullName}#${prNumber}` which could cause cross-project pollution
when two projects share the same repository.

Changes:
- buildSettledKey now takes projectId as first argument
- Key format: `${projectId}:${repoFullName}#${prNumber}`
- Cleanup loops use project-scoped prefix
- resetSettledHeadTracking updated to accept (projectId, repo, pr)

New tests:
- Two projects sharing repo do not share settled state
- Cleanup for project A does not remove project B's entries

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Before dispatching a dirty+settled PR for conflict resolution, check if
the work item is already locked by another resolve-conflicts run. This
prevents burning the attempt counter (max 2, in-memory) when a previous
cycle's job is still active.

Implementation:
- Call resolveWorkItemId to get Jira key from pr_work_items table
- Call isWorkItemLocked with same key derivation as checkDispatchLocks
- If locked: skip (no trigger evaluation, no ledger write), info log
- If no work item linked: proceed to dispatch (existing behavior)
- Fail-closed: if lookup throws, skip PR, count as error

New tests:
- Lock pre-check unit tests (locked, no work item, lock released, etc.)
- Contract test verifying pre-check uses same key as real dispatch

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The comment at pr-conflict-poller.ts:299 said "Fail-closed" but
resolveWorkItemId internally catches DB errors and returns undefined,
so a DB lookup failure actually skips lock protection (fail-open),
matching trigger handler behavior. The try-catch only handles
unexpected throws.

Updated the comment to describe the real behavior and renamed the
test from "(fail-closed)" to "throws unexpectedly" since it tests
the try-catch path, not DB failures.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add a 5-second overlap window constant for watermark advancement.
When advancing the watermark, we subtract this value from the cycle
start time to ensure events occurring during cycle execution are not
missed. The dedup ledger prevents duplicate processing.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Fix race condition where reviews submitted mid-cycle could be missed
when watermark advanced to cycle end time or latestReviewTime.

Changes:
- Capture cycleStart BEFORE watermark read and PR list fetch
- Set watermark = cycleStart - WATERMARK_OVERLAP_MS in ALL success paths
- Remove latestReviewTime tracking (no longer needed)
- Keep unchanged: errors > 0 prevents watermark advance, cold-start fallback

The dedup ledger prevents duplicate processing of re-seen reviews
in the overlap window.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Fix race condition where merges occurring mid-cycle could be missed
when watermark advanced to cycle end time or latestMergeTime.

Changes:
- Capture cycleStart BEFORE watermark read and PR list fetch
- Set watermark = cycleStart - WATERMARK_OVERLAP_MS in ALL success paths
- Remove latestMergeTime tracking (no longer needed)
- Keep unchanged: errors > 0 prevents watermark advance, cold-start fallback
- Keep unchanged: errors handling at lines 141-144 (fetch failure)

The dedup ledger (keyed by PR number only) prevents duplicate processing
of re-seen merges in the overlap window.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add tests that simulate two consecutive polling cycles to verify that
events occurring mid-cycle are not missed due to watermark timing.

pr-review-poller tests:
- two-cycle race: review submitted after PR list fetch is picked up next cycle
- Path C race: review on PR B submitted before PR A's review but missed in cycle 1

merged-pr-poller tests:
- two-cycle race: PR merged after list fetch is picked up next cycle

Tests use fake timers and in-memory watermark storage to precisely control
time and verify watermark persistence between cycles.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@gdsavills gdsavills closed this Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant