Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b77c7b5f56 | ||
|
|
9315fa6d32 |
Vendored
+319
@@ -0,0 +1,319 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CacheKey represents a cache key for an activity result
|
||||||
|
type CacheKey struct {
|
||||||
|
ActivityType string // "implementer", "judge", "planner"
|
||||||
|
TaskID string
|
||||||
|
InputHash string // MD5 hash of input
|
||||||
|
ModelID string // LLM model used
|
||||||
|
}
|
||||||
|
|
||||||
|
// String returns a string representation of the cache key
|
||||||
|
func (ck *CacheKey) String() string {
|
||||||
|
return fmt.Sprintf("%s:%s:%s:%s", ck.ActivityType, ck.TaskID, ck.InputHash, ck.ModelID)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CacheEntry represents a cached activity result
|
||||||
|
type CacheEntry struct {
|
||||||
|
Key CacheKey `json:"key"`
|
||||||
|
Result map[string]interface{} `json:"result"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
HitCount int `json:"hit_count"`
|
||||||
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResultCache caches activity results to avoid redundant computations
|
||||||
|
type ResultCache struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
basePath string
|
||||||
|
cache map[string]*CacheEntry
|
||||||
|
maxSize int
|
||||||
|
ttl time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewResultCache creates a new result cache
|
||||||
|
func NewResultCache(basePath string, maxSize int, ttl time.Duration) *ResultCache {
|
||||||
|
return &ResultCache{
|
||||||
|
basePath: basePath,
|
||||||
|
cache: make(map[string]*CacheEntry),
|
||||||
|
maxSize: maxSize,
|
||||||
|
ttl: ttl,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ComputeHash computes a hash of the input data
|
||||||
|
func ComputeHash(data interface{}) (string, error) {
|
||||||
|
jsonData, err := json.Marshal(data)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
hash := md5.Sum(jsonData)
|
||||||
|
return fmt.Sprintf("%x", hash), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set stores a result in the cache
|
||||||
|
func (rc *ResultCache) Set(key *CacheKey, result map[string]interface{}) error {
|
||||||
|
if key == nil {
|
||||||
|
return fmt.Errorf("cache key cannot be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
rc.mu.Lock()
|
||||||
|
defer rc.mu.Unlock()
|
||||||
|
|
||||||
|
keyStr := key.String()
|
||||||
|
|
||||||
|
entry := &CacheEntry{
|
||||||
|
Key: *key,
|
||||||
|
Result: result,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
Metadata: make(map[string]interface{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check size limit
|
||||||
|
if len(rc.cache) >= rc.maxSize && rc.cache[keyStr] == nil {
|
||||||
|
// Evict oldest entry (simple FIFO)
|
||||||
|
var oldestKey string
|
||||||
|
var oldestTime time.Time
|
||||||
|
|
||||||
|
for k, v := range rc.cache {
|
||||||
|
if oldestTime.IsZero() || v.CreatedAt.Before(oldestTime) {
|
||||||
|
oldestKey = k
|
||||||
|
oldestTime = v.CreatedAt
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if oldestKey != "" {
|
||||||
|
delete(rc.cache, oldestKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rc.cache[keyStr] = entry
|
||||||
|
return rc.persistLocked(keyStr, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves a result from the cache
|
||||||
|
func (rc *ResultCache) Get(key *CacheKey) (map[string]interface{}, bool, error) {
|
||||||
|
if key == nil {
|
||||||
|
return nil, false, fmt.Errorf("cache key cannot be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
rc.mu.Lock()
|
||||||
|
defer rc.mu.Unlock()
|
||||||
|
|
||||||
|
keyStr := key.String()
|
||||||
|
entry, exists := rc.cache[keyStr]
|
||||||
|
|
||||||
|
if !exists {
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check TTL
|
||||||
|
if rc.ttl > 0 && time.Since(entry.CreatedAt) > rc.ttl {
|
||||||
|
delete(rc.cache, keyStr)
|
||||||
|
return nil, false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Increment hit count
|
||||||
|
entry.HitCount++
|
||||||
|
_ = rc.persistLocked(keyStr, entry)
|
||||||
|
|
||||||
|
return entry.Result, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Invalidate removes a cache entry
|
||||||
|
func (rc *ResultCache) Invalidate(key *CacheKey) error {
|
||||||
|
if key == nil {
|
||||||
|
return fmt.Errorf("cache key cannot be nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
rc.mu.Lock()
|
||||||
|
defer rc.mu.Unlock()
|
||||||
|
|
||||||
|
keyStr := key.String()
|
||||||
|
delete(rc.cache, keyStr)
|
||||||
|
|
||||||
|
// Delete from disk
|
||||||
|
cacheFile := filepath.Join(rc.basePath, "cache", fmt.Sprintf("%s.json", keyStr))
|
||||||
|
_ = os.Remove(cacheFile)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear clears all cache entries
|
||||||
|
func (rc *ResultCache) Clear() error {
|
||||||
|
rc.mu.Lock()
|
||||||
|
defer rc.mu.Unlock()
|
||||||
|
|
||||||
|
rc.cache = make(map[string]*CacheEntry)
|
||||||
|
|
||||||
|
// Clear disk cache
|
||||||
|
cacheDir := filepath.Join(rc.basePath, "cache")
|
||||||
|
_ = os.RemoveAll(cacheDir)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetStats returns cache statistics
|
||||||
|
func (rc *ResultCache) GetStats() map[string]interface{} {
|
||||||
|
rc.mu.RLock()
|
||||||
|
defer rc.mu.RUnlock()
|
||||||
|
|
||||||
|
totalHits := 0
|
||||||
|
for _, entry := range rc.cache {
|
||||||
|
totalHits += entry.HitCount
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"size": len(rc.cache),
|
||||||
|
"max_size": rc.maxSize,
|
||||||
|
"total_hits": totalHits,
|
||||||
|
"usage_ratio": float64(len(rc.cache)) / float64(rc.maxSize),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSize returns the current cache size
|
||||||
|
func (rc *ResultCache) GetSize() int {
|
||||||
|
rc.mu.RLock()
|
||||||
|
defer rc.mu.RUnlock()
|
||||||
|
|
||||||
|
return len(rc.cache)
|
||||||
|
}
|
||||||
|
|
||||||
|
// persistLocked saves a cache entry to disk (must be called with lock held)
|
||||||
|
func (rc *ResultCache) persistLocked(keyStr string, entry *CacheEntry) error {
|
||||||
|
cacheDir := filepath.Join(rc.basePath, "cache")
|
||||||
|
|
||||||
|
// Create directory if it doesn't exist
|
||||||
|
if err := os.MkdirAll(cacheDir, 0755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cacheFile := filepath.Join(cacheDir, fmt.Sprintf("%s.json", keyStr))
|
||||||
|
|
||||||
|
data, err := json.MarshalIndent(entry, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return os.WriteFile(cacheFile, data, 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load loads cache from disk
|
||||||
|
func (rc *ResultCache) Load() error {
|
||||||
|
rc.mu.Lock()
|
||||||
|
defer rc.mu.Unlock()
|
||||||
|
|
||||||
|
cacheDir := filepath.Join(rc.basePath, "cache")
|
||||||
|
entries, err := os.ReadDir(cacheDir)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil // Cache doesn't exist yet
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
filePath := filepath.Join(cacheDir, entry.Name())
|
||||||
|
data, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var cacheEntry CacheEntry
|
||||||
|
if err := json.Unmarshal(data, &cacheEntry); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip expired entries
|
||||||
|
if rc.ttl > 0 && time.Since(cacheEntry.CreatedAt) > rc.ttl {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
keyStr := cacheEntry.Key.String()
|
||||||
|
rc.cache[keyStr] = &cacheEntry
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvalidateByActivity invalidates all cache entries for an activity type
|
||||||
|
func (rc *ResultCache) InvalidateByActivity(activityType string) error {
|
||||||
|
rc.mu.Lock()
|
||||||
|
defer rc.mu.Unlock()
|
||||||
|
|
||||||
|
keysToDelete := make([]string, 0)
|
||||||
|
for keyStr, entry := range rc.cache {
|
||||||
|
if entry.Key.ActivityType == activityType {
|
||||||
|
keysToDelete = append(keysToDelete, keyStr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, keyStr := range keysToDelete {
|
||||||
|
delete(rc.cache, keyStr)
|
||||||
|
|
||||||
|
// Delete from disk
|
||||||
|
cacheFile := filepath.Join(rc.basePath, "cache", fmt.Sprintf("%s.json", keyStr))
|
||||||
|
_ = os.Remove(cacheFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// InvalidateByTask invalidates all cache entries for a task
|
||||||
|
func (rc *ResultCache) InvalidateByTask(taskID string) error {
|
||||||
|
rc.mu.Lock()
|
||||||
|
defer rc.mu.Unlock()
|
||||||
|
|
||||||
|
keysToDelete := make([]string, 0)
|
||||||
|
for keyStr, entry := range rc.cache {
|
||||||
|
if entry.Key.TaskID == taskID {
|
||||||
|
keysToDelete = append(keysToDelete, keyStr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, keyStr := range keysToDelete {
|
||||||
|
delete(rc.cache, keyStr)
|
||||||
|
|
||||||
|
// Delete from disk
|
||||||
|
cacheFile := filepath.Join(rc.basePath, "cache", fmt.Sprintf("%s.json", keyStr))
|
||||||
|
_ = os.Remove(cacheFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetHitRate returns the cache hit rate
|
||||||
|
func (rc *ResultCache) GetHitRate() (float64, int) {
|
||||||
|
rc.mu.RLock()
|
||||||
|
defer rc.mu.RUnlock()
|
||||||
|
|
||||||
|
if len(rc.cache) == 0 {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
totalHits := 0
|
||||||
|
for _, entry := range rc.cache {
|
||||||
|
totalHits += entry.HitCount
|
||||||
|
}
|
||||||
|
|
||||||
|
if totalHits == 0 {
|
||||||
|
return 0, len(rc.cache)
|
||||||
|
}
|
||||||
|
|
||||||
|
return float64(totalHits) / float64(len(rc.cache)), len(rc.cache)
|
||||||
|
}
|
||||||
Vendored
+316
@@ -0,0 +1,316 @@
|
|||||||
|
package cache
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestCacheKeyString(t *testing.T) {
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "abc123",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
keyStr := key.String()
|
||||||
|
assert.Contains(t, keyStr, "implementer")
|
||||||
|
assert.Contains(t, keyStr, "T1.1")
|
||||||
|
assert.Contains(t, keyStr, "abc123")
|
||||||
|
assert.Contains(t, keyStr, "claude-opus")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestComputeHash(t *testing.T) {
|
||||||
|
data := map[string]interface{}{
|
||||||
|
"task": "T1.1",
|
||||||
|
"code": "package main",
|
||||||
|
}
|
||||||
|
|
||||||
|
hash1, err := ComputeHash(data)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.NotEmpty(t, hash1)
|
||||||
|
|
||||||
|
hash2, err := ComputeHash(data)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, hash1, hash2)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSetAndGet(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "abc123",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
result := map[string]interface{}{
|
||||||
|
"output": "implementation code",
|
||||||
|
"files": []string{"file1.go", "file2.go"},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := cache.Set(key, result)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
|
||||||
|
retrieved, found, err := cache.Get(key)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.True(t, found)
|
||||||
|
assert.Equal(t, "implementation code", retrieved["output"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCacheMiss(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "abc123",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
retrieved, found, err := cache.Get(key)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.False(t, found)
|
||||||
|
assert.Nil(t, retrieved)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvalidate(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "abc123",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
assert.Equal(t, 1, cache.GetSize())
|
||||||
|
|
||||||
|
cache.Invalidate(key)
|
||||||
|
assert.Equal(t, 0, cache.GetSize())
|
||||||
|
|
||||||
|
_, found, _ := cache.Get(key)
|
||||||
|
assert.False(t, found)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestClear(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
for i := 0; i < 10; i++ {
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: string(rune(48 + i)),
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, 10, cache.GetSize())
|
||||||
|
|
||||||
|
cache.Clear()
|
||||||
|
assert.Equal(t, 0, cache.GetSize())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetStats(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "abc123",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
cache.Get(key) // Hit
|
||||||
|
|
||||||
|
stats := cache.GetStats()
|
||||||
|
assert.Equal(t, 1, stats["size"])
|
||||||
|
assert.Equal(t, 100, stats["max_size"])
|
||||||
|
assert.Equal(t, 1, stats["total_hits"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTTLExpiration(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 100*time.Millisecond)
|
||||||
|
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "abc123",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
|
||||||
|
// Should find immediately
|
||||||
|
_, found, _ := cache.Get(key)
|
||||||
|
assert.True(t, found)
|
||||||
|
|
||||||
|
// Wait for TTL to expire
|
||||||
|
time.Sleep(150 * time.Millisecond)
|
||||||
|
|
||||||
|
// Should not find after TTL
|
||||||
|
_, found, _ = cache.Get(key)
|
||||||
|
assert.False(t, found)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMaxSizeEviction(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 3, 0)
|
||||||
|
|
||||||
|
// Add 3 entries
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: string(rune(48 + i)),
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, 3, cache.GetSize())
|
||||||
|
|
||||||
|
// Add 4th entry (should evict oldest)
|
||||||
|
key4 := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "3",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
cache.Set(key4, map[string]interface{}{"output": "code"})
|
||||||
|
|
||||||
|
// Size should still be 3
|
||||||
|
assert.Equal(t, 3, cache.GetSize())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvalidateByActivity(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
// Add implementer entries
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: string(rune(48 + i)),
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add judge entries
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "judge",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: string(rune(48 + i)),
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "verdict"})
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, 4, cache.GetSize())
|
||||||
|
|
||||||
|
// Invalidate implementer entries
|
||||||
|
cache.InvalidateByActivity("implementer")
|
||||||
|
|
||||||
|
assert.Equal(t, 2, cache.GetSize())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInvalidateByTask(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
// Add entries for T1.1
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: string(rune(48 + i)),
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add entries for T1.2
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.2",
|
||||||
|
InputHash: string(rune(48 + i)),
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
cache.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.Equal(t, 4, cache.GetSize())
|
||||||
|
|
||||||
|
// Invalidate T1.1 entries
|
||||||
|
cache.InvalidateByTask("T1.1")
|
||||||
|
|
||||||
|
assert.Equal(t, 2, cache.GetSize())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetHitRate(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
key1 := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "1",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
key2 := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "2",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
cache.Set(key1, map[string]interface{}{"output": "code"})
|
||||||
|
cache.Set(key2, map[string]interface{}{"output": "code"})
|
||||||
|
|
||||||
|
cache.Get(key1)
|
||||||
|
cache.Get(key1)
|
||||||
|
cache.Get(key2)
|
||||||
|
|
||||||
|
hitRate, count := cache.GetHitRate()
|
||||||
|
assert.Equal(t, 2, count)
|
||||||
|
assert.GreaterOrEqual(t, hitRate, 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPersistence(t *testing.T) {
|
||||||
|
tmpDir := t.TempDir()
|
||||||
|
cache1 := NewResultCache(tmpDir, 100, 0)
|
||||||
|
|
||||||
|
key := &CacheKey{
|
||||||
|
ActivityType: "implementer",
|
||||||
|
TaskID: "T1.1",
|
||||||
|
InputHash: "abc123",
|
||||||
|
ModelID: "claude-opus",
|
||||||
|
}
|
||||||
|
|
||||||
|
cache1.Set(key, map[string]interface{}{"output": "code"})
|
||||||
|
|
||||||
|
// Create new cache and load
|
||||||
|
cache2 := NewResultCache(tmpDir, 100, 0)
|
||||||
|
cache2.Load()
|
||||||
|
|
||||||
|
retrieved, found, _ := cache2.Get(key)
|
||||||
|
assert.True(t, found)
|
||||||
|
assert.Equal(t, "code", retrieved["output"])
|
||||||
|
}
|
||||||
@@ -0,0 +1,295 @@
|
|||||||
|
package dispatch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Task represents a unit of work that can be executed
|
||||||
|
type Task interface {
|
||||||
|
ID() string
|
||||||
|
Execute(ctx context.Context) (interface{}, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TaskResult holds the result of a task execution
|
||||||
|
type TaskResult struct {
|
||||||
|
TaskID string
|
||||||
|
Result interface{}
|
||||||
|
Error error
|
||||||
|
Duration time.Duration
|
||||||
|
StartTime time.Time
|
||||||
|
EndTime time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dispatcher manages parallel task execution
|
||||||
|
type Dispatcher struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
maxConcurrency int
|
||||||
|
results map[string]*TaskResult
|
||||||
|
inProgress map[string]bool
|
||||||
|
completed map[string]bool
|
||||||
|
semaphore chan struct{}
|
||||||
|
taskOrder []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDispatcher creates a new task dispatcher
|
||||||
|
func NewDispatcher(maxConcurrency int) *Dispatcher {
|
||||||
|
if maxConcurrency <= 0 {
|
||||||
|
maxConcurrency = 10
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Dispatcher{
|
||||||
|
maxConcurrency: maxConcurrency,
|
||||||
|
results: make(map[string]*TaskResult),
|
||||||
|
inProgress: make(map[string]bool),
|
||||||
|
completed: make(map[string]bool),
|
||||||
|
semaphore: make(chan struct{}, maxConcurrency),
|
||||||
|
taskOrder: make([]string, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DispatchAll dispatches all tasks concurrently and waits for completion
|
||||||
|
func (d *Dispatcher) DispatchAll(ctx context.Context, tasks []Task) (map[string]*TaskResult, error) {
|
||||||
|
if len(tasks) == 0 {
|
||||||
|
return make(map[string]*TaskResult), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
d.mu.Lock()
|
||||||
|
d.taskOrder = make([]string, len(tasks))
|
||||||
|
for i, task := range tasks {
|
||||||
|
d.taskOrder[i] = task.ID()
|
||||||
|
}
|
||||||
|
d.mu.Unlock()
|
||||||
|
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errChan := make(chan error, len(tasks))
|
||||||
|
|
||||||
|
// Launch all tasks concurrently with concurrency limit
|
||||||
|
for _, task := range tasks {
|
||||||
|
wg.Add(1)
|
||||||
|
go func(t Task) {
|
||||||
|
defer wg.Done()
|
||||||
|
|
||||||
|
// Acquire semaphore slot
|
||||||
|
select {
|
||||||
|
case d.semaphore <- struct{}{}:
|
||||||
|
defer func() { <-d.semaphore }()
|
||||||
|
case <-ctx.Done():
|
||||||
|
errChan <- ctx.Err()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
err := d.executeTask(ctx, t)
|
||||||
|
if err != nil {
|
||||||
|
errChan <- err
|
||||||
|
}
|
||||||
|
}(task)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for all tasks to complete
|
||||||
|
wg.Wait()
|
||||||
|
close(errChan)
|
||||||
|
|
||||||
|
// Collect errors
|
||||||
|
var errors []error
|
||||||
|
for err := range errChan {
|
||||||
|
if err != nil {
|
||||||
|
errors = append(errors, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
d.mu.RLock()
|
||||||
|
resultsCopy := make(map[string]*TaskResult)
|
||||||
|
for id, result := range d.results {
|
||||||
|
resultsCopy[id] = result
|
||||||
|
}
|
||||||
|
d.mu.RUnlock()
|
||||||
|
|
||||||
|
if len(errors) > 0 {
|
||||||
|
return resultsCopy, fmt.Errorf("tasks completed with %d errors", len(errors))
|
||||||
|
}
|
||||||
|
|
||||||
|
return resultsCopy, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// executeTask executes a single task and stores the result
|
||||||
|
func (d *Dispatcher) executeTask(ctx context.Context, task Task) error {
|
||||||
|
taskID := task.ID()
|
||||||
|
|
||||||
|
d.mu.Lock()
|
||||||
|
d.inProgress[taskID] = true
|
||||||
|
d.mu.Unlock()
|
||||||
|
|
||||||
|
result := &TaskResult{
|
||||||
|
TaskID: taskID,
|
||||||
|
StartTime: time.Now(),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute task with context timeout
|
||||||
|
taskCtx, cancel := context.WithCancel(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
taskResult, err := task.Execute(taskCtx)
|
||||||
|
result.EndTime = time.Now()
|
||||||
|
result.Duration = result.EndTime.Sub(result.StartTime)
|
||||||
|
result.Result = taskResult
|
||||||
|
result.Error = err
|
||||||
|
|
||||||
|
d.mu.Lock()
|
||||||
|
d.results[taskID] = result
|
||||||
|
d.inProgress[taskID] = false
|
||||||
|
d.completed[taskID] = true
|
||||||
|
d.mu.Unlock()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetResult retrieves the result of a task
|
||||||
|
func (d *Dispatcher) GetResult(taskID string) (*TaskResult, bool) {
|
||||||
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
|
||||||
|
result, exists := d.results[taskID]
|
||||||
|
return result, exists
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetResults retrieves all results
|
||||||
|
func (d *Dispatcher) GetResults() map[string]*TaskResult {
|
||||||
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
|
||||||
|
resultsCopy := make(map[string]*TaskResult)
|
||||||
|
for id, result := range d.results {
|
||||||
|
resultsCopy[id] = result
|
||||||
|
}
|
||||||
|
|
||||||
|
return resultsCopy
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetStats returns dispatcher statistics
|
||||||
|
func (d *Dispatcher) GetStats() map[string]interface{} {
|
||||||
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
|
||||||
|
completed := len(d.completed)
|
||||||
|
totalDuration := time.Duration(0)
|
||||||
|
maxDuration := time.Duration(0)
|
||||||
|
minDuration := time.Duration(0)
|
||||||
|
|
||||||
|
for _, result := range d.results {
|
||||||
|
totalDuration += result.Duration
|
||||||
|
if result.Duration > maxDuration {
|
||||||
|
maxDuration = result.Duration
|
||||||
|
}
|
||||||
|
if minDuration == 0 || result.Duration < minDuration {
|
||||||
|
minDuration = result.Duration
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
avgDuration := time.Duration(0)
|
||||||
|
if completed > 0 {
|
||||||
|
avgDuration = totalDuration / time.Duration(completed)
|
||||||
|
}
|
||||||
|
|
||||||
|
return map[string]interface{}{
|
||||||
|
"total_tasks": len(d.results),
|
||||||
|
"completed": completed,
|
||||||
|
"total_duration": totalDuration,
|
||||||
|
"avg_duration": avgDuration,
|
||||||
|
"max_duration": maxDuration,
|
||||||
|
"min_duration": minDuration,
|
||||||
|
"concurrency": d.maxConcurrency,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExecutionTime returns the total execution time (wallclock)
|
||||||
|
func (d *Dispatcher) GetExecutionTime() time.Duration {
|
||||||
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
|
||||||
|
if len(d.results) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
var minStart time.Time
|
||||||
|
var maxEnd time.Time
|
||||||
|
|
||||||
|
for _, result := range d.results {
|
||||||
|
if minStart.IsZero() || result.StartTime.Before(minStart) {
|
||||||
|
minStart = result.StartTime
|
||||||
|
}
|
||||||
|
if result.EndTime.After(maxEnd) {
|
||||||
|
maxEnd = result.EndTime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return maxEnd.Sub(minStart)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTotalTaskDuration returns the sum of all task durations
|
||||||
|
func (d *Dispatcher) GetTotalTaskDuration() time.Duration {
|
||||||
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
|
||||||
|
total := time.Duration(0)
|
||||||
|
for _, result := range d.results {
|
||||||
|
total += result.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSpeedup returns the speedup factor (sum of task durations / wallclock time)
|
||||||
|
func (d *Dispatcher) GetSpeedup() float64 {
|
||||||
|
totalDuration := d.GetTotalTaskDuration()
|
||||||
|
executionTime := d.GetExecutionTime()
|
||||||
|
|
||||||
|
if executionTime == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
return float64(totalDuration) / float64(executionTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsComplete checks if a task is complete
|
||||||
|
func (d *Dispatcher) IsComplete(taskID string) bool {
|
||||||
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
|
||||||
|
return d.completed[taskID]
|
||||||
|
}
|
||||||
|
|
||||||
|
// AreAllComplete checks if all tasks are complete
|
||||||
|
func (d *Dispatcher) AreAllComplete() bool {
|
||||||
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
|
||||||
|
return len(d.completed) == len(d.results)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCompletedCount returns the number of completed tasks
|
||||||
|
func (d *Dispatcher) GetCompletedCount() int {
|
||||||
|
d.mu.RLock()
|
||||||
|
defer d.mu.RUnlock()
|
||||||
|
|
||||||
|
return len(d.completed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WaitForCompletion waits for all tasks to complete or context to be cancelled
|
||||||
|
func (d *Dispatcher) WaitForCompletion(ctx context.Context) error {
|
||||||
|
ticker := time.NewTicker(10 * time.Millisecond)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case <-ticker.C:
|
||||||
|
if d.AreAllComplete() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
package dispatch
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MockTask is a simple task for testing
|
||||||
|
type MockTask struct {
|
||||||
|
id string
|
||||||
|
duration time.Duration
|
||||||
|
shouldErr bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mt *MockTask) ID() string {
|
||||||
|
return mt.id
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mt *MockTask) Execute(ctx context.Context) (interface{}, error) {
|
||||||
|
select {
|
||||||
|
case <-time.After(mt.duration):
|
||||||
|
if mt.shouldErr {
|
||||||
|
return nil, fmt.Errorf("task %s failed", mt.id)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("result-%s", mt.id), nil
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewDispatcher(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(5)
|
||||||
|
assert.NotNil(t, dispatcher)
|
||||||
|
assert.Equal(t, 5, dispatcher.maxConcurrency)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchSingleTask(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(1)
|
||||||
|
|
||||||
|
task := &MockTask{
|
||||||
|
id: "task-1",
|
||||||
|
duration: 10 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
results, err := dispatcher.DispatchAll(context.Background(), []Task{task})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, 1, len(results))
|
||||||
|
|
||||||
|
result, exists := dispatcher.GetResult("task-1")
|
||||||
|
assert.True(t, exists)
|
||||||
|
assert.NoError(t, result.Error)
|
||||||
|
assert.Equal(t, "result-task-1", result.Result)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchMultipleTasks(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(10)
|
||||||
|
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 5; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 10 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
results, err := dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, 5, len(results))
|
||||||
|
|
||||||
|
for i := 1; i <= 5; i++ {
|
||||||
|
taskID := fmt.Sprintf("task-%d", i)
|
||||||
|
result, exists := dispatcher.GetResult(taskID)
|
||||||
|
assert.True(t, exists)
|
||||||
|
assert.NoError(t, result.Error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDispatchWithErrors(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(10)
|
||||||
|
|
||||||
|
tasks := []Task{
|
||||||
|
&MockTask{id: "task-1", duration: 10 * time.Millisecond, shouldErr: false},
|
||||||
|
&MockTask{id: "task-2", duration: 10 * time.Millisecond, shouldErr: true},
|
||||||
|
&MockTask{id: "task-3", duration: 10 * time.Millisecond, shouldErr: false},
|
||||||
|
}
|
||||||
|
|
||||||
|
results, _ := dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
// Errors don't prevent all tasks from completing
|
||||||
|
assert.Equal(t, 3, len(results))
|
||||||
|
|
||||||
|
result2, _ := dispatcher.GetResult("task-2")
|
||||||
|
assert.Error(t, result2.Error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParallelExecution(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(10)
|
||||||
|
|
||||||
|
// Create 9 tasks, each taking 100ms
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 9; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 100 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
results, err := dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
elapsed := time.Since(start)
|
||||||
|
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, 9, len(results))
|
||||||
|
|
||||||
|
// With parallel execution, should take ~100ms (not 900ms)
|
||||||
|
// Allow some margin (150ms)
|
||||||
|
assert.Less(t, elapsed, 150*time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSpeedup(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(10)
|
||||||
|
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 9; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 50 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
|
||||||
|
speedup := dispatcher.GetSpeedup()
|
||||||
|
// With 9 tasks running in parallel, speedup should be close to 9
|
||||||
|
assert.Greater(t, speedup, 8.0)
|
||||||
|
assert.Less(t, speedup, 10.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestExecutionTime(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(10)
|
||||||
|
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 3; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 100 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
|
||||||
|
executionTime := dispatcher.GetExecutionTime()
|
||||||
|
// Should be roughly 100ms (parallel execution)
|
||||||
|
assert.Greater(t, executionTime, 80*time.Millisecond)
|
||||||
|
assert.Less(t, executionTime, 200*time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTotalTaskDuration(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(10)
|
||||||
|
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 3; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 100 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
|
||||||
|
totalDuration := dispatcher.GetTotalTaskDuration()
|
||||||
|
// Sum should be roughly 300ms
|
||||||
|
assert.Greater(t, totalDuration, 290*time.Millisecond)
|
||||||
|
assert.Less(t, totalDuration, 350*time.Millisecond)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetStats(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(5)
|
||||||
|
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 5; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 50 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
|
||||||
|
stats := dispatcher.GetStats()
|
||||||
|
assert.Equal(t, 5, stats["total_tasks"])
|
||||||
|
assert.Equal(t, 5, stats["completed"])
|
||||||
|
assert.Equal(t, 5, stats["concurrency"])
|
||||||
|
assert.NotZero(t, stats["total_duration"])
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsComplete(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(1)
|
||||||
|
|
||||||
|
task := &MockTask{
|
||||||
|
id: "task-1",
|
||||||
|
duration: 10 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatcher.DispatchAll(context.Background(), []Task{task})
|
||||||
|
|
||||||
|
assert.True(t, dispatcher.IsComplete("task-1"))
|
||||||
|
assert.False(t, dispatcher.IsComplete("task-2"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestAreAllComplete(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(5)
|
||||||
|
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 3; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 10 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
|
||||||
|
assert.True(t, dispatcher.AreAllComplete())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetCompletedCount(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(5)
|
||||||
|
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 5; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 10 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
|
||||||
|
assert.Equal(t, 5, dispatcher.GetCompletedCount())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConcurrencyLimit(t *testing.T) {
|
||||||
|
// Create dispatcher with low concurrency
|
||||||
|
dispatcher := NewDispatcher(2)
|
||||||
|
|
||||||
|
// All tasks should still complete
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 5; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 10 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
results, err := dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, 5, len(results))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestContextCancellation(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(2) // Low concurrency
|
||||||
|
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for i := 1; i <= 10; i++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", i),
|
||||||
|
duration: 500 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
|
go func() {
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
cancel()
|
||||||
|
}()
|
||||||
|
|
||||||
|
_, _ = dispatcher.DispatchAll(ctx, tasks)
|
||||||
|
// Some tasks may be cancelled
|
||||||
|
completed := dispatcher.GetCompletedCount()
|
||||||
|
assert.Less(t, completed, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEmptyTaskList(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(5)
|
||||||
|
|
||||||
|
results, err := dispatcher.DispatchAll(context.Background(), []Task{})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, 0, len(results))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestTaskResultFields(t *testing.T) {
|
||||||
|
dispatcher := NewDispatcher(1)
|
||||||
|
|
||||||
|
task := &MockTask{
|
||||||
|
id: "task-1",
|
||||||
|
duration: 50 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatcher.DispatchAll(context.Background(), []Task{task})
|
||||||
|
|
||||||
|
result, _ := dispatcher.GetResult("task-1")
|
||||||
|
assert.NotZero(t, result.StartTime)
|
||||||
|
assert.NotZero(t, result.EndTime)
|
||||||
|
assert.NotZero(t, result.Duration)
|
||||||
|
assert.True(t, result.EndTime.After(result.StartTime))
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkParallelDispatch(b *testing.B) {
|
||||||
|
dispatcher := NewDispatcher(10)
|
||||||
|
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
tasks := make([]Task, 0)
|
||||||
|
for j := 0; j < 10; j++ {
|
||||||
|
tasks = append(tasks, &MockTask{
|
||||||
|
id: fmt.Sprintf("task-%d", j),
|
||||||
|
duration: 5 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
dispatcher.DispatchAll(context.Background(), tasks)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkDispatchSingleTask(b *testing.B) {
|
||||||
|
dispatcher := NewDispatcher(1)
|
||||||
|
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
task := &MockTask{
|
||||||
|
id: "task-1",
|
||||||
|
duration: 5 * time.Millisecond,
|
||||||
|
shouldErr: false,
|
||||||
|
}
|
||||||
|
dispatcher.DispatchAll(context.Background(), []Task{task})
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -4,8 +4,8 @@
|
|||||||
|
|
||||||
| ID | Scope | Status | Branch | Verification |
|
| ID | Scope | Status | Branch | Verification |
|
||||||
|----|-------|--------|--------|--------------|
|
|----|-------|--------|--------|--------------|
|
||||||
| T2.1 | Activity result caching: deduplicate repeated LLM calls for same task state | [ ] | `task/T2.1` | Implementer called 2x on same code → second call returns cached Implementer output |
|
| T2.1 | Activity result caching: deduplicate repeated LLM calls for same task state | [x] | `task/T2.1` | Implementer called 2x on same code → second call returns cached Implementer output |
|
||||||
| T2.2 | Parallel task dispatch: multiple T0.x tasks execute truly concurrently (not sequential) | [ ] | `task/T2.2` | 9 tasks complete in ~1/9 total time (wall-clock speedup measured) |
|
| T2.2 | Parallel task dispatch: multiple T0.x tasks execute truly concurrently (not sequential) | [x] | `task/T2.2` | 9 tasks complete in ~1/9 total time (wall-clock speedup measured) |
|
||||||
| T2.3 | Prompt template caching: pre-compile Go templates on worker startup | [ ] | `task/T2.3` | Template render latency < 100ms (vs parse+render each time) |
|
| T2.3 | Prompt template caching: pre-compile Go templates on worker startup | [ ] | `task/T2.3` | Template render latency < 100ms (vs parse+render each time) |
|
||||||
| T2.4 | Lessons file indexing: fast lookup of past failures without full file scan | [ ] | `task/T2.4` | Query lessons by task type → return in < 10ms for 1000s of entries |
|
| T2.4 | Lessons file indexing: fast lookup of past failures without full file scan | [ ] | `task/T2.4` | Query lessons by task type → return in < 10ms for 1000s of entries |
|
||||||
| T2.5 | Git operation batching: combine multiple worktree commits into single push/merge | [ ] | `task/T2.5` | N tasks → 1 push (vs N pushes), measured via git ref-log |
|
| T2.5 | Git operation batching: combine multiple worktree commits into single push/merge | [ ] | `task/T2.5` | N tasks → 1 push (vs N pushes), measured via git ref-log |
|
||||||
|
|||||||
Reference in New Issue
Block a user