Skip to content

Commit 8c60640

Browse files
committed
fix[task]: Send IPC after DB transaction commits
`processNewPendingTask` and `processTaskExecutionStarting` enqueued the execution request inside their DB transaction. The assumption that no worker could dequeue it before the commit is wrong: integration testing showed the receiver picking up the message and processing an execution instance whose row was not yet committed. Both now capture the poke as post-commit intent and send after the transaction closes, mirroring `workflow`'s state-before-poke rule (workflow/DESIGN.md Invariant 8). The sender lookup stays inside the transaction so a task with no route to a worker still rolls back. That inverts the failure mode - a lost poke now strands a committed ENQUEUED instance - so two backstops come with it: - `repokeEnqueuedExecution` plus a maintenance sweep step that re-sends (and mutates nothing) for instances ENQUEUED past a grace period of one maintenance interval. Needs the new `UpdatedBefore` query filter. - The receiver now reads an instance's state before claiming it and drops a duplicate request for one already at or past ACQUIRED. Previously this failed ValidNextState and was reported as ENGINE_FAILED, failing the whole parent task - a latent hazard independent of this change. Also stamps GORM's `created_at`/`updated_at` in UTC (`NowFunc`), which the rest of the schema already used. Left as local time, `UpdatedBefore` would be off by the host's UTC offset.
1 parent 8e1015a commit 8c60640

13 files changed

Lines changed: 783 additions & 34 deletions

