Skip to content

CROSSLINK-360 Recover interrupted batch runs and support manual reruns - #892

Open
JanisSaldabols wants to merge 5 commits into
mainfrom
codex/crosslink-360-batch-recovery
Open

JanisSaldabols wants to merge 5 commits into
mainfrom
codex/crosslink-360-batch-recovery

Conversation

@JanisSaldabols

Copy link
Copy Markdown
Collaborator

Summary

  • Reserve pull-slip email, request-aging, and overdue runs by owner and action across broker replicas. Keep the reservation until their background and inline work finishes.
  • Claim batch work atomically with a Postgres lease. Recover expired tasks as errors and fence late writes, child creation, and completion. Keep healthy sibling work running.
  • Let staff rerun a saved action by POSTing to its runLink after recovery. Scheduled actions pick up at the next occurrence.
  • Bound the SMTP exchange and delegated ISO 18626 waits. A later run can repeat an email if the broker was interrupted after SMTP had accepted it.

Stop older broker replicas before applying migration 083. The operator and deployment procedures are in the broker README.

Verification

  • Full broker, HTTP client, and illmock Go checks
  • Race checks for scheduler recovery, the event bus, SMTP, and ISO 18626 confirmation
  • Broker build and FOLIO OpenAPI lint
  • Postgres migration down/up round-trip
  • Bruno happy-flow and recall scenarios, 86 requests passed

The standalone coverage checker rejects the existing local-prefix key in the broker coverage configuration. The broker tests generated a coverage profile.

Copilot AI balanced review requested due to automatic review settings November 25, 2026 14:11

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical lifecycle gaps leave late-confirmation tasks unfinished and local message tasks and inline actions outside worker recovery, blocking archiving and subsequent actions after interruption.

2 open issues
What changed in this PR

This PR adds durable batch-run recovery to the broker scheduler, coordinating work across replicas and allowing staff to rerun interrupted saved actions.

Changes:

  • Adds owner/action reservations, worker leases, recovery, and protection against writes from expired workers.
  • Exposes manual runLink URLs and documents recovery and upgrade procedures.
  • Bounds external exchanges, paginates overdue selection, and adds recovery and concurrency tests.
File Description
httpclient/​httpclient.go Adds context-aware HTTP exchanges.
broker/​test/​scheduler/​service/​batch_run_test.go Tests overlapping-run reservations.
broker/​test/​scheduler/​service/​batch_recovery_test.go Tests recovery, leases, and worker draining.
broker/​test/​events/​eventbus_test.go Uses synchronized event capture and tests reconnection.
broker/​sqlc/​pr_query.sql Adds paginated overdue candidate selection.
broker/​sqlc/​event_schema.sql Defines run and worker-lease storage.
broker/​sqlc/​event_query.sql Adds reservation, lease, and recovery queries.
broker/​service/​workflow.go Propagates worker context into workflow tasks.
broker/​scheduler/​service/​scheduler.go Skips conflicting scheduled occurrences.
broker/​scheduler/​service/​scheduler_test.go Tests dispatch around conflicting runs.
broker/​scheduler/​service/​overdue.go Pages candidates and scopes child-task creation.
broker/​scheduler/​service/​email_sender.go Bounds SMTP and scopes follow-up tasks.
broker/​scheduler/​service/​email_sender_test.go Updates repository mocks for candidate selection.
broker/​scheduler/​service/​batch_action.go Scopes request-aging child tasks.
broker/​scheduler/​db/​repo.go Atomically reserves and queues batch runs.
broker/​scheduler/​api/​api_handler.go Returns conflict responses and manual-run links.
broker/​scheduler/​api/​api_handler_test.go Verifies manual-run links.
broker/​repo/​batch_worker.go Adds lease-aware contexts and write guards.
broker/​README.md Documents recovery, reruns, limits, and deployment.
broker/​patron_request/​service/​message_sender.go Scopes message-log event creation.
broker/​patron_request/​service/​action.go Propagates leases through actions and email.
broker/​patron_request/​db/​prrepo.go Guards batch-originated persistence writes.
broker/​patron_request/​db/​overdue_candidates.go Implements lightweight overdue pagination.
broker/​oapi/​open-api.yaml Documents run links and reservation conflicts.
broker/​ncipclientv1/​client.go Adds context-aware NCIP v1 exchanges.
broker/​ncipclient/​ncipclient_impl.go Adds context-aware NCIP exchanges.
broker/​migrations/​083_batch_worker_leases.up.sql Creates lease storage and marks legacy interruptions.
broker/​migrations/​083_batch_worker_leases.down.sql Removes lease storage and its lock function.
broker/​lms/​lms_creator_impl.go Passes caller context into LMS adapters.
broker/​lms/​lms_adapter_ncip1.go Creates context-aware NCIP v1 clients.
broker/​lms/​lms_adapter_ncip.go Creates context-aware NCIP v2 clients.
broker/​ill_db/​illrepo.go Guards batch-originated transaction writes.
broker/​ill_db/​archive.go Guards batch archive mutations.
broker/​handler/​request_wait_test.go Tests channel-based waiters and cancellation.
broker/​handler/​iso18626-handler.go Bounds confirmation waits and scopes notices.
broker/​events/​eventmodels.go Adds worker signals and delegated lease metadata.
broker/​events/​eventbus.go Integrates run tracking and guarded task lifecycles.
broker/​events/​batch_worker.go Implements worker claims, renewal, recovery, and draining.
broker/​email/​smtp.go Implements bounded SMTP with DATA-based acceptance.
broker/​email/​smtp_test.go Tests SMTP acceptance and stalled exchanges.
broker/​email/​email.go Adds context-aware email dispatch.
broker/​client/​client.go Makes ISO HTTP delivery and delays cancellable.
broker/​app/​app.go Coordinates scheduler shutdown and worker draining.

