Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

Improve context management and database operations with enhanced locking mechanism

Dane Schneider8cec22e1ff87
diff --git a/app/server/db/context_helpers.go b/app/server/db/context_helpers.go
index 3e187cd8..1f180089 100644
--- a/app/server/db/context_helpers.go
+++ b/app/server/db/context_helpers.go
@@ -412,6 +412,7 @@ type LoadContextsParams struct {
UserId string
SkipConflictInvalidation bool
CachedMapsByPath map[string]*CachedMap
+ AutoLoaded bool
}
func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextResponse, []*Context, error) {
@@ -427,6 +428,7 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
planId := plan.Id
branchName := params.BranchName
userId := params.UserId
+ autoLoaded := params.AutoLoaded
filesToLoad := map[string]string{}
for _, context := range *req {
@@ -447,6 +449,7 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
}
tokensAdded := 0
+ basicTokensAdded := 0
paramsByTempId := make(map[string]*shared.LoadContextParams)
numTokensByTempId := make(map[string]int)
@@ -457,6 +460,7 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
}
totalTokens := branch.ContextTokens
totalPlannerTokens := totalTokens
+ totalBasicPlannerTokens := 0
totalMapTokens := 0
settings, err := GetPlanSettings(plan, true)
@@ -487,6 +491,10 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
totalMapTokens += context.NumTokens
totalPlannerTokens -= context.NumTokens
}
+
+ if !context.AutoLoaded && context.ContextType != shared.ContextMapType {
+ totalBasicPlannerTokens += context.NumTokens
+ }
}
var filteredReq []*shared.LoadContextParams
@@ -562,6 +570,7 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
MapParts: mappedFiles,
MapShas: mapShas,
MapTokens: mapTokens,
+ AutoLoaded: autoLoaded,
}
mapContextsByFilePath[context.FilePath] = newContext
@@ -583,9 +592,14 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
if planConfig.AutoLoadContext && isMap {
tokensAdded += numTokens
totalMapTokens += numTokens
+ } else if autoLoaded {
+ tokensAdded += numTokens
+ totalPlannerTokens += numTokens
} else {
tokensAdded += numTokens
totalPlannerTokens += numTokens
+ totalBasicPlannerTokens += numTokens
+ basicTokensAdded += numTokens
}
}
@@ -599,15 +613,24 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
MaxTokensExceeded: true,
}, nil, nil
}
- }
- if totalPlannerTokens > plannerMaxTokens {
- return &shared.LoadContextResponse{
- TokensAdded: tokensAdded,
- TotalTokens: totalPlannerTokens,
- MaxTokens: plannerMaxTokens,
- MaxTokensExceeded: true,
- }, nil, nil
+ if totalBasicPlannerTokens > plannerMaxTokens {
+ return &shared.LoadContextResponse{
+ TokensAdded: basicTokensAdded,
+ TotalTokens: totalBasicPlannerTokens,
+ MaxTokens: plannerMaxTokens,
+ MaxTokensExceeded: true,
+ }, nil, nil
+ }
+ } else {
+ if totalTokens > plannerMaxTokens {
+ return &shared.LoadContextResponse{
+ TokensAdded: tokensAdded,
+ TotalTokens: totalTokens,
+ MaxTokens: plannerMaxTokens,
+ MaxTokensExceeded: true,
+ }, nil, nil
+ }
}
var dbContexts []*Context
@@ -643,6 +666,7 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon
Body: loadParams.Body,
ForceSkipIgnore: loadParams.ForceSkipIgnore,
ImageDetail: loadParams.ImageDetail,
+ AutoLoaded: autoLoaded,
}
}
@@ -716,8 +740,16 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
totalTokens := branch.ContextTokens
totalPlannerTokens := totalTokens
+
totalMapTokens := 0
+ totalBasicPlannerTokens := 0
+ for _, context := range params.ContextsById {
+ if context.ContextType != shared.ContextMapType && !context.AutoLoaded {
+ totalBasicPlannerTokens += context.NumTokens
+ }
+ }
+
settings, err := GetPlanSettings(plan, true)
if err != nil {
return nil, fmt.Errorf("error getting settings: %v", err)
@@ -746,6 +778,7 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
}
aggregateTokensDiff := 0
+ aggregateBasicTokensDiff := 0
tokenDiffsById := make(map[string]int)
var contextsById map[string]*Context
@@ -834,6 +867,10 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
aggregateTokensDiff += tokenDiff
totalTokens += tokenDiff
totalPlannerTokens += tokenDiff
+ if !context.AutoLoaded {
+ totalBasicPlannerTokens += tokenDiff
+ aggregateBasicTokensDiff += tokenDiff
+ }
context.NumTokens = updateNumTokens
}
@@ -859,15 +896,16 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
}
}
- if totalPlannerTokens > plannerMaxTokens {
- return &shared.UpdateContextResponse{
- TokensAdded: aggregateTokensDiff,
- TotalTokens: totalTokens,
- MaxTokens: plannerMaxTokens,
- MaxTokensExceeded: true,
- }, nil
+ if planConfig.AutoLoadContext {
+ if totalBasicPlannerTokens > plannerMaxTokens {
+ return &shared.UpdateContextResponse{
+ TokensAdded: aggregateTokensDiff,
+ TotalTokens: totalBasicPlannerTokens,
+ MaxTokens: plannerMaxTokens,
+ MaxTokensExceeded: true,
+ }, nil
+ }
}
-
filesToLoad := map[string]string{}
for _, context := range updatedContexts {
if context.ContextType == shared.ContextFileType {
diff --git a/app/server/db/convo_helpers.go b/app/server/db/convo_helpers.go
index 3754ec94..7a0c09a9 100644
--- a/app/server/db/convo_helpers.go
+++ b/app/server/db/convo_helpers.go
@@ -9,6 +9,8 @@ import (
"strings"
"time"
+ shared "plandex-shared"
+
"github.com/fatih/color"
"github.com/google/uuid"
"github.com/sashabaranov/go-openai"
@@ -149,7 +151,15 @@ func StoreConvoMessage(message *ConvoMessage, currentUserId, branch string, comm
}
}
- if message.Flags.IsImplementationStage && message.Subtask != nil {
+ if len(message.RemovedSubtasks) > 0 {
+ msg += "\n\n"
+ msg += "Removed Tasks"
+ for _, subtask := range message.RemovedSubtasks {
+ msg += "\n• " + subtask
+ }
+ }
+
+ if message.Flags.CurrentStage.TellStage == shared.TellStageImplementation && message.Subtask != nil {
msg += "\n\n" + "📋 " + message.Subtask.Title
if len(message.Subtask.UsesFiles) > 0 {
for _, file := range message.Subtask.UsesFiles {
diff --git a/app/server/db/data_models.go b/app/server/db/data_models.go
index 677531d7..b3c43362 100644
--- a/app/server/db/data_models.go
+++ b/app/server/db/data_models.go
@@ -397,6 +397,7 @@ type Context struct {
MapParts shared.FileMapBodies `json:"mapParts,omitempty"`
MapShas map[string]string `json:"mapShas,omitempty"`
MapTokens map[string]int `json:"mapTokens,omitempty"`
+ AutoLoaded bool `json:"autoLoaded"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
@@ -417,6 +418,7 @@ func (context *Context) ToMeta() *Context {
NumTokens: context.NumTokens,
BodySize: context.BodySize,
ForceSkipIgnore: context.ForceSkipIgnore,
+ AutoLoaded: context.AutoLoaded,
ImageDetail: context.ImageDetail,
MapShas: context.MapShas,
MapTokens: context.MapTokens,
@@ -438,6 +440,7 @@ func (context *Context) ToApi() *shared.Context {
Body: context.Body,
BodySize: context.BodySize,
ForceSkipIgnore: context.ForceSkipIgnore,
+ AutoLoaded: context.AutoLoaded,
ImageDetail: context.ImageDetail,
MapParts: context.MapParts,
MapShas: context.MapShas,
@@ -448,19 +451,21 @@ func (context *Context) ToApi() *shared.Context {
}
type ConvoMessage struct {
- Id string `json:"id"`
- OrgId string `json:"orgId"`
- PlanId string `json:"planId"`
- UserId string `json:"userId"`
- Role string `json:"role"`
- Tokens int `json:"tokens"`
- Num int `json:"num"`
- Message string `json:"message"`
- Stopped bool `json:"stopped"`
- Subtask *Subtask `json:"subtask,omitempty"`
- AddedSubtasks []*Subtask `json:"addedSubtasks,omitempty"`
- Flags shared.ConvoMessageFlags `json:"flags"`
- CreatedAt time.Time `json:"createdAt"`
+ Id string `json:"id"`
+ OrgId string `json:"orgId"`
+ PlanId string `json:"planId"`
+ UserId string `json:"userId"`
+ Role string `json:"role"`
+ Tokens int `json:"tokens"`
+ Num int `json:"num"`
+ Message string `json:"message"`
+ Stopped bool `json:"stopped"`
+ Subtask *Subtask `json:"subtask,omitempty"`
+ AddedSubtasks []*Subtask `json:"addedSubtasks,omitempty"`
+ RemovedSubtasks []string `json:"removedSubtasks,omitempty"`
+ Flags shared.ConvoMessageFlags `json:"flags"`
+ ActivatedPaths map[string]bool `json:"activatedPaths,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
}
func (msg *ConvoMessage) ToApi() *shared.ConvoMessage {
@@ -469,17 +474,18 @@ func (msg *ConvoMessage) ToApi() *shared.ConvoMessage {
addedSubtasks[i] = subtask.ToApi()
}
return &shared.ConvoMessage{
- Id: msg.Id,
- UserId: msg.UserId,
- Role: msg.Role,
- Tokens: msg.Tokens,
- Num: msg.Num,
- Message: msg.Message,
- Stopped: msg.Stopped,
- Flags: msg.Flags,
- Subtask: msg.Subtask.ToApi(),
- AddedSubtasks: addedSubtasks,
- CreatedAt: msg.CreatedAt,
+ Id: msg.Id,
+ UserId: msg.UserId,
+ Role: msg.Role,
+ Tokens: msg.Tokens,
+ Num: msg.Num,
+ Message: msg.Message,
+ Stopped: msg.Stopped,
+ Flags: msg.Flags,
+ Subtask: msg.Subtask.ToApi(),
+ AddedSubtasks: addedSubtasks,
+ RemovedSubtasks: msg.RemovedSubtasks,
+ CreatedAt: msg.CreatedAt,
}
}
@@ -564,6 +570,30 @@ func (res *PlanFileResult) ToApi() *shared.PlanFileResult {
}
}
+type PlanApply struct {
+ Id string `json:"id"`
+ OrgId string `json:"orgId"`
+ PlanId string `json:"planId"`
+ UserId string `json:"userId"`
+ ConvoMessageIds []string `json:"convoMessageIds"`
+ ConvoMessageDescriptionIds []string `json:"convoMessageDescriptionIds"`
+ PlanFileResultIds []string `json:"planFileResultIds"`
+ CommitMsg string `json:"commitMsg"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+func (apply *PlanApply) ToApi() *shared.PlanApply {
+ return &shared.PlanApply{
+ Id: apply.Id,
+ UserId: apply.UserId,
+ ConvoMessageIds: apply.ConvoMessageIds,
+ ConvoMessageDescriptionIds: apply.ConvoMessageDescriptionIds,
+ PlanFileResultIds: apply.PlanFileResultIds,
+ CommitMsg: apply.CommitMsg,
+ CreatedAt: apply.CreatedAt,
+ }
+}
+
type Subtask struct {
Title string `json:"title"`
Description string `json:"description"`
diff --git a/app/server/db/fs.go b/app/server/db/fs.go
index 8f681a1b..095389c2 100644
--- a/app/server/db/fs.go
+++ b/app/server/db/fs.go
@@ -103,6 +103,10 @@ func getPlanResultsDir(orgId, planId string) string {
return filepath.Join(getPlanDir(orgId, planId), "results")
}
+func getPlanAppliesDir(orgId, planId string) string {
+ return filepath.Join(getPlanDir(orgId, planId), "applies")
+}
+
func getPlanDescriptionsDir(orgId, planId string) string {
return filepath.Join(getPlanDir(orgId, planId), "descriptions")
}
diff --git a/app/server/db/locks.go b/app/server/db/locks.go
index a554fecd..2f2e12cc 100644
--- a/app/server/db/locks.go
+++ b/app/server/db/locks.go
@@ -53,20 +53,27 @@ var planLocks = make(map[string]*PlanLockState)
// PlanLockState tracks concurrency for one plan, with its own mutex and cond.
type PlanLockState struct {
- mu sync.Mutex // Protects the fields below
- cond *sync.Cond
- currentBranch string
- readCount int
- hasWriter bool
+ mu sync.Mutex
+ cond *sync.Cond
+ currentBranch string
+ readCount int
+ hasWriter bool
+ waitingWriters int // Track number of writers waiting to acquire the lock
}
// getOrCreatePlanLockState fetches or creates a PlanLockState for a planId.
func getOrCreatePlanLockState(planId string) *PlanLockState {
+ log.Printf("Attempting to acquire planLocksMu for plan %s", planId)
+
planLocksMu.Lock()
+ log.Printf("Acquired planLocksMu for plan %s", planId)
defer planLocksMu.Unlock()
pls := planLocks[planId]
+ log.Printf("Current plan lock state for %s: %+v", planId, pls)
+
if pls == nil {
+ log.Printf("Creating new plan lock state for %s", planId)
pls = &PlanLockState{}
pls.cond = sync.NewCond(&pls.mu)
planLocks[planId] = pls
@@ -77,15 +84,46 @@ func getOrCreatePlanLockState(planId string) *PlanLockState {
// acquireLocalLock attempts to acquire local concurrency for (planId, branch, scope).
// Blocks until successful or context canceled.
func acquireLocalLock(ctx context.Context, planId, branch string, scope LockScope) error {
+ if locksVerboseLogging {
+ log.Printf("Attempting to acquire local lock for plan %s branch %s scope %s", planId, branch, scope)
+ }
+
pls := getOrCreatePlanLockState(planId)
+ if locksVerboseLogging {
+ log.Printf("About to acquire mutex for plan %s", planId)
+ }
pls.mu.Lock()
+ if locksVerboseLogging {
+ log.Printf("Acquired mutex for plan %s", planId)
+ }
defer pls.mu.Unlock()
+ // Track waiting writers
+ if scope == LockScopeWrite {
+ pls.waitingWriters++
+ if locksVerboseLogging {
+ log.Printf("Incrementing waiting writers for plan %s to %d", planId, pls.waitingWriters)
+ }
+ defer func() {
+ pls.waitingWriters--
+ if locksVerboseLogging {
+ log.Printf("Decremented waiting writers for plan %s to %d", planId, pls.waitingWriters)
+ }
+ }()
+ }
+
for {
+ if locksVerboseLogging {
+ log.Printf("Lock state for plan %s: hasWriter=%v readCount=%d currentBranch=%s waitingWriters=%d",
+ planId, pls.hasWriter, pls.readCount, pls.currentBranch, pls.waitingWriters)
+ }
+
// If there's an active writer, no read or write can proceed
if pls.hasWriter {
- // Wait, but also check context
+ if locksVerboseLogging {
+ log.Printf("Plan %s has writer, waiting...", planId)
+ }
if err := waitOrCtx(ctx, pls); err != nil {
return err
}
@@ -96,6 +134,10 @@ func acquireLocalLock(ctx context.Context, planId, branch string, scope LockScop
// If we have existing readers, must match branch
if pls.readCount > 0 {
if pls.currentBranch != branch {
+ if locksVerboseLogging {
+ log.Printf("Plan %s has readers on different branch %s, waiting...",
+ planId, pls.currentBranch)
+ }
if err := waitOrCtx(ctx, pls); err != nil {
return err
}
@@ -103,22 +145,26 @@ func acquireLocalLock(ctx context.Context, planId, branch string, scope LockScop
}
} else {
// No readers yet => set the branch
+ if locksVerboseLogging {
+ log.Printf("Plan %s has no readers, setting branch to %s", planId, branch)
+ }
pls.currentBranch = branch
}
// Acquire a read slot
pls.readCount++
+ if locksVerboseLogging {
+ log.Printf("Acquired read lock for plan %s branch %s (readCount=%d)",
+ planId, branch, pls.readCount)
+ }
return nil
} else {
// scope == LockScopeWrite
- // Write can only proceed if no readers and no writer
+ // Write can only proceed if no readers
if pls.readCount > 0 {
- if err := waitOrCtx(ctx, pls); err != nil {
- return err
+ if locksVerboseLogging {
+ log.Printf("Plan %s has readers, waiting for write lock...", planId)
}
- continue
- }
- if pls.hasWriter {
if err := waitOrCtx(ctx, pls); err != nil {
return err
}
@@ -127,6 +173,9 @@ func acquireLocalLock(ctx context.Context, planId, branch string, scope LockScop
// Acquire the writer
pls.hasWriter = true
pls.currentBranch = branch
+ if locksVerboseLogging {
+ log.Printf("Acquired write lock for plan %s branch %s", planId, branch)
+ }
return nil
}
}
@@ -134,41 +183,75 @@ func acquireLocalLock(ctx context.Context, planId, branch string, scope LockScop
// releaseLocalLock frees local concurrency for (planId, branch, scope).
func releaseLocalLock(planId, branch string, scope LockScope) {
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] Starting to release local lock for plan %s branch %s scope %s", planId, branch, scope)
+ }
+
planLocksMu.Lock()
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] Acquired planLocksMu for deletion check for plan %s", planId)
+ }
pls, ok := planLocks[planId]
if !ok {
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] No lock state found for plan %s", planId)
+ }
planLocksMu.Unlock()
return
}
planLocksMu.Unlock()
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] About to acquire mutex for plan %s. Pre-state: hasWriter=%v readCount=%d currentBranch=%s waitingWriters=%d",
+ planId, pls.hasWriter, pls.readCount, pls.currentBranch, pls.waitingWriters)
+ }
pls.mu.Lock()
- defer pls.mu.Unlock()
-
- if pls.currentBranch != branch {
- log.Printf("WARN: Releasing lock for branch=%s, but planLockState has branch=%s",
- branch, pls.currentBranch)
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] Acquired mutex for plan %s", planId)
}
+ defer pls.mu.Unlock()
if scope == LockScopeRead {
pls.readCount--
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] Released read lock for plan %s branch %s (readCount=%d)",
+ planId, branch, pls.readCount)
+ }
if pls.readCount < 0 {
log.Printf("BUG: readCount < 0 for plan %s", planId)
pls.readCount = 0
}
} else {
+ prevState := fmt.Sprintf("hasWriter=%v readCount=%d currentBranch=%s waitingWriters=%d",
+ pls.hasWriter, pls.readCount, pls.currentBranch, pls.waitingWriters)
pls.hasWriter = false
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] Released write lock for plan %s. Previous state: %s, New state: hasWriter=%v readCount=%d currentBranch=%s waitingWriters=%d",
+ planId, prevState, pls.hasWriter, pls.readCount, pls.currentBranch, pls.waitingWriters)
+ }
}
- if pls.readCount == 0 && !pls.hasWriter {
+ // Only remove state if no active readers/writers AND no waiting writers
+ if pls.readCount == 0 && !pls.hasWriter && pls.waitingWriters == 0 {
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] No readers/writers/waiters left, removing state for plan %s", planId)
+ }
pls.currentBranch = ""
- // Optionally remove from the map entirely
planLocksMu.Lock()
delete(planLocks, planId)
planLocksMu.Unlock()
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] Removed lock state for plan %s from global map", planId)
+ }
+ } else if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] Keeping lock state for plan %s (readCount=%d, hasWriter=%v, waitingWriters=%d)",
+ planId, pls.readCount, pls.hasWriter, pls.waitingWriters)
}
pls.cond.Broadcast()
+ if locksVerboseLogging {
+ log.Printf("[LOCAL_UNLOCK] Completed unlock operation for plan %s", planId)
+ }
}
// waitOrCtx calls pls.cond.Wait() but also checks if ctx is canceled.
@@ -228,8 +311,8 @@ func LockRepo(params LockRepoParams) (string, error) {
func DeleteRepoLock(id, planId string) error {
// Try to fetch scope + branch from DB
var scope LockScope
- var branch *string
- err := Conn.QueryRow("SELECT scope, branch FROM repo_locks WHERE id = $1", id).Scan(&scope, &branch)
+ var maybeBranch *string
+ err := Conn.QueryRow("SELECT scope, branch FROM repo_locks WHERE id = $1", id).Scan(&scope, &maybeBranch)
if err != nil && err != sql.ErrNoRows {
return fmt.Errorf("error getting lock info: %v", err)
}
@@ -237,11 +320,14 @@ func DeleteRepoLock(id, planId string) error {
// Do the DB remove first
dbErr := deleteRepoLockDB(id, planId, 0)
- // Then free local concurrency
- if branch != nil && scope != "" {
- releaseLocalLock(planId, *branch, scope)
+ branch := ""
+ if maybeBranch != nil {
+ branch = *maybeBranch
}
+ // Then free local concurrency
+ releaseLocalLock(planId, branch, scope)
+
return dbErr
}