Skip to content

fix(enrichment): PLTF-3689 save PR stats once, count attempts up front - #586

Merged
aivong-openhands merged 11 commits into
mainfrom
task-queue/01-enrichment-guard
Oct 6, 2026
Merged

aivong-openhands merged 11 commits into
mainfrom
task-queue/01-enrichment-guard

Conversation

@aivong-openhands

@aivong-openhands aivong-openhands commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

HUMAN:

  • A human has tested these changes.

AGENT:


Why

Two runs of the PR enrichment job can overlap, for example when a stalled run is reclaimed while its process is still alive. Two defects make that unsafe. The duplicate-write guard compares updated_at, but nothing advances that column after the row is inserted, so a run that finishes second overwrites the first. And an attempt is counted only after processing, so a PR whose processing crashes every time is retried forever instead of stopping at MAX_RETRIES.

Enrichment records each closed PR once, so the first run to finish should win. Under the row lock the stats write already takes, it is now refused if the PR is already processed, and the later run writes nothing, neither the database row nor the saved PR file. The attempt is now consumed when the PR is claimed, before any work, so a crash still uses it up. The updated_at check stays, because it still catches a row that insert_pr replaced mid-run.

Summary

  • update_pr_openhands_stats refuses the write when the PR is already processed.
  • claim_pr_for_processing replaces increment_process_attempts. It consumes an attempt in a single UPDATE ... RETURNING and returns nothing for a PR that is already processed or out of attempts.
  • The job claims each PR before save_full_pr and skips it when the claim returns nothing.
  • save_full_pr returns before saving the PR file when the stats write is refused, so a losing run does not replace the winner's file.
  • process_pr returns whether it claimed the PR, and the job only logs success when it did.

Issue Number