Review effort: Balanced

Comment thread broker/events/eventbus.go Resolved
Comment thread broker/handler/iso18626-handler.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

An expired or cleared worker lease can leave notice signals permanently blocking transaction archiving, while incomplete migration cleanup leaves legacy local-message actions stranded and blocking later exclusive actions.

1 open issue
1 previously missed issue

In code that hasn't changed since last review

Medium severity Clean up legacy local-message tasks and inline actions during migration

broker/​migrations/​083_batch_worker_leases.up.sql:88

If an older broker stops during a local message’s automatic action, migration 083 leaves the detached patron-request-message task and its invoke-action descendants unfinished without lease records. The surviving action blocks later exclusive actions on that request, and the new recovery loop cannot discover it. Extend upgrade cleanup to cover these legacy local-message tasks and their inline actions after old replicas stop, with a regression fixture for the disconnected ancestry.

2 resolved since last review

Review effort: Balanced

Comment thread broker/events/eventbus.go Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@jakub-id jakub-id left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this follows the agreed plan closely. The polled queue with 8 workers and the shared worker leases are improvements on it. Below are the changes I'd like to see before merging.

Must fix

  1. Frozen deadline: repo.BatchIOContext(ctx) at the top of executeAction (patron_request/service/action.go:280) freezes the lease deadline for the whole action and its inline auto-actions. A chain that runs longer than that deadline fails even though the lease is still being renewed, which is likely with a short BATCH_WORKER_LEASE. Drop it there and rely on the worker context, which is already cancelled at the live deadline.
  2. Lease renewal gives up too early: a single transient error in RenewBatchWorkerLease (events/batch_worker.go:180-185) stops renewal for good, and the worker is lost with two thirds of the lease left. Retry until the deadline, and give up only on ErrNoRows or an expired deadline.
  3. Down migration: batch events still NEW are stranded after a rollback, and HasActiveBatchActionEvents then blocks deleting the task forever. Mark NEW/PROCESSING batch events as ERROR before dropping the tables.
  4. Overdue filter can vanish: in overdue_candidates.go:19, if strings.Replace(sql, "ORDER BY id", ...) finds no match, the CQL filter is silently dropped. Return an error when the marker is missing, as prcql.go:261 does.
  5. ISO confirmation wait: it is now 30s, where ordinary ISO 18626 traffic effectively had 60s before (the server write timeout). A peer answering in 30–60s now gets a 500 and may retry, sending a duplicate. Use about 55s, and log a WARN on timeout. Raise the message_confirmation_expiry default in 083 (INTERVAL '1 minute') and event_schema.sql at the same time, to about 2 minutes. Otherwise expiry can race a live waiter.

