You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
CROSSLINK-360 Recover interrupted batch runs and support manual reruns - #892
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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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;
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:
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).
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.
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
patron_request/service/message_sender.go: stop passing a parent ID into HandleSupplyingAgencyMessage, HandleRequestingAgencyMessage and HandleRequest. Delete messageParentID.
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.
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.
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.
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.
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.
events/batch_worker.go: delete delegatedBatchContext, waitForBatchDependents and the call in runBatchWorker.
events/eventmodels.go: delete EventData.BatchWorkerID. It was never on main, so no compatibility path is needed.
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.
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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
runLinkafter recovery. Scheduled actions pick up at the next occurrence.Stop older broker replicas before applying migration 083. The operator and deployment procedures are in the broker README.
Verification
The standalone coverage checker rejects the existing
local-prefixkey in the broker coverage configuration. The broker tests generated a coverage profile.