‎db/client.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package db
44
import (
55
"context"
66
"fmt"
7+
"time"
78

89
"github.com/alwitt/goutils"
910
"github.com/apex/log"
@@ -64,6 +65,12 @@ func NewConnection(dbDialector gorm.Dialector, dbLogLevel logger.LogLevel) (Clie
6465
db, err := gorm.Open(dbDialector, &gorm.Config{
6566
Logger: logger.Default.LogMode(dbLogLevel),
6667
SkipDefaultTransaction: true,
68+
// Stamp the auto-managed `created_at` / `updated_at` columns in UTC. GORM's default
69+
// NowFunc uses local time, which would leave those two columns as the only timestamps in
70+
// the schema not in UTC - every timestamp the application writes explicitly is UTC. A
71+
// query comparing a UTC bound against a locally-stamped column (the stale-ENQUEUED sweep's
72+
// `UpdatedBefore` filter, for one) would then be off by the host's UTC offset.
73+
NowFunc: func() time.Time { return time.Now().UTC() },
6774
})
6875
if err != nil {
6976
return nil, goutils.NewRuntimeError("failed to connect with DB", err, true)

‎db/database.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ type TaskQueryFilter struct {
4949
TaskStates []models.TaskStateENUM `validate:"omitempty,dive,task_state"`
5050
// TargetDeadline tasks with deadline set before this timestamp
5151
TargetDeadline *time.Time
52+
// UpdatedBefore tasks last updated at or before this timestamp. Used to find tasks which
53+
// have sat in a state longer than expected.
54+
UpdatedBefore *time.Time
5255
}
5356

5457
// TaskExecutionQueryFilter query filter conditions to list task executions
@@ -68,6 +71,10 @@ type TaskExecutionQueryFilter struct {
6871
TargetDeadline *time.Time
6972
// TargetStart execution instances set to start before this timestamp
7073
TargetStart *time.Time
74+
// UpdatedBefore execution instances last updated at or before this timestamp. Used to find
75+
// instances which have sat in a state longer than expected - a stale ENQUEUED instance whose
76+
// dispatch poke was lost, for instance.
77+
UpdatedBefore *time.Time
7178
}
7279

7380
// NewTaskParameter new task parameters

‎db/task.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,10 @@ func (c *databaseImpl) ListTasks(
327327
query = query.Where("(deadline is not null and deadline <= ?)", *filters.TargetDeadline)
328328
}
329329

330+
if filters.UpdatedBefore != nil {
331+
query = query.Where("updated_at <= ?", *filters.UpdatedBefore)
332+
}
333+
330334
if filters.Limit != nil {
331335
query = query.Limit(*filters.Limit)
332336
}
@@ -585,6 +589,10 @@ func (c *databaseImpl) ListAllExecutions(
585589
query = query.Where("(execute_at is not null and execute_at <= ?)", *filters.TargetStart)
586590
}
587591

592+
if filters.UpdatedBefore != nil {
593+
query = query.Where("updated_at <= ?", *filters.UpdatedBefore)
594+
}
595+
588596
if filters.Limit != nil {
589597
query = query.Limit(*filters.Limit)
590598
}

‎db/task_test.go‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,59 @@ func TestTaskListTasks(t *testing.T) {
682682
got = idSet(listTasks(db.TaskQueryFilter{Creators: []string{"nobody"}}))
683683
assert.Empty(got)
684684
}
685+
686+
// Case 10: UpdatedBefore - only tasks last touched at or before the cutoff. Scoped to its own
687+
// creator so it is independent of the corpus above.
688+
{
689+
creator := "updated-before-creator"
690+
var task models.Task
691+
assert.Nil(persistence.UseDatabaseInTransaction(
692+
utCtx, func(ctx context.Context, dbClient db.Database) error {
693+
var err error
694+
task, err = dbClient.DefineNewOneShotTask(ctx, db.NewTaskParameter{
695+
Name: "epsilon",
696+
Creator: creator,
697+
RetryParam: models.DefaultTaskRetryParameters(),
698+
})
699+
return err
700+
},
701+
))
702+
703+
// The task was written during this test, so a past cutoff excludes it...
704+
past := time.Now().UTC().Add(-time.Hour)
705+
assert.Empty(listTasks(db.TaskQueryFilter{
706+
Creators: []string{creator}, UpdatedBefore: &past,
707+
}))
708+
709+
// ...and a future one includes it.
710+
future := time.Now().UTC().Add(time.Hour)
711+
got := listTasks(db.TaskQueryFilter{
712+
Creators: []string{creator}, UpdatedBefore: &future,
713+
})
714+
assert.Len(got, 1)
715+
assert.Equal(task.ID, got[0].ID)
716+
717+
// UpdatedBefore intersects with the other conditions rather than replacing them.
718+
assert.Empty(listTasks(db.TaskQueryFilter{
719+
Creators: []string{creator},
720+
TaskStates: []models.TaskStateENUM{models.TaskStateActive},
721+
UpdatedBefore: &future,
722+
}))
723+
724+
// A state change re-stamps updated_at, so the task stays visible to a later cutoff.
725+
assert.Nil(persistence.UseDatabaseInTransaction(
726+
utCtx, func(ctx context.Context, dbClient db.Database) error {
727+
return dbClient.MarkTaskActive(ctx, task.ID)
728+
},
729+
))
730+
got = listTasks(db.TaskQueryFilter{
731+
Creators: []string{creator},
732+
TaskStates: []models.TaskStateENUM{models.TaskStateActive},
733+
UpdatedBefore: &future,
734+
})
735+
assert.Len(got, 1)
736+
assert.Equal(task.ID, got[0].ID)
737+
}
685738
}
686739

687740
func TestTaskDeleteTask(t *testing.T) {
@@ -1663,6 +1716,36 @@ func TestTaskExecListAllExecutions(t *testing.T) {
16631716
assert.Len(got, 1)
16641717
assert.Equal(immAcquired.ID, got[0].ID)
16651718
}
1719+
1720+
// Case 10: UpdatedBefore - only instances last touched at or before the cutoff. Every
1721+
// instance above was written during this test, so a past cutoff excludes all of them and a
1722+
// future one includes all of them.
1723+
{
1724+
past := time.Now().UTC().Add(-time.Hour)
1725+
assert.Empty(listExecs(db.TaskExecutionQueryFilter{UpdatedBefore: &past}))
1726+
1727+
future := time.Now().UTC().Add(time.Hour)
1728+
assert.Len(listExecs(db.TaskExecutionQueryFilter{UpdatedBefore: &future}), len(created))
1729+
}
1730+
1731+
// Case 11: ExecStates + UpdatedBefore - the scheduler's stale-ENQUEUED sweep query. Only the
1732+
// enqueued instance qualifies, and only once the cutoff moves past when it was enqueued.
1733+
{
1734+
future := time.Now().UTC().Add(time.Hour)
1735+
got := listExecs(db.TaskExecutionQueryFilter{
1736+
ExecStates: []models.TaskExecutionStateENUM{models.TaskExecutionStateEnqueued},
1737+
UpdatedBefore: &future,
1738+
})
1739+
assert.Len(got, 1)
1740+
assert.Equal(immEnqueued.ID, got[0].ID)
1741+
1742+
// Within the grace period (cutoff before it was enqueued) it is not yet stale.
1743+
past := time.Now().UTC().Add(-time.Hour)
1744+
assert.Empty(listExecs(db.TaskExecutionQueryFilter{
1745+
ExecStates: []models.TaskExecutionStateENUM{models.TaskExecutionStateEnqueued},
1746+
UpdatedBefore: &past,
1747+
}))
1748+
}
16661749
}
16671750

16681751
func TestAuditRecordInvalidTaskIPCMessage(t *testing.T) {

‎task/DESIGN.md‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,9 @@ Supporting layers:
105105
events (the seam into `notify`).
106106
- **`db`** — persistence. State-change methods (`MarkTask*`) write a `SystemEventAudit` row
107107
**in the same transaction** as the state change, so an event and its state commit
108-
atomically.
108+
atomically. Every timestamp in the schema is UTC, including the GORM-managed `created_at` /
109+
`updated_at` (the connection overrides GORM's local-time `NowFunc`), so a query may compare a
110+
UTC bound against any timestamp column.
109111
- **`common`** — the Redis reliable-queue IPC send/receive clients (§7).
110112

111113
### 3.0 The Client is creator-scoped
@@ -257,6 +259,46 @@ maintenance sweep, or a redundant re-delivery from buffer recovery) using
257259
the delivery is a **safe no-op**; a genuinely out-of-order delivery is *not* masked and still
258260
surfaces as a consistency error via the subsequent `ValidNextState` check.
259261

262+
The **receiver** applies the same rule to the one message it consumes. `processOneIPCRequest`
263+
reads the execution instance before claiming it: an instance already at or past `ACQUIRED`
264+
(which includes every ended state) means somebody already owns it, so the request is dropped
265+
from the buffer as a benign duplicate — *not* reported as an engine failure, which would fail a
266+
parent task that is running perfectly well elsewhere. A state **upstream** of `ACQUIRED` is
267+
deliberately left unmasked and still surfaces through `MarkTaskExecAcquired`'s `ValidNextState`
268+
check. Duplicates are expected here by construction: §6.3's stale-`ENQUEUED` sweep re-sends a
269+
dispatch whose original looked lost, and buffer replay can re-deliver one.
270+
271+
### 6.2.1 State-before-poke
272+
273+
Every handler follows one ordering rule: **it commits the driving state change to the DB first,
274+
and only then emits the follow-on IPC message.** The message is a *poke* — it lets the next
275+
component act sooner than the maintenance sweep would; it is never the sole record that work
276+
exists.
277+
278+
This is load-bearing, not stylistic. The scheduler and the task worker are separate processes
279+
against a shared Redis queue: a message enqueued *inside* the transaction is visible to a worker
280+
**immediately**, well before the transaction commits. A worker that dequeues it then reads an
281+
execution instance that does not exist yet, or reads it in its pre-transaction state. The
282+
inverse — commit first — is safe because a worker can only ever observe state that is already
283+
durable.
284+
285+
Concretely:
286+
287+
- **New Pending Task** marks the task `ACTIVE` and its immediate execution instance `ENQUEUED`
288+
(committed), *then* emits the dispatch request onto the task queue.
289+
- **Execution Starting** marks the instance `ENQUEUED` (committed), *then* emits the dispatch.
290+
291+
Because of this ordering, a **failed emit** — the enqueue errors, or the process dies between
292+
the commit and the send — loses only the *poke*, never the *work*, so it is logged rather than
293+
returned. What the emit must never do is fail the handler: the state is already committed, and
294+
returning an error would only re-run a handler whose idempotency guard now no-ops.
295+
296+
Two things the rule requires of the surrounding code. The *sender lookup* stays inside the
297+
transaction — it is an in-memory map read, not IPC, and a task with no route to a worker must
298+
roll the whole thing back rather than commit an `ENQUEUED` instance nothing can ever claim.
299+
And every lost poke needs a sweep step that re-derives it (§6.3); `ENQUEUED` is the one state
300+
with no state change left to make, which is why it gets a re-*send* rather than a re-drive.
301+
260302
### 6.3 The maintenance timer is the universal backstop
261303

262304
The maintenance interval timer does not invoke maintenance directly — it enqueues an
@@ -269,12 +311,23 @@ lost poke could strand:
269311
3. **PROCESSED / FAILED executions** awaiting finalization — finalize them.
270312
4. **SCHEDULED executions due to start** — enqueue them. *(This is also the only path that
271313
fires scheduled and retry executions — there is no poke for a future time.)*
272-
5. **Live executions past their deadline** — time them out.
314+
5. **ENQUEUED executions past the re-poke grace period** — re-send their dispatch request.
315+
6. **Live executions past their deadline** — time them out.
273316

274317
This is why the engine is self-healing: **a dropped IPC message only delays work; the next
275318
maintenance pass catches it.** It is also structurally required for scheduled/retry
276319
executions, which have no triggering message.
277320

321+
Step 5 is the odd one out and exists because of §6.2.1. Every other step re-derives a *state
322+
change* the DB says is still owed. `ENQUEUED` has no such change left — it is the state an
323+
instance is committed in immediately before its dispatch is sent, so a lost send leaves nothing
324+
for the DB to reveal except an instance sitting there. `repokeEnqueuedExecution` therefore
325+
re-*sends* the message and mutates nothing. The grace period is one full maintenance interval
326+
(floored at 10s): an instance a worker is about to claim leaves `ENQUEUED` within milliseconds,
327+
so anything still there after a whole sweep cycle has lost its poke rather than merely queued
328+
behind a busy worker pool. Re-sends that race a claim are absorbed by the receiver's guard
329+
(§6.2).
330+
278331
### 6.4 Retry decision
279332

280333
On an execution FAILED (and the task still ACTIVE), `processTaskExecutionFailed` counts prior

‎task/receiver.go‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -755,10 +755,37 @@ func (r *receiverImpl) processOneIPCRequest(
755755
// ------------------------------------------------------------------------------------
756756
// Claim ownership of the execution request
757757

758+
// alreadyClaimed reports that the instance was found at or past ACQUIRED - somebody is already
759+
// on it (or it has ended), so this delivery is a duplicate. Set inside the transaction, acted
760+
// on after it.
761+
var alreadyClaimed bool
762+
758763
// Claim ownership of the execution instance
759764
if dbErr := r.persistence.UseDatabaseInTransaction(
760765
ctx,
761766
func(dbCtx context.Context, dbClient db.Database) error {
767+
// Idempotency guard: a dispatch request can legitimately arrive twice - the scheduler's
768+
// maintenance sweep re-pokes an instance whose original poke looked lost, and buffer
769+
// replay can re-deliver one. Claiming an instance already at or past ACQUIRED would
770+
// fail ValidNextState, which the caller below would report as an ENGINE_FAILED and
771+
// which fails the whole parent task. Read the state first and treat a duplicate as the
772+
// no-op it is. Every ended state (Processed / Failed / Cancelled / Finalized) is
773+
// downstream of ACQUIRED, so this one check covers them all. A state UPSTREAM of
774+
// ACQUIRED is deliberately not masked: that is a genuine out-of-order delivery and
775+
// still surfaces through MarkTaskExecAcquired's ValidNextState check below.
776+
execInstance, err := dbClient.GetTaskExecution(dbCtx, execRequest.InstanceID)
777+
if err != nil {
778+
return goutils.NewPersistenceError(
779+
fmt.Sprintf(
780+
"failed to fetch execution instance %s", execRequest.InstanceID,
781+
), err, true,
782+
)
783+
}
784+
if execInstance.IsStateAtOrPast(models.TaskExecutionStateAcquired) {
785+
alreadyClaimed = true
786+
return nil
787+
}
788+
762789
if err := dbClient.MarkTaskExecAcquired(
763790
dbCtx, execRequest.InstanceID, r.config.Name,
764791
); err != nil {
@@ -811,6 +838,25 @@ func (r *receiverImpl) processOneIPCRequest(
811838
return nil
812839
}
813840

841+
// A duplicate delivery: somebody already owns this instance (or it has ended). Drop the
842+
// message and stop here. This is NOT an engine failure - reporting one would fail a task that
843+
// is running perfectly well elsewhere.
844+
if alreadyClaimed {
845+
log.
846+
WithFields(goutils.UpdateCodePositionInTags(logTags)).
847+
WithField("exec-id", execRequest.InstanceID).
848+
Info("Discarding duplicate execution request: instance already claimed or ended")
849+
if delErr := receiver.DeleteBufferedMessage(ctx, msg); delErr != nil {
850+
log.
851+
WithError(delErr).
852+
WithFields(goutils.UpdateCodePositionInTags(logTags)).
853+
WithField("exec-id", execRequest.InstanceID).
854+
Error("Failed to delete buffered message for duplicate execution request")
855+
}
856+
// NOOP
857+
return nil
858+
}
859+
814860
// ------------------------------------------------------------------------------------
815861
// Submit for processing
816862

0 commit comments

Comments
 (0)