Please decide

  • Fencing on every write (lock_batch_worker / BatchWrite in prrepo, illrepo and archive): the plan dropped this.

    • The handler ctx is already cancelled before the lease expires in the DB.
    • Coverage is partial: DeletePatronRequest, UpdatePatronRequestInternalNote, DeletePeer and the pull-slip writes are not fenced.
    • It adds a lock per write.
    • It hides a self-deadlock rule: no second pooled connection may touch the worker row inside a fenced transaction.

    I'd keep the lease check only in the event bus.

  • How abandoned tasks complete: finishAbandonedWorkerEvents completes expired tasks with SignalConsumers. This causes two problems:

    • For expired message-supplier/message-requester tasks, it runs the workflow's on-complete handlers as if the send had failed.
    • It leaves last_signal = 'task_complete' to be cleared by NOTIFY. If that NOTIFY is missed, for example during a listener reconnect, archiving stays blocked.

    I'd complete them silently (ERROR, last_signal = ''), as ExpireMessageConfirmationTasks does, and add a test.

Smaller

  • Include the blocking run ID and start time in the 409 message and in the skip log.
  • Add event_status = 'NEW' to the claim update (batch_worker.go:233).
  • Add a nil-ctx guard in ncipclientv1/client.go:67, as ncipclient_impl.go has.
  • Make the SMTP timeout configurable. 30s is tight for large pull-slip PDFs on relays that scan attachments.
  • Tests: let a short lease really expire, instead of editing lease_expires_at. Also cover:
    • a renewal failure or the cap cancelling the handler;
    • a drain where the handler finishes in time;
    • overdue paging across more than one page.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@jakub-id

Copy link
Copy Markdown
Contributor

Thanks for the fixes, all points from my previous review are addressed. Two remaining issues, both about keeping recovery generic so a new batch action gets it without extra code:

  1. Overlap protection is opt-in. QueueBatchActionRun (scheduler/db/repo.go:195) checks conflicts only for EmailPullslips, RequestAging and Overdue. A new action gets no protection unless someone adds it to the switch. Please invert it: check every action by default and exempt the archive actions explicitly, with a comment on why (atomic per-resource SQL, no external side effects).

  2. Linking children to the run depends on every call site. Each path that creates a child must wrap the bus in events.WithWorkerContext(...) (batch_action.go, email_sender.go, overdue.go, action.go, message_sender.go, workflow.go). If one forgets, the child isn't linked: the run can be released while it is still running, and recovery never sees it. The event bus also hard-codes which event names belong to a run (eventbus.go:243-283, batchOwnershipRequired). The plan dropped this plumbing. Instead, CreateTask should link a child to its parent's run whenever the parent belongs to one, and the local-message path should pass the parent ID rather than rely on ctx. That should remove the WithWorkerContext calls and the event-name lists, and probably most of the delegated-lease code too.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing. Review the Copilot code review billing settings.

@jakub-id jakub-id left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, all points from my earlier review and follow-up comment are addressed. One change remains before I can approve. It's a scope reduction, not a new feature.

Problem. The batch run now also tracks the ISO 18626 events that an action waits on:

  • the supplier-msg-received/requester-msg-received notice;
  • message-requester/message-supplier;
  • confirm-*;
  • the other request's patron-request-message.

Any replica can process these events. Tracking them is what requires:

  • the delegatedBatchContext lease polling;
  • the creation-signal ownership path in handleNotify;
  • waitForBatchDependents;
  • the in-process completion callbacks in completeTask.

The run doesn't need them:

  • The batch worker dies: these events keep running on their own replicas. A confirm task with no waiter is cleaned up by message_confirmation_expiry.
  • Their own replica dies: they block later actions on that one other request, not the batch run. The same is already true on main for every CrossLink-to-CrossLink message, including staff-triggered ones. That needs a general fix, so I'll open a separate ticket.
  • Completion consumers: they exist only for the ISO workflow tasks (app.go:448-452). The batch, background, invoke-action and patron-request-message tasks have none.

Rule. A batch run contains only:

  • the invoke-batch-action task;
  • the tasks it queues (invoke-background-action);
  • the inline tasks those create (invoke-action, via SignalInline).

Linking stops at the ISO 18626 handler. Notices are never linked to a run.

Remove

  1. patron_request/service/message_sender.go: stop passing a parent ID into HandleSupplyingAgencyMessage, HandleRequestingAgencyMessage and HandleRequest. Delete messageParentID.
  2. handler/iso18626-handler.go:
    • Remove RequestOptions.ParentEventID.
    • Remove the parentID parameters on HandleRequestingAgencyMessage, HandleSupplyingAgencyMessage, their handle* and handle*ErrorWithNotice helpers, createNotice and waitForMessageConfirmation. Revert the interface to match.
  3. client/client.go and patron_request/service/message-handler.go:
    • Remove the parentID parameter from HandleIllMessage, HandleMessage, handlePatronRequestMessageWithPeer, handleRequestMessageWithPeer and processPatronRequestMessageTask.
    • patron-request-message is created with a nil parent, as on main.
  4. events/eventbus.go, notice creation:
    • Remove the parentId parameter from CreateNoticeWithID.
    • In CreateNoticeWithID/CreateNoticeWithParent, drop batchParent, addBatchEvent and the observer-only FinishBatchRunEvent branch. Notices are never run members.
  5. events/eventbus.go, handleNotify: drop the GetEventForCreationSignal lookup, finishNotice, the delegatedBatchContext branch and the legacy BatchWorkerID fallback. Load the event and claim it as on main.
  6. events/eventbus.go, completeTask: drop the in-process completion callbacks. In one transaction:
    • save the result;
    • for a run member, finish its membership and release the run if idle;
    • for a run member, leave last_signal empty and notify observers only if the target includes them;
    • for a non-member, keep the normal Notify.
  7. events/batch_worker.go: delete delegatedBatchContext, waitForBatchDependents and the call in runBatchWorker.
  8. events/eventmodels.go: delete EventData.BatchWorkerID. It was never on main, so no compatibility path is needed.
  9. sqlc/event_query.sql, plus generated code: delete GetEventForCreationSignal, GetActiveBatchWorkerLease and HasFinishedBatchWorkerDependents. In ExpireMessageConfirmationTasks, drop the batch_members CTE, since confirm tasks are no longer members.
  10. README.md: remove the sentences about delegated ISO tasks following the owner's lease and about the run staying active through completion callbacks.

Keep (unchanged)

  • Generic parent linking in CreateTask (batchParent), and SignalInline.
  • Overlap protection on by default, with archive actions exempt.
  • The lease and its renewal with retry, the cap, recovery and silent ERROR completion (FinishAbandonedWorkerEvents), and the drain.
  • Removal of per-write fencing.
  • The ISO 18626 55s budget with a WARN, the 5s detached publish of the request notice, the 2-minute message_confirmation_expiry, and ConfirmSupplierMsg using its own parent chain.
  • The down-migration cleanup, the overdue ORDER BY check, SMTP_TIMEOUT, the NCIP nil guard, and the 409 and skip-log run ID.

Tests

  • Remove TestDelegatedBatchWorkFollowsRenewalAcrossReplicas. Remove the completion-successor parts of TestBatchRunTracksGenericChildrenAndCompletionSuccessors, and keep its generic-children assertions.
  • Add: a background action that sends an ISO message to a local CrossLink peer. Assert:
    • the run finishes when the action completes;
    • no notice, message-*, confirm-* or patron-request-message row is in batch_action_run_event.
  • Add: kill the worker while it waits for a confirmation. After lease expiry:
    • the run is released;
    • the downstream events still complete;
    • the confirm task is expired by message_confirmation_expiry.

Done when

  • git grep -nE 'delegatedBatchContext|waitForBatchDependents|BatchWorkerID|GetActiveBatchWorkerLease|HasFinishedBatchWorkerDependents|GetEventForCreationSignal|ParentEventID|messageParentID' broker returns nothing.
  • make -C broker check passes, and the Bruno E2E tests pass.
  • Non-test code shrinks against the current head.

If you know of a case that needs the downstream tracking, describe it here before changing the code and we'll reconsider.

@jakub-id

jakub-id commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

The separate ticket for tasks stranded when a replica dies mid ISO 18626 message (mentioned in my review) is now CROSSLINK-367. It's out of scope for this PR.

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

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants