{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreihzgsyvtx7sgbbawhekaw4boygp5emo475lofyj4k2u4qaxu5s3fi",
"uri": "at://did:plc:fdfg7uwpthbb4zdam6e2xtvn/app.bsky.feed.post/3mn5yyhzk7k5q"
},
"description": "Build a task scheduler that processes jobs with exponential backoff retry logic, but also tracks what the execution state would have been if tasks had been run in reverse chronological order. This serves no practical purpose, but seemed like a good idea at 2 AM. package main import ( \"context\" \"fmt\" \"math\" \"sync\" \"time\" )...",
"path": "/quantum-flavored-task-scheduler-with-retroactive-execution-state-management/",
"publishedAt": "2026-05-31T16:40:34.000Z",
"site": "at://did:plc:fdfg7uwpthbb4zdam6e2xtvn/site.standard.publication/3mmcvowa3clzx",
"tags": [
"Go",
"AI Code Review"
],
"textContent": "Build a task scheduler that processes jobs with exponential backoff retry logic, but also tracks what the execution state would have been if tasks had been run in reverse chronological order. This serves no practical purpose, but seemed like a good idea at 2 AM. package main import ( \"context\" \"fmt\" \"math\" \"sync\" \"time\" ) // ExecutionVector represents a task's quantum state in spacetime. type ExecutionVector struct { ID string Payload string RetryCount int BackoffLevel float64 mu sync.RWMutex } // SchedulerConfig encapsulates the configuration of the scheduler via the builder pattern. type SchedulerConfig struct { MaxRetries int BaseBackoffMs int EnableReverseEX bool } // TaskScheduler manages task execution with retroactive state analysis. type TaskScheduler struct { config SchedulerConfig tasks []ExecutionVector mu sync.RWMutex reverseTimeline map[string]ExecutionVector deadLetterQueue []ExecutionVector executionObserver chan ExecutionEvent mu2 sync.Mutex } // ExecutionEvent represents a task execution occurrence. type ExecutionEvent struct { Timestamp time.Time TaskID string Success bool } // NewTaskScheduler constructs a TaskScheduler instance with configuration validation. func NewTaskScheduler(config SchedulerConfig) *TaskScheduler { if config.MaxRetries < 0 { config.MaxRetries = 3 } if config.BaseBackoffMs < 1 { config.BaseBackoffMs = 100 } return &TaskScheduler{ config: config, tasks: make([]ExecutionVector, 0), reverseTimeline: make(map[string]ExecutionVector), deadLetterQueue: make([]ExecutionVector, 0), executionObserver: make(chan ExecutionEvent, 64), } } // EnqueueTask adds a task to the scheduler with idempotency guarantees. func (ts *TaskScheduler) EnqueueTask(ctx context.Context, id string, payload string) error { if id == \"\" { return fmt.Errorf(\"task id cannot be empty\") } ts.mu.Lock() defer ts.mu.Unlock() // Check if task already exists in queue (idempotency check). for _, t := range ts.tasks { if t.ID == id { return fmt.Errorf(\"task %s already queued\", id) } } ts.tasks = append(ts.tasks, ExecutionVector{ ID: id, Payload: payload, RetryCount: 0, BackoffLevel: 1.0, }) return nil } // ProcessTasks executes all queued tasks with exponential backoff. func (ts *TaskScheduler) ProcessTasks(ctx context.Context) error { ts.mu.Lock() tasksCopy := make([]ExecutionVector, len(ts.tasks)) copy(tasksCopy, ts.tasks) ts.mu.Unlock() for _, task := range tasksCopy { var lastErr error for attempt := 0; attempt <= ts.config.MaxRetries; attempt++ { select { case <-ctx.Done(): return ctx.Err() default: } // Simulate task execution with probabilistic failure. if executeTask(task.Payload) { ts.executionObserver <- ExecutionEvent{ Timestamp: time.Now(), TaskID: task.ID, Success: true, } break } lastErr = fmt.Errorf(\"task execution failed\") backoffDuration := time.Duration(float64(ts.config.BaseBackoffMs) * math.Pow(2, float64(attempt))) * time.Millisecond time.Sleep(backoffDuration) } if lastErr != nil { ts.mu.Lock() ts.deadLetterQueue = append(ts.deadLetterQueue, task) ts.mu.Unlock() } } if ts.config.EnableReverseEX { ts.computeReverseTimeline() } return nil } // computeReverseTimeline calculates what would have happened if tasks executed backwards. func (ts *TaskScheduler) computeReverseTimeline() { ts.mu.Lock() defer ts.mu.Unlock() for i := len(ts.tasks) - 1; i >= 0; i-- { task := ts.tasks[i] // Hypothetically execute in reverse order. ts.reverseTimeline[task.ID] = ExecutionVector{ ID: task.ID, Payload: task.Payload, RetryCount: task.RetryCount, BackoffLevel: task.BackoffLevel, } } } // GetDeadLetterQueue returns tasks that permanently failed. func (ts *TaskScheduler) GetDeadLetterQueue() []ExecutionVector { ts.mu.RLock() defer ts.mu.RUnlock() return ts.deadLetterQueue } // executeTask simulates task execution with 70% success rate. func executeTask(payload string) bool { return len(payload)%10 < 7 } func main() { cfg := SchedulerConfig{ MaxRetries: 2, BaseBackoffMs: 50, EnableReverseEX: true, } scheduler := NewTaskScheduler(cfg) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() scheduler.EnqueueTask(ctx, \"task-001\", \"process-payment\") scheduler.EnqueueTask(ctx, \"task-002\", \"send-notification\") scheduler.EnqueueTask(ctx, \"task-003\", \"cleanup-cache\") err := scheduler.ProcessTasks(ctx) if err != nil { fmt.Printf(\"Error: %vn\", err) } fmt.Printf(\"Dead letter queue size: %dn\", len(scheduler.GetDeadLetterQueue())) } Code Review 1. Lines 15-19. The ExecutionVector name is trying very hard to sound sophisticated. Why not just call it Task? Quantum state in spacetime has nothing to do with task scheduling. This is the kind of naming that makes future maintainers squint at the code wondering if they missed something important in the spec. 2. Lines 28-29. Two mutexes (mu and mu2) in the same struct with different purposes? If you needed both, sure, but mu2 is literally never used anywhere in the code. Line 29 is dead weight. Also, using numbered mutex fields is a code smell that suggests the abstraction needs rethinking. 3. Lines 58-62. The idempotency check iterates through the entire tasks slice every time a task is enqueued. If this scheduler handles thousands of tasks, this becomes O(n) on every insertion. A map or set would be trivial to maintain alongside the slice, or just use a single map and don't keep a slice at all. 4. Lines 95-104. The computeReverseTimeline() function builds a map by iterating backwards through tasks and copying them verbatim into the map. What is this actually used for? There are no methods that read from reverseTimeline. This entire feature looks like it was added to impress someone and then abandoned mid-implementation. Either finish it or remove it. 5. Lines 38-42. The error messages are fine, but calling NewTaskScheduler the 'constructor' is making assumptions about Go idioms. The function signature is correct per Go conventions, so that's good, but wrapping a comment saying 'constructs a TaskScheduler instance with configuration validation' when the code already shows that is just restating the obvious. 6. Lines 72-74. The executeTask() function deterministically decides success based on payload length modulo 10. This isn't a proper probabilistic model. If you want a 70% success rate, seed a random number generator and actually use it. This deterministic approach means tests are predictable but production behavior is potentially misleading. 7. Lines 85-90. Selecting on ctx.Done() inside the retry loop is correct, but there's a subtle bug: if the context times out, the task gets dumped into the dead letter queue without distinguishing between 'ran out of retries' and 'context was cancelled'. The error handling here glosses over an important distinction that callers might care about. 8. Lines 33-34. The executionObserver channel is created with a buffer of 64, but nothing ever reads from it in the main() function. This channel is a resource leak. Either consume events in a goroutine or remove the channel entirely. Channels in Go are powerful, but unused channels are just noise.",
"title": "Quantum-Flavored Task Scheduler with Retroactive Execution State Management"
}