OHE-3417 (the tracked issue; the title's PLTF-3689 is the task-queue umbrella, as on #587).

Fixes #554. The install-gitlab-webhooks half is now tracked separately in #623.

How to Test

uv run pytest tests/unit/storage/test_openhands_pr_store.py tests/unit/sync/test_enrich_user_interaction_data.py tests/unit/integrations/github/test_data_collector_save_full_pr.py (the Python Tests on Linux CI job also runs them). Against a real database, the tests check that:

  • of two overlapping runs that read the same row, whichever commits first is kept and the other writes nothing, in either commit order and with the commits racing;
  • a run that read a row insert_pr has since replaced writes nothing;
  • the attempt is already counted when processing starts, and a PR that fails on every run stops after MAX_RETRIES;
  • a run working from a stale list of unprocessed PRs skips one another run has already finished;
  • a run whose stats write is refused leaves the winner's saved PR file in place.

Every writer of OpenhandsPR.updated_at was also checked. Only insert_pr changes it, by deleting and re-inserting the row. The column has no onupdate, and no migration adds a trigger to openhands_prs.

Video/Screenshots

N/A. No UI change.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

No migration or config change.


This PR was drafted by an AI agent on behalf of the user.

@aivong-openhands can click here to continue refining the PR


Enterprise server image for this PR:

ghcr.io/openhands/enterprise-server:sha-063247f

@github-actions

github-actions Bot commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  integrations/github
  data_collector.py
  storage
  openhands_pr_store.py 106-107
  sync
  enrich_user_interaction_data.py
Project Total  

This report was generated by python-coverage-comment-action

@aivong-openhands
aivong-openhands changed the base branch from task-queue/00-alembic-single-head to main September 30, 2026 06:14
@aivong-openhands
aivong-openhands force-pushed the task-queue/01-enrichment-guard branch from bf86e6e to dfa97bc Compare September 30, 2026 06:14
…claim

update_pr_openhands_stats guarded concurrent writes with
updated_at != original_updated_at, but updated_at has no onupdate, so a
successful write never advanced it and the guard could not see a
concurrent commit. Refuse the write under the existing row lock when the
PR is already processed.

increment_process_attempts ran after processing, so a crash loop never
exhausted MAX_RETRIES. Replace it with claim_pr_for_processing, which
consumes the attempt atomically before any work.

OHE-3417 (Track 1, T1.4)

Co-authored-by: openhands <openhands@all-hands.dev>
@aivong-openhands
aivong-openhands force-pushed the task-queue/01-enrichment-guard branch from dfa97bc to f61d0bb Compare October 2, 2026 01:43
@aivong-openhands aivong-openhands changed the title fix(enrichment): first successful completion wins; count attempts at claim fix(enrichment): PLTF-3689 save PR stats once, count attempts up front Oct 2, 2026
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review: test strength

I broke the changed code by hand, one mutant at a time, and ran the two test files this PR adds against a real Postgres each time. Baseline: 10 passed.

Controls (revert the fix; these must fail)

Mutant Result
C1: drop pr.processed or from the stats-write guard, so the second finisher overwrites ❌ caught
C2: count the attempt after save_full_pr instead of before ❌ caught
C3: claim ignores process_attempts < max_retries ❌ caught

Also caught: the claim ignoring ~processed, an off-by-one <= on the retry cap, the claim never committing, and the stats write dropping the updated_at check. The suite holds up because it checks the persisted row, not return values alone. _load() re-reads process_attempts and the num_openhands_* columns, and test_attempt_is_counted_before_processing reads the DB from inside save_full_pr. That makes the ordering claim directly observable.

Survivors

Mutant Result
M6: update_pr_openhands_stats drops .with_for_update() ✅ 10 passed
M4: claim drops the pr_number == pr_number filter ✅ 10 passed
M3: claim drops the repo_id == repo_id filter ✅ 10 passed
M7: process_pr passes the scanned pr to save_full_pr instead of claimed ✅ 10 passed

M6: the row lock is not pinned

"First successful completion wins" between runs that truly overlap depends on with_for_update(). Without it, two runs can both read processed = False and both write, which is the bug this PR fixes. test_concurrent_commits_admit_exactly_one is meant to cover this, but it still passed 5 out of 5 times with the lock removed, so the four gathered calls don't actually interleave in this setup. One way to force the overlap is to hold the row lock yourself:

async def test_write_waits_for_a_finisher_holding_the_row(self, store):
    """A run that already holds the row and commits first must win."""
    await _insert_pr(store)
    original = (await _load()).updated_at

    async with a_session_maker() as holder:
        row = (
            await holder.execute(select(OpenhandsPR).with_for_update())
        ).scalars().one()
        late = asyncio.create_task(_record(store, original, commits=2))
        await asyncio.sleep(0.2)
        row.processed = True
        row.num_openhands_commits = 1
        await holder.commit()

    assert await late is False
    assert (await _load()).num_openhands_commits == 1

With the lock in place, late blocks on its SELECT ... FOR UPDATE, then sees processed = True and backs off. Without the lock, it reads the old row, waits on the row lock only at UPDATE, and overwrites the holder's write. The sleep only gives the mutant time to reach its UPDATE. The correct code can't flake on it, because it blocks until the holder commits.

M3 / M4: the claim's scope is not pinned

Every claim test inserts exactly one PR, so the WHERE can match too many rows and nothing notices. If the pr_number filter were lost, a single claim would use up an attempt on every unprocessed PR in the repo. Those PRs would hit MAX_RETRIES without ever being processed. If the repo_id filter were lost, PR #N would be claimed in every repo at once, and .first() could hand save_full_pr a PR from the wrong repo. A neighbour row of each kind kills both mutants:

async def test_claim_touches_only_the_named_pr(self, store):
    await _insert_pr(store)
    await _insert_pr(store, repo_id='other-repo')
    await _insert_pr(store, pr_number=PR_NUMBER + 1)

    claimed = await store.claim_pr_for_processing(REPO_ID, PR_NUMBER, MAX_RETRIES)

    assert claimed is not None
    assert (claimed.repo_id, claimed.pr_number) == (REPO_ID, PR_NUMBER)
    async with a_session_maker() as session:
        rows = (
            await session.execute(
                select(
                    OpenhandsPR.repo_id,
                    OpenhandsPR.pr_number,
                    OpenhandsPR.process_attempts,
                )
            )
        ).all()
    assert sorted(rows) == sorted(
        [
            (REPO_ID, PR_NUMBER, 1),
            ('other-repo', PR_NUMBER, 0),
            (REPO_ID, PR_NUMBER + 1, 0),
        ]
    )

M7: save_full_pr(claimed) is not pinned

Passing the claimed row rather than the scanned one matters when insert_pr replaces the row between the scan and the claim. save_full_pr passes openhands_pr.updated_at as original_updated_at. With the scanned object, that timestamp is stale, so the stats write is refused and the attempt is wasted. This one costs the least in production, but it is one line to pin (it also needs import asyncio in this file):

async def test_processing_uses_the_claimed_row_not_the_stale_scan():
    """insert_pr replaced the row after the scan; enrichment must see the current one."""
    await _insert_pr(1)
    [stale] = await job.get_unprocessed_prs()
    await asyncio.sleep(0.01)
    await _insert_pr(1)
    async with a_session_maker() as session:
        current = (await session.execute(select(OpenhandsPR))).scalars().one()
    assert current.updated_at != stale.updated_at

    save = AsyncMock()
    with patch.object(job.data_collector, 'save_full_pr', save):
        await job.process_pr(stale)

    [saved] = save.await_args.args
    assert saved.updated_at == current.updated_at

Verified: with all three tests added, the PR branch passes (13 passed; the lock test passed 5 out of 5 repeat runs). Each mutant is then killed by exactly the test written for it, and no other test fails.

Not a test gap

  • update_pr_openhands_stats: logger.warning('Did not find PR {pr_number} for repo {repo_id}') is missing its f prefix, so the braces are logged literally. This predates the PR but sits in the function it edits.

This comment was generated by an AI assistant on behalf of the user.

Kill surviving mutants from the mutation review: the stats write must wait on a row lock held by a finisher, the claim must touch only the named PR, and process_pr must hand the claimed row (not the stale scan) to save_full_pr. Also add the missing f-prefix on the 'Did not find PR' warning.

Co-authored-by: openhands <openhands@all-hands.dev>
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Addressed the mutation review in fdc840d.

Finding Fix Mutant re-run
M6: .with_for_update() not pinned test_write_waits_for_a_finisher_holding_the_row in TestUpdatePrOpenhandsStats ❌ caught
M3: claim's repo_id filter not pinned test_claim_touches_only_the_named_pr in TestClaimPrForProcessing ❌ caught
M4: claim's pr_number filter not pinned same test ❌ caught
M7: save_full_pr(claimed) not pinned test_processing_uses_the_claimed_row_not_the_stale_scan ❌ caught
Missing f prefix on the "Did not find PR" warning made it an f-string n/a

Each mutant was applied on top of the new commit and failed exactly the test named next to it. No source behaviour changed apart from the log line.

Verified: uv run pytest -q -p no:randomly tests/unit/storage/test_openhands_pr_store.py tests/unit/sync/test_enrich_user_interaction_data.py gives 13 passed against the Postgres testcontainer, and pre-commit passes on the changed files. On this head, Lint python has passed and Python Tests on Linux is still running.


This comment was generated by an AI assistant on behalf of the user.

@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Code review: #586, head fdc840d

Verdict: approve with nits. I found nothing that blocks the merge. The patch does what the PR says, and the two notes below are optional.

Taste: good. The fix is small and keeps the existing store and job pattern. It uses a single atomic UPDATE … RETURNING to claim a PR and adds one predicate to the stats write, which already holds the row lock.

What I checked

  • Claim is atomic. claim_pr_for_processing (storage/openhands_pr_store.py:35-61) puts both conditions, not processed and attempts below the limit, in the WHERE of one UPDATE. In Postgres at READ COMMITTED, a competing UPDATE waits for the row lock and then re-checks the WHERE against the committed row. So two claims cannot both take the last attempt. A claim that arrives while a stats write holds the lock sees processed=True and gets None.
  • First to finish wins. At openhands_pr_store.py:109, SELECT … FOR UPDATE returns the latest committed row, and the write is refused if processed is already set. The updated_at check still catches a row that insert_pr replaced mid-run. I confirmed insert_pr is the only thing that changes updated_at: the model has no onupdate, and migration 050 adds no trigger.
  • Crash loop now ends at MAX_RETRIES. Under the old code, an exception from save_full_pr (for example from _get_repo_node_id) skipped increment_process_attempts, so the PR was retried forever. The attempt is now counted before any work. The early-return paths inside save_full_pr counted an attempt before and still do, so their behaviour is unchanged.
  • Handing the claimed row to save_full_pr(claimed) is safe. The async session maker uses expire_on_commit=False (openhands/app_server/services/db_session_injector.py:279), so the row returned after commit is detached but still loaded. The claim does not change updated_at, so the later original_updated_at comparison still lines up.
  • No one else uses the removed method. Nothing in the repo still calls increment_process_attempts. The only other caller of update_pr_openhands_stats is integrations/github/data_collector.py:574, and its return value is only logged.
  • The claim not filtering on provider is fine. The only place that creates OpenhandsPR rows is data_collector.py:648, and it always sets provider to GitHub.
  • Duplicate rows behave better than before. There is no unique constraint on (repo_id, pr_number), so duplicates are possible. The old code only ever incremented one of them. The new UPDATE increments every match, so even duplicates stop at MAX_RETRIES.
  • Tests and lint pass locally. 13 tests passed against the Postgres testcontainer, and pre-commit (ruff, ruff format, mypy) passed on all four files. On this head, CI Lint python has passed and Python Tests on Linux was still running at the time of posting.

Nits (non-blocking)

  1. The losing run still overwrites the saved PR file (integrations/github/data_collector.py:584-595).
    • When update_pr_openhands_stats returns False, save_full_pr only logs a warning. It then still calls self._save_data(file_name, data), and the file name depends only on the repo and PR number.
    • So the run that finishes second replaces the winner's file. The PR description's "the later run writes nothing" is true of the database row, not of this file.
    • Both runs fetched the same closed PR, so the contents are almost always the same. That is why this is not a correctness bug, but the database stats and the file can come from different runs.
    • Fix: either return after the warning when update_success is False, or change the description to say the guard covers the database row only.
  2. A skipped PR is still logged as processed (sync/enrich_user_interaction_data.py:60-63).
    • When the claim returns None, process_pr logs "Skipping…" and returns normally. main() then logs "Successfully processed PR #…" for that same PR, which is confusing when reading logs during an overlap.
    • Fix: have process_pr return a bool and log success only when the PR was claimed, or move the success log into process_pr after save_full_pr.

Taking two overlapping runs should not cost more attempts than the job can afford. Each run's claim uses up one attempt, so an overlap spends 2 of the 3 allowed. With MAX_RETRIES = 3 that leaves one more try, so I don't count it as a finding.

[RISK ASSESSMENT]

[Overall PR] ⚠️ Risk Assessment: 🟢 LOW

The change is limited to one sync CronJob and its store, with no migration, config, dependency or API change. The concurrency rules are enforced by Postgres row locks and the UPDATE re-check, and the tests run against a real database.

Verdict: approve with nits.

Key insight: the work is now guarded twice, at claim time and at write time. The claim stops runs from starting on a finished PR and caps the attempts, and the check under the lock decides which run's stats are kept. Neither check depends on the other being in place.

Improve this review? If feedback seems incorrect or irrelevant, update the repository's .agents/skills/custom-codereview-guide.md (with the /codereview trigger), then re-request review. The reviewer reads the guide from the PR head.

Resolve with AI? Install the iterate skill and run /iterate.

Was this review helpful? React with 👍 or 👎.


This review was generated by an AI assistant (OpenHands) on behalf of the user.

aivong-openhands and others added 2 commits October 1, 2026 23:06
Keep the winner's saved PR file when the stats write is refused, and
report the outcome of process_pr so a skipped PR is not logged as
processed.

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Contributor Author

Both nits addressed in 18cce17.

  1. Losing run no longer overwrites the saved PR file. save_full_pr returns after the warning when update_pr_openhands_stats returns False, so a run that loses the row-lock race leaves the winner's prs/github/{repo}-{pr}/data.json untouched. Added tests/unit/integrations/github/test_data_collector_save_full_pr.py, which asserts the file is written on a successful stats write and not written when the write is refused. I confirmed the second test fails without the guard.
  2. A skipped PR is no longer logged as processed. process_pr now returns a bool and main() only logs "Successfully processed" when the PR was actually claimed. Extended the sync tests to assert the return value on both the claimed and skipped paths.

uv run pytest tests/unit/sync tests/unit/storage tests/unit/integrations/github passes (613 tests); ruff and mypy are clean on the changed files.

This comment was generated by an AI agent (OpenHands) on behalf of the user.

The docstring claimed True meant the PR was enriched, but it means the
claim succeeded; an overlapping run that loses the stats write still
returns True.

Co-authored-by: openhands <openhands@all-hands.dev>
Say claiming reserves an attempt rather than implying exclusive ownership,
and state that the first stats write to commit is the one kept.

Co-authored-by: openhands <openhands@all-hands.dev>
The test asserted a successful claim, not completed enrichment; the old
wording was removed from process_pr in c23b2ed.

Co-authored-by: openhands <openhands@all-hands.dev>

Copy link
Copy Markdown
Contributor Author

Code review: #586, head c205dcb

Taste: good. This is a small fix that follows the existing store and job pattern. A single atomic UPDATE … RETURNING claims the PR, and the stats write, which already holds the row lock, gets one extra predicate.

I found no material issues on this head. The two nits from the previous review (fdc840d) were both fixed in 18cce17, and I confirmed the fixes in the code:

  • integrations/github/data_collector.py:588: save_full_pr now returns when the stats write is refused, so the run that loses doesn't overwrite the saved PR file.
  • sync/enrich_user_interaction_data.py:66: "Successfully processed" is now logged only when process_pr actually claimed the PR.

What I checked

  • Claim is atomic and capped. claim_pr_for_processing puts ~processed and process_attempts < max_retries in the WHERE of one UPDATE. In Postgres at READ COMMITTED, a competing UPDATE waits for the row lock and then checks the WHERE again against the committed row. Two claims therefore can't both take the last attempt, and the lost-increment bug from enrich-user-interaction isn't safe to run concurrently #554 is gone.
  • First to finish wins. SELECT … FOR UPDATE followed by pr.processed or pr.updated_at != original_updated_at refuses both a later finisher and a row that insert_pr replaced. updated_at is set only by server_default, with no onupdate and no trigger, so insert_pr is still the only thing that changes it.
  • Claimed row handoff. save_full_pr(claimed) uses the row from RETURNING, so original_updated_at matches the current row even if insert_pr replaced it after the scan. The session maker uses expire_on_commit=False (db_session_injector.py:279), so the detached object is still fully loaded.
  • Callers. Nothing still references increment_process_attempts. save_full_pr is called only from the enrichment job, and the update_pr_openhands_stats result is only used for the early return.
  • Tests. They run against the real Postgres fixtures, as AGENTS.md requires. Only GitHub and the file store are stubbed. The row-lock test holds FOR UPDATE in a separate session, so it fails if .with_for_update() is removed. The claim-scope test seeds neighbouring rows from another repo and with another PR number. The crash-loop test drives main() across MAX_RETRIES + 2 runs.
  • CI on c205dcb. Every check passes, including Python Tests on Linux (3.12) (6833 passed), Lint python, and both image builds.

Acceptance criteria (#554)

  • The attempt is counted at claim time in a single UPDATE … RETURNING, and the claim returns nothing for a PR that is processed or out of attempts.
  • The stats write is refused under the row lock if the PR is already processed.
  • The losing run writes nothing: neither the row nor the saved PR file.
  • The attempt cap holds under overlap (atomic increment), and a crash loop stops at MAX_RETRIES.

Non-blocking observation (no change requested)

A PR that raises a transient exception (for example a network error in _get_repo_node_id) used to be retried indefinitely. It is now dropped for good after 3 runs, about 30 minutes at the 10-minute schedule. #554 intends this, but it changes behaviour during flaky-GitHub periods, and the only way to recover is to reset process_attempts by hand.

[RISK ASSESSMENT]

[Overall PR] ⚠️ Risk Assessment: 🟢 LOW

The change only touches one peripheral CronJob, its store, and the file-save guard. It adds no migration, config, dependency, API, or auth change. Postgres row locks and the UPDATE re-check enforce the concurrency rules, and tests exercise them against a real database.

Verdict: worth merging. Nothing blocks it. GitHub won't let this account approve its own PR, so this is posted as a comment. The PR is still a draft, and the "A human has tested these changes" box is unchecked. Those are left to the author.

Key insight: the PR now has two separate guards. The claim decides whether a run may start and enforces the attempt cap. The check under the lock decides whose result is kept. Neither guard relies on the other, so the job stays correct even without concurrencyPolicy: Forbid.


This review was generated by an AI agent (OpenHands) on behalf of the user.

@aivong-openhands
aivong-openhands marked this pull request as ready for review October 2, 2026 15:34
@aivong-openhands

aivong-openhands commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author
  • Test in replicated for no regression check

@aivong-openhands

aivong-openhands commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor Author

Replicated no-regression test — ✅ PASS

Tested this PR's enterprise-server image (enterprise-server:sha-aa9aa5a) through a full fresh Replicated install to confirm no regression to the shipped self-hosted product.

Setup

  • Built an OpenHands-Cloud release from a clean main with a single change: the enterprise-server image pinned to this PR's build (sha-aa9aa5a).
  • Fresh install on a clean embedded-cluster VM: external Postgres, GitLab OAuth, Anthropic LLM, legacy hostname layout.

Results

Check Result
Release build + lint + promote ✅
Host preflights ✅
Admin Console + embedded cluster install ✅
openhands deployment rollout ✅
Running image == PR build (sha-aa9aa5a) ✅
App reachable + GitLab login + TOS ✅
End-to-end conversation ("do a flip") ✅ agent replied, flip completed
App pod startup — tracebacks / import errors ✅ none

Scope note

The closed-PR enrichment job that this PR changes is disabled by default in the self-hosted product (the cronjob is gated off) and depends on a configured GitHub App, which a GitLab-based install does not have. So this test validates that the PR's image does not regress install, auth, or the conversation flow — it does not exercise the enrichment concurrency-guard fix itself, which is covered by the PR's DB-backed unit/integration tests.

Conclusion: No regression observed. ✅


This comment was posted by an AI agent (OpenHands) on behalf of @aivong.

Copy link
Copy Markdown
Contributor Author

Impact assessment

Verdict: Only SaaS prod and feature previews behave differently, plus any OHE install that turned the PR-enrichment job on by hand. OHE / Replicated defaults, staging and dev are unaffected. The only opt-out is enrichUserInteractionData.enabled=false. MAX_RETRIES=3 is hard-coded.

Result Deployment Enrichment job / COLLECT_GITHUB_INTERACTIONS Retries / overlapping runs (before → after)
🟡 changed SaaS prod / feature job on / true PR that crashes every run: retried forever → stops after 3; overlap: the run that finishes last wins → the run that finishes first wins
🟡 changed OHE Helm, job manually enabled enabled: true + env set via extraEnvVars same as SaaS prod
🟢 unchanged SaaS staging job on / unset empty table, so the job does nothing
🟢 unchanged SaaS dev job off —
🟢 unchanged OHE / Replicated default job not rendered (enabled: false, no KOTS option) —

Validation: The diff and call sites were read statically at 1434989. The PR's 16 tests were run locally against Postgres 16 and all passed; CI is also green. SaaS inputs come from the saas-deploy environment values, and OHE inputs from the OpenHands-Cloud chart, replicated/openhands.yaml and the OpenHands-Charts defaults. Nothing was checked against live systems, including staging's table contents and prod's count of PRs that fail on every run.

Customer installs:

  • Both charts ship enrichUserInteractionData.enabled: false, and KOTS has no option to turn it on, so the CronJob doesn't exist on Replicated installs.
  • The PR table only fills when COLLECT_GITHUB_INTERACTIONS=true, and no chart sets that. Even with the job on, it finds nothing to process unless that env var is also added.
  • There is no schema change, migration or new config.

Rollout: SaaS prod and feature previews get this with the next enterprise-server image bump. PRs that currently fail on every run will use up their 3 attempts within about 30 minutes (three 10-minute runs). After that they stay unprocessed until someone resets process_attempts by hand. Both charts set concurrencyPolicy: Forbid, so runs rarely overlap today. The "first run to finish wins" rule mainly prepares for the PLTF-3689 task queue.

Changed symbols and call sites
  • OpenhandsPRStore.claim_pr_for_processing (new; replaces increment_process_attempts): sync/enrich_user_interaction_data.py:40. No other callers. quint-specs/quint.lock:1230,1251,1254 still names the old method and is now out of date.
  • OpenhandsPRStore.update_pr_openhands_stats now refuses the write if the PR is already processed: integrations/github/data_collector.py:574, its only caller.
  • GitHubDataCollector.save_full_pr: if the stats write is refused, it now returns before writing the PR JSON to the file store. Its only caller is sync/enrich_user_interaction_data.py:49, which now passes the freshly claimed row, so the updated_at check compares against claim time.
  • process_pr now returns bool, and main() logs success only when the run claimed the PR.
  • Exceptions inside save_full_pr, such as a DB or file-store error or a bug in the counting or building code, now use up an attempt; before, they didn't. GitHub errors (token, GraphQL) were already caught and counted.
  • Rows are unique on (repo_id, pr_number) (migration 050), so the new UPDATE … RETURNING claim touches at most one row. Sessions use expire_on_commit=False, so the returned row can still be read after commit.
  • CronJob wiring:
    • OpenHands-Cloud charts/openhands/templates/enrich-user-interaction-cronjob.yaml
    • OpenHands-Charts charts/openhands-umbrella/charts/openhands/templates/enrich-user-interaction-cronjob.yaml
    • Enabled in saas-deploy production, staging and feature.

This analysis was produced by an AI agent (OpenHands) on behalf of @aivong-openhands.

@aivong-openhands
aivong-openhands merged commit ec3c23f into main Oct 6, 2026
18 checks passed
@aivong-openhands
aivong-openhands deleted the task-queue/01-enrichment-guard branch October 6, 2026 19:13
@openhands-release-bot openhands-release-bot Bot added the released: 1.69.0 Shipped in 1.69.0 label Oct 6, 2026
@openhands-release-bot

Copy link
Copy Markdown
Contributor

🚀 Released in 1.69.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released: 1.69.0 Shipped in 1.69.0 type: fix A bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

enrich-user-interaction isn't safe to run concurrently

3 participants