fix(backend): stop a duplicate lifecycle turn from hiding a pending clarification (#2989)

Co-authored-by: nova28 <17953305+nova28@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Carlos Florencio <carlosmflorencio@gmail.com>
This commit is contained in:
Henry
2026-08-27 19:56:39 +00:00
committed by GitHub
parent e6a66b4f1f
commit c7de33b0bc
27 changed files with 2041 additions and 59 deletions
@@ -116,14 +116,15 @@ func clarificationBundleQuery(drv, whereExtra string) string {
)
notParentQuestion := dialect.ExcludeTruthyMetadataPredicate(drv, "m.metadata", "parent_question")
nonTerminalSession := nonTerminalSessionPredicate("m")
predicate, orderBy := currentTurnAuthority(drv, "turn_row")
currentTurn := fmt.Sprintf(`m.turn_id = (
SELECT turn_row.id
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = m.task_session_id
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
)`, turnAuthorityPredicate(drv, "turn_row"))
)`, predicate, orderBy)
return fmt.Sprintf(`
SELECT b.pending_id, b.session_id, b.task_id, b.created_at
FROM (
@@ -32,7 +32,8 @@ func seedBundleTurn(t *testing.T, repo *Repository, turnID, sessionID, taskID st
// seedBundleTurnAt creates a turn with an explicit started_at/created_at, so
// a test can control which of two turns on the same session is newest per
// turnAuthorityPredicate's ORDER BY (started_at DESC, created_at DESC, id DESC).
// currentTurnAuthority's ordering: open turns (completed_at IS NULL) before
// completed ones, then started_at DESC, created_at DESC, id DESC.
func seedBundleTurnAt(t *testing.T, repo *Repository, turnID, sessionID, taskID string, at time.Time) {
t.Helper()
_, err := repo.db.Exec(repo.db.Rebind(`
@@ -582,13 +582,14 @@ func (r *Repository) FindMessagesByPendingID(ctx context.Context, pendingID stri
// cleanup; they never become current input authority.
func (r *Repository) FindActiveClarificationMessagesBySessionID(ctx context.Context, sessionID string) ([]*models.Message, error) {
drv := r.ro.DriverName()
predicate, orderBy := currentTurnAuthority(drv, "turn_row")
query := fmt.Sprintf(`
WITH current_turn AS (
SELECT turn_row.id
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = ?
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
)
SELECT m.id, m.task_session_id, m.task_id, m.turn_id, m.author_type, m.author_id,
@@ -599,7 +600,7 @@ func (r *Repository) FindActiveClarificationMessagesBySessionID(ctx context.Cont
AND m.type = 'clarification_request'
AND COALESCE(%s, '') IN ('', 'pending')
ORDER BY m.created_at ASC, m.id ASC
`, turnAuthorityPredicate(drv, "turn_row"), dialect.JSONExtract(drv, "m.metadata", "status"))
`, predicate, orderBy, dialect.JSONExtract(drv, "m.metadata", "status"))
// First sessionID selects current-turn authority; second scopes messages so
// a malformed cross-session turn reference cannot leak another session's row.
rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(query), sessionID, sessionID)
@@ -661,6 +662,7 @@ func pendingActionsBySessionQuery(driverName string, placeholders []string) stri
// Terminal sessions quarantine pending history even when best-effort expiry
// persistence failed. Both message CTEs inherit the requested-session
// boundary through their task_session_id and turn_id joins to current_turn.
predicate, orderBy := currentTurnAuthority(driverName, "turn_row")
return fmt.Sprintf(`
WITH current_turn AS (
SELECT task_session_id, id AS turn_id
@@ -669,7 +671,7 @@ func pendingActionsBySessionQuery(driverName string, placeholders []string) stri
id,
ROW_NUMBER() OVER (
PARTITION BY task_session_id
ORDER BY started_at DESC, created_at DESC, id DESC
ORDER BY %s
) AS rn
FROM task_session_turns turn_row
WHERE turn_row.task_session_id IN (%s)
@@ -706,7 +708,7 @@ func pendingActionsBySessionQuery(driverName string, placeholders []string) stri
SELECT task_session_id, 'permission' AS action
FROM latest_permissions
WHERE rn = 1 AND status IN ('', 'pending')
`, placeholderList, turnAuthorityPredicate(driverName, "turn_row"),
`, orderBy, placeholderList, predicate,
nonTerminalSessionPredicate("turn_row"), statusExpr, statusExpr, permissionOrderExpr)
}
@@ -54,6 +54,7 @@ func (r *Repository) DetachActiveClarificationMessagesBySessionID(
return nil, err
}
updatedAt := r.nowUTC()
predicate, orderBy := currentTurnAuthority(drv, "turn_row")
query := fmt.Sprintf(`
UPDATE task_session_messages
SET metadata = %s, updated_at = ?
@@ -66,7 +67,7 @@ func (r *Repository) DetachActiveClarificationMessagesBySessionID(
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = task_session_messages.task_session_id
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
)
RETURNING id, task_session_id, task_id, turn_id, author_type, author_id,
@@ -74,7 +75,7 @@ func (r *Repository) DetachActiveClarificationMessagesBySessionID(
`, clarificationDetachedMetadataExpr(drv),
dialect.JSONExtract(drv, "task_session_messages.metadata", "status"),
clarificationNotDetachedPredicate(drv),
turnAuthorityPredicate(drv, "turn_row"))
predicate, orderBy)
rows, err := tx.QueryxContext(ctx, r.db.Rebind(query), updatedAt, sessionID)
if err != nil {
return nil, fmt.Errorf("detach active clarification messages: %w", err)
@@ -111,6 +112,7 @@ func (r *Repository) ExpireActiveClarificationBundle(
return nil, err
}
updatedAt := r.nowUTC()
predicate, orderBy := currentTurnAuthority(drv, "turn_row")
query := fmt.Sprintf(`
UPDATE task_session_messages
SET metadata = %s, updated_at = ?
@@ -123,7 +125,7 @@ func (r *Repository) ExpireActiveClarificationBundle(
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = task_session_messages.task_session_id
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
)
RETURNING id, task_session_id, task_id, turn_id, author_type, author_id,
@@ -131,7 +133,7 @@ func (r *Repository) ExpireActiveClarificationBundle(
`, clarificationExpiredMetadataExpr(drv),
dialect.JSONExtract(drv, "task_session_messages.metadata", "status"),
dialect.JSONExtract(drv, "task_session_messages.metadata", "pending_id"),
turnAuthorityPredicate(drv, "turn_row"))
predicate, orderBy)
rows, err := tx.QueryxContext(ctx, r.db.Rebind(query), updatedAt, sessionID, pendingID)
if err != nil {
return nil, fmt.Errorf("expire active clarification messages: %w", err)
@@ -345,6 +347,7 @@ func (r *Repository) loadRestorableClarificationBundle(
) ([]*models.Message, error) {
pendingIDExpr := dialect.JSONExtract(drv, "m.metadata", "pending_id")
bundlePendingIDExpr := dialect.JSONExtract(drv, "bundle.metadata", "pending_id")
predicate, orderBy := currentTurnAuthority(drv, "turn_row")
// A pending ID spanning message types, sessions, or turns is malformed. The
// NOT EXISTS guard intentionally makes the whole bundle ineligible to restore.
query := fmt.Sprintf(`
@@ -360,7 +363,7 @@ func (r *Repository) loadRestorableClarificationBundle(
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = m.task_session_id
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
)
AND NOT EXISTS (
@@ -377,7 +380,7 @@ func (r *Repository) loadRestorableClarificationBundle(
`, pendingIDExpr,
nonTerminalSessionPredicate("m"),
clarificationResponseDeliveryPendingPredicate(drv, "m"),
turnAuthorityPredicate(drv, "turn_row"),
predicate, orderBy,
bundlePendingIDExpr,
)
rows, err := tx.QueryxContext(
@@ -406,6 +409,7 @@ func (r *Repository) restoreClarificationMessages(
) error {
updatedAt := r.nowUTC()
statusExpr := dialect.JSONExtract(drv, "metadata", "status")
predicate, orderBy := currentTurnAuthority(drv, "turn_row")
updateQuery := r.db.Rebind(fmt.Sprintf(`
UPDATE task_session_messages
SET metadata = ?, updated_at = ?
@@ -417,14 +421,14 @@ func (r *Repository) restoreClarificationMessages(
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = task_session_messages.task_session_id
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
)
`,
statusExpr,
clarificationResponseDeliveryPendingPredicate(drv, "task_session_messages"),
nonTerminalSessionPredicate("task_session_messages"),
turnAuthorityPredicate(drv, "turn_row"),
predicate, orderBy,
))
restoredMetadataByMessage := make([]map[string]interface{}, len(messages))
for i, message := range messages {
@@ -479,6 +483,7 @@ func (r *Repository) claimActiveClarificationBundle(
// it is replaced with the requested terminal status before this transaction
// commits or is rolled back with the transaction.
claimAt := r.nowUTC()
predicate, orderBy := currentTurnAuthority(drv, "turn_row")
claimQuery := fmt.Sprintf(`
UPDATE task_session_messages
SET metadata = %s, updated_at = ?
@@ -491,7 +496,7 @@ func (r *Repository) claimActiveClarificationBundle(
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = task_session_messages.task_session_id
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
)
AND NOT EXISTS (
@@ -506,7 +511,7 @@ func (r *Repository) claimActiveClarificationBundle(
)
`, dialect.JSONSet(drv, "metadata", "status", clarificationStatusResponding), pendingIDExpr, statusExpr,
nonTerminalSessionPredicate("task_session_messages"),
turnAuthorityPredicate(drv, "turn_row"), bundlePendingIDExpr)
predicate, orderBy, bundlePendingIDExpr)
// pendingID is bound once for the outer bundle and once for the malformed-
// bundle NOT EXISTS guard.
result, err := tx.ExecContext(ctx, r.db.Rebind(claimQuery), claimAt, pendingID, pendingID)
@@ -526,6 +531,7 @@ func (r *Repository) loadClaimedClarificationBundle(
drv, pendingID string,
) ([]*models.Message, error) {
claimedStatusExpr := dialect.JSONExtract(drv, "m.metadata", "status")
predicate, orderBy := currentTurnAuthority(drv, "turn_row")
rows, err := tx.QueryxContext(ctx, r.db.Rebind(fmt.Sprintf(`
SELECT m.id, m.task_session_id, m.task_id, m.turn_id, m.author_type, m.author_id,
m.content, m.requests_input, m.type, m.metadata, m.created_at, m.updated_at
@@ -536,12 +542,12 @@ func (r *Repository) loadClaimedClarificationBundle(
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = m.task_session_id
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
)
ORDER BY m.created_at ASC, m.id ASC
`, dialect.JSONExtract(drv, "m.metadata", "pending_id"), claimedStatusExpr,
turnAuthorityPredicate(drv, "turn_row"))), pendingID, clarificationStatusResponding)
predicate, orderBy)), pendingID, clarificationStatusResponding)
if err != nil {
return nil, fmt.Errorf("load claimed clarification bundle: %w", err)
}
@@ -216,17 +216,21 @@ func (r *Repository) GetTurn(ctx context.Context, id string) (*models.Turn, erro
return scanTurnRow(row)
}
// GetActiveTurnBySessionID gets the currently active (non-completed) turn for a session
// GetActiveTurnBySessionID gets the currently active (non-completed) turn for
// a session. This is not the same query as "current turn": it keeps its own
// completed_at IS NULL filter alongside currentTurnAuthority's predicate and
// ordering (D10) so AbandonOpenTurns' re-bury loop keeps working.
func (r *Repository) GetActiveTurnBySessionID(ctx context.Context, sessionID string) (*models.Turn, error) {
predicate, orderBy := currentTurnAuthority(r.ro.DriverName(), "turn_row")
query := fmt.Sprintf(`
SELECT id, task_session_id, task_id, execution_profile_id, route_generation, started_at, completed_at, metadata, created_at, updated_at
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = ?
AND turn_row.completed_at IS NULL
AND %s
ORDER BY turn_row.started_at DESC, turn_row.created_at DESC, turn_row.id DESC
ORDER BY %s
LIMIT 1
`, turnAuthorityPredicate(r.ro.DriverName(), "turn_row"))
`, predicate, orderBy)
row := r.ro.QueryRowContext(ctx, r.ro.Rebind(query), sessionID)
return scanTurnRow(row)
}
@@ -0,0 +1,156 @@
{
"cases": [
{
"name": "lifecycle_only boolean true excludes the newer turn",
"turns": [
{ "id": "bool-true-real", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "bool-true-lifecycle", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": true } }
],
"expected_current_turn_id": "bool-true-real"
},
{
"name": "lifecycle_only number 1 excludes the newer turn",
"turns": [
{ "id": "num-one-real", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "num-one-lifecycle", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": 1 } }
],
"expected_current_turn_id": "num-one-real"
},
{
"name": "lifecycle_only string true excludes the newer turn",
"turns": [
{ "id": "str-true-real", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "str-true-lifecycle", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": "true" } }
],
"expected_current_turn_id": "str-true-real"
},
{
"name": "lifecycle_only string 1 excludes the newer turn",
"turns": [
{ "id": "str-one-real", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "str-one-lifecycle", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": "1" } }
],
"expected_current_turn_id": "str-one-real"
},
{
"name": "lifecycle_only null keeps the newer turn eligible",
"turns": [
{ "id": "null-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "null-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": null } }
],
"expected_current_turn_id": "null-newer"
},
{
"name": "lifecycle_only absent key keeps the newer turn eligible",
"turns": [
{ "id": "absent-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "absent-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": {} }
],
"expected_current_turn_id": "absent-newer"
},
{
"name": "lifecycle_only boolean false keeps the newer turn eligible",
"turns": [
{ "id": "bool-false-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "bool-false-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": false } }
],
"expected_current_turn_id": "bool-false-newer"
},
{
"name": "lifecycle_only number 0 keeps the newer turn eligible",
"turns": [
{ "id": "num-zero-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "num-zero-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": 0 } }
],
"expected_current_turn_id": "num-zero-newer"
},
{
"name": "lifecycle_only empty string keeps the newer turn eligible",
"turns": [
{ "id": "empty-str-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "empty-str-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": "" } }
],
"expected_current_turn_id": "empty-str-newer"
},
{
"name": "lifecycle_only string false keeps the newer turn eligible",
"turns": [
{ "id": "str-false-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "str-false-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": "false" } }
],
"expected_current_turn_id": "str-false-newer"
},
{
"name": "lifecycle_only string 0 keeps the newer turn eligible",
"turns": [
{ "id": "str-zero-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "str-zero-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": "0" } }
],
"expected_current_turn_id": "str-zero-newer"
},
{
"name": "lifecycle_only string yes keeps the newer turn eligible",
"turns": [
{ "id": "yes-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "yes-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": "yes" } }
],
"expected_current_turn_id": "yes-newer"
},
{
"name": "lifecycle_only empty object keeps the newer turn eligible",
"turns": [
{ "id": "obj-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "obj-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": {} } }
],
"expected_current_turn_id": "obj-newer"
},
{
"name": "lifecycle_only empty array keeps the newer turn eligible",
"turns": [
{ "id": "arr-older", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "arr-newer", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": [] } }
],
"expected_current_turn_id": "arr-newer"
},
{
"name": "a session with only lifecycle turns resolves no current turn",
"turns": [
{ "id": "all-lifecycle-a", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": { "lifecycle_only": true } },
{ "id": "all-lifecycle-b", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": "2026-08-14T11:00:00Z", "metadata": { "lifecycle_only": "1" } }
],
"expected_current_turn_id": null
},
{
"name": "an open turn beats a later completed turn",
"turns": [
{ "id": "order-open", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": null, "metadata": {} },
{ "id": "order-completed-later", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T11:00:00Z", "completed_at": "2026-08-14T11:05:00Z", "metadata": {} }
],
"expected_current_turn_id": "order-open"
},
{
"name": "later started_at wins among completed turns",
"turns": [
{ "id": "order-started-later", "started_at": "2026-08-14T11:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": "2026-08-14T12:00:00Z", "metadata": {} },
{ "id": "order-started-earlier", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": "2026-08-14T12:00:00Z", "metadata": {} }
],
"expected_current_turn_id": "order-started-later"
},
{
"name": "tie on started_at broken by later created_at",
"turns": [
{ "id": "order-created-later", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:01:00Z", "completed_at": "2026-08-14T12:00:00Z", "metadata": {} },
{ "id": "order-created-earlier", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": "2026-08-14T12:00:00Z", "metadata": {} }
],
"expected_current_turn_id": "order-created-later"
},
{
"name": "tie on started_at and created_at broken by higher id",
"turns": [
{ "id": "order-tie-2", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": "2026-08-14T12:00:00Z", "metadata": {} },
{ "id": "order-tie-1", "started_at": "2026-08-14T10:00:00Z", "created_at": "2026-08-14T10:00:00Z", "completed_at": "2026-08-14T12:00:00Z", "metadata": {} }
],
"expected_current_turn_id": "order-tie-2"
}
]
}
@@ -59,6 +59,33 @@ func turnDispatchAttemptedPredicate(driverName, turnAlias string) string {
)
}
// currentTurnAuthority composes turnAuthorityPredicate with R1's lifecycle
// exclusion into predicate, and D1's total order into orderBy. Every
// current-turn resolution site takes both values from this one call and
// hand-writes neither (AC-3).
//
// predicate is a single parenthesized conjunct for `WHERE ... AND %s`.
// orderBy is a bare, turnAlias-qualified expression list with no ORDER BY
// keyword and no LIMIT, so it drops into both `ORDER BY %s` and
// `ROW_NUMBER() OVER (... ORDER BY %s)`. Its first key ranks an open turn
// (completed_at IS NULL) ahead of a completed one regardless of timestamps;
// the remaining keys break ties by started_at, created_at, then id — all
// descending, with id (the primary key) providing a total order.
func currentTurnAuthority(driverName, turnAlias string) (predicate, orderBy string) {
authority := turnAuthorityPredicate(driverName, turnAlias)
lifecycle := turnLifecycleOnlyPredicate(driverName, turnAlias)
predicate = fmt.Sprintf("(%s AND NOT (%s))", authority, lifecycle)
orderBy = fmt.Sprintf(
"CASE WHEN %s.completed_at IS NULL THEN 0 ELSE 1 END ASC, %s.started_at DESC, %s.created_at DESC, %s.id DESC",
turnAlias, turnAlias, turnAlias, turnAlias,
)
return predicate, orderBy
}
func turnLifecycleOnlyPredicate(driverName, turnAlias string) string {
return turnMetadataFlagPredicate(driverName, turnAlias, models.TurnMetaKeyLifecycleOnly)
}
func turnMetadataFlagPredicate(driverName, turnAlias, key string) string {
value := dialect.JSONExtract(
driverName,
@@ -0,0 +1,128 @@
package sqlite
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"os"
"testing"
"time"
"github.com/kandev/kandev/internal/task/models"
)
// turnResolutionFixture mirrors
// testdata/current_turn_resolution.json (AC-10). It is the shared contract
// between this Go repository test and the TypeScript unit test that loads
// the same file from apps/web/lib/utils/pending-clarification-turn-authority.test.ts
// (or a sibling file it imports) - one artifact both implementations are
// proven to agree with, not two independently-trusted ones.
type turnResolutionFixture struct {
Cases []turnResolutionCase `json:"cases"`
}
type turnResolutionCase struct {
Name string `json:"name"`
Turns []turnResolutionTurn `json:"turns"`
ExpectedCurrentTurnID *string `json:"expected_current_turn_id"`
}
type turnResolutionTurn struct {
ID string `json:"id"`
StartedAt time.Time `json:"started_at"`
CreatedAt time.Time `json:"created_at"`
CompletedAt *time.Time `json:"completed_at"`
Metadata map[string]interface{} `json:"metadata"`
}
// loadTurnResolutionFixture SHALL fail the test (not skip) when the fixture
// is missing, unreadable, or unparseable - a fixture that silently stops
// being read is indistinguishable from two implementations that agree.
func loadTurnResolutionFixture(t *testing.T) turnResolutionFixture {
t.Helper()
raw, err := os.ReadFile("testdata/current_turn_resolution.json")
if err != nil {
t.Fatalf("read current_turn_resolution.json: %v", err)
}
var fixture turnResolutionFixture
if err := json.Unmarshal(raw, &fixture); err != nil {
t.Fatalf("parse current_turn_resolution.json: %v", err)
}
if len(fixture.Cases) == 0 {
t.Fatal("current_turn_resolution.json has no cases")
}
return fixture
}
// resolveCurrentTurnID runs currentTurnAuthority's predicate/orderBy directly
// against the turns table, the same CTE shape
// FindActiveClarificationMessagesBySessionID uses internally, without its
// join to messages - so it resolves a session's current turn regardless of
// whether any message references it. Returns nil when no turn resolves.
func resolveCurrentTurnID(t *testing.T, repo *Repository, sessionID string) *string {
t.Helper()
predicate, orderBy := currentTurnAuthority(repo.ro.DriverName(), "turn_row")
query := fmt.Sprintf(`
SELECT turn_row.id
FROM task_session_turns turn_row
WHERE turn_row.task_session_id = ?
AND %s
ORDER BY %s
LIMIT 1
`, predicate, orderBy)
row := repo.ro.QueryRowContext(context.Background(), repo.ro.Rebind(query), sessionID)
var id string
switch err := row.Scan(&id); {
case errors.Is(err, sql.ErrNoRows):
return nil
case err != nil:
t.Fatalf("resolve current turn for session %s: %v", sessionID, err)
return nil
default:
return &id
}
}
// TestCurrentTurnResolutionFixture is AC-10: every case in the shared
// fixture, run against the real Go currentTurnAuthority resolution. The
// TypeScript counterpart runs the identical cases through
// newestDurableTurnId. Neither test may filter the shared cases; each may
// add its own.
func TestCurrentTurnResolutionFixture(t *testing.T) {
fixture := loadTurnResolutionFixture(t)
for i, tc := range fixture.Cases {
t.Run(tc.Name, func(t *testing.T) {
repo := newRepoForSessionTests(t)
ctx := context.Background()
taskID := fmt.Sprintf("task-fixture-%d", i)
sessionID := fmt.Sprintf("session-fixture-%d", i)
seedSessionForTurns(t, repo, taskID, sessionID)
for _, turn := range tc.Turns {
if err := repo.CreateTurn(ctx, &models.Turn{
ID: turn.ID,
TaskSessionID: sessionID,
TaskID: taskID,
StartedAt: turn.StartedAt,
CreatedAt: turn.CreatedAt,
CompletedAt: turn.CompletedAt,
Metadata: turn.Metadata,
}); err != nil {
t.Fatalf("seed fixture turn %s: %v", turn.ID, err)
}
}
got := resolveCurrentTurnID(t, repo, sessionID)
switch {
case tc.ExpectedCurrentTurnID == nil && got != nil:
t.Fatalf("current turn = %s, want none to resolve", *got)
case tc.ExpectedCurrentTurnID != nil && got == nil:
t.Fatalf("current turn = none, want %s", *tc.ExpectedCurrentTurnID)
case tc.ExpectedCurrentTurnID != nil && got != nil && *got != *tc.ExpectedCurrentTurnID:
t.Fatalf("current turn = %s, want %s", *got, *tc.ExpectedCurrentTurnID)
}
})
}
}
@@ -0,0 +1,57 @@
package sqlite
import (
"context"
"fmt"
"testing"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/testutil"
)
// TestCurrentTurnResolutionFixturePostgres is AC-10/D9: the same shared
// fixture TestCurrentTurnResolutionFixture proves against SQLite, run
// against PostgreSQL so D1's key 1 (open beats completed) and the
// lifecycle_only exclusion resolve identically on both dialects. Skips
// unless KANDEV_TEST_POSTGRES_DSN is set. Neither this test nor the SQLite
// one may filter the shared cases; each may add its own.
func TestCurrentTurnResolutionFixturePostgres(t *testing.T) {
fixture := loadTurnResolutionFixture(t)
for i, tc := range fixture.Cases {
t.Run(tc.Name, func(t *testing.T) {
db := testutil.OpenIsolatedPostgres(t, testutil.PostgresDSNFromEnv(t))
repo, err := NewWithDB(db, db, nil)
if err != nil {
t.Fatalf("init postgres schema: %v", err)
}
ctx := context.Background()
taskID := fmt.Sprintf("task-fixture-pg-%d", i)
sessionID := fmt.Sprintf("session-fixture-pg-%d", i)
seedSessionForTurns(t, repo, taskID, sessionID)
for _, turn := range tc.Turns {
if err := repo.CreateTurn(ctx, &models.Turn{
ID: turn.ID,
TaskSessionID: sessionID,
TaskID: taskID,
StartedAt: turn.StartedAt,
CreatedAt: turn.CreatedAt,
CompletedAt: turn.CompletedAt,
Metadata: turn.Metadata,
}); err != nil {
t.Fatalf("seed fixture turn %s: %v", turn.ID, err)
}
}
got := resolveCurrentTurnID(t, repo, sessionID)
switch {
case tc.ExpectedCurrentTurnID == nil && got != nil:
t.Fatalf("current turn = %s, want none to resolve", *got)
case tc.ExpectedCurrentTurnID != nil && got == nil:
t.Fatalf("current turn = none, want %s", *tc.ExpectedCurrentTurnID)
case tc.ExpectedCurrentTurnID != nil && got != nil && *got != *tc.ExpectedCurrentTurnID:
t.Fatalf("current turn = %s, want %s", *got, *tc.ExpectedCurrentTurnID)
}
})
}
}
@@ -8,6 +8,146 @@ import (
"github.com/kandev/kandev/internal/task/models"
)
// seedAuthorityTurn creates a turn with explicit started_at/created_at and an
// optional completed_at, so a test can control every key of D1's total order
// independently. A nil completedAt leaves the turn open.
func seedAuthorityTurn(
t *testing.T,
repo *Repository,
taskID, sessionID, turnID string,
startedAt, createdAt time.Time,
completedAt *time.Time,
metadata map[string]interface{},
) {
t.Helper()
if err := repo.CreateTurn(context.Background(), &models.Turn{
ID: turnID, TaskID: taskID, TaskSessionID: sessionID,
StartedAt: startedAt, CreatedAt: createdAt, CompletedAt: completedAt,
Metadata: metadata,
}); err != nil {
t.Fatalf("seed authority turn %s: %v", turnID, err)
}
}
// TestCurrentTurnAuthorityOrdering exercises D1's total order end-to-end
// through FindActiveClarificationMessagesBySessionID, which applies
// currentTurnAuthority with no extra completed_at filter (unlike
// GetActiveTurnBySessionID) so both open and completed turns compete. Each
// case seeds a pending clarification on exactly one of two candidate turns
// and asserts whether that message survives, which is only true when its
// turn resolves as current.
func TestCurrentTurnAuthorityOrdering(t *testing.T) {
base := time.Date(2026, time.August, 20, 12, 0, 0, 0, time.UTC)
completed := base.Add(-time.Hour)
for _, tt := range []struct {
name string
winnerID string
winnerStarted time.Time
winnerCreated time.Time
winnerDone *time.Time
loserID string
loserStarted time.Time
loserCreated time.Time
loserDone *time.Time
}{
{
// AC-5/AC-6: an open turn outranks a completed one regardless of
// which started earlier (R2). The completed turn here carries no
// lifecycle_only marker, matching a pre-existing legacy row.
name: "open turn beats later completed turn",
winnerID: "turn-ord-open",
winnerStarted: base,
winnerCreated: base,
winnerDone: nil,
loserID: "turn-ord-completed-later",
loserStarted: base.Add(time.Hour),
loserCreated: base.Add(time.Hour),
loserDone: &completed,
},
{
name: "later started_at wins among completed turns",
winnerID: "turn-ord-started-later",
winnerStarted: base.Add(time.Hour),
winnerCreated: base,
winnerDone: &completed,
loserID: "turn-ord-started-earlier",
loserStarted: base,
loserCreated: base,
loserDone: &completed,
},
{
name: "tie on started_at broken by later created_at",
winnerID: "turn-ord-created-later",
winnerStarted: base,
winnerCreated: base.Add(time.Minute),
winnerDone: &completed,
loserID: "turn-ord-created-earlier",
loserStarted: base,
loserCreated: base,
loserDone: &completed,
},
{
name: "tie on started_at and created_at broken by higher id",
winnerID: "turn-ord-tie-2",
winnerStarted: base,
winnerCreated: base,
winnerDone: &completed,
loserID: "turn-ord-tie-1",
loserStarted: base,
loserCreated: base,
loserDone: &completed,
},
} {
t.Run(tt.name, func(t *testing.T) {
repo := newRepoForSessionTests(t)
ctx := context.Background()
taskID := "task-" + tt.name
sessionID := "session-" + tt.name
seedSessionForTurns(t, repo, taskID, sessionID)
seedAuthorityTurn(t, repo, taskID, sessionID, tt.winnerID, tt.winnerStarted, tt.winnerCreated, tt.winnerDone, nil)
seedAuthorityTurn(t, repo, taskID, sessionID, tt.loserID, tt.loserStarted, tt.loserCreated, tt.loserDone, nil)
insertClarificationMessage(t, repo, "msg-"+tt.winnerID, sessionID, taskID, tt.winnerID, "pending-"+tt.winnerID, "q1", "pending", 0, tt.winnerStarted)
insertClarificationMessage(t, repo, "msg-"+tt.loserID, sessionID, taskID, tt.loserID, "pending-"+tt.loserID, "q1", "pending", 0, tt.loserStarted)
messages, err := repo.FindActiveClarificationMessagesBySessionID(ctx, sessionID)
if err != nil {
t.Fatalf("FindActiveClarificationMessagesBySessionID: %v", err)
}
if len(messages) != 1 || messages[0].TurnID != tt.winnerID {
t.Fatalf("messages = %+v, want exactly the winner turn %s's message", messages, tt.winnerID)
}
})
}
}
// TestCurrentTurnAuthorityTwoOpenTurnsResolvesDeterministically covers D2's
// observed half: at most one open turn per session is an invariant the
// repository does not enforce with a constraint, so resolution must still
// behave deterministically (not error) if it is ever violated. With both
// candidates open, D1's first key ties and the remaining keys (started_at,
// created_at, id, all descending) pick the winner exactly as they would for
// two completed turns.
func TestCurrentTurnAuthorityTwoOpenTurnsResolvesDeterministically(t *testing.T) {
repo := newRepoForSessionTests(t)
ctx := context.Background()
const taskID = "task-two-open-turns"
const sessionID = "session-two-open-turns"
seedSessionForTurns(t, repo, taskID, sessionID)
base := time.Date(2026, time.August, 21, 9, 0, 0, 0, time.UTC)
seedAuthorityTurn(t, repo, taskID, sessionID, "turn-open-older", base, base, nil, nil)
seedAuthorityTurn(t, repo, taskID, sessionID, "turn-open-newer", base.Add(time.Minute), base.Add(time.Minute), nil, nil)
active, err := repo.GetActiveTurnBySessionID(ctx, sessionID)
if err != nil {
t.Fatalf("GetActiveTurnBySessionID: %v", err)
}
if active == nil || active.ID != "turn-open-newer" {
t.Fatalf("active turn = %#v, want turn-open-newer (later started_at wins deterministically)", active)
}
}
func TestTurnAuthorityToleratesStringFlagEncodings(t *testing.T) {
for _, tt := range []struct {
name string
@@ -0,0 +1,70 @@
package sqlite
import (
"context"
"testing"
"time"
"github.com/kandev/kandev/internal/task/models"
)
// TestListTurnsBySessionKeepsLifecycleTurnVisible is AC-11's predicate half:
// turnHistoryPredicate SHALL keep including lifecycle turns in visible
// history, so the boot message stays grouped under its own turn in the
// transcript, even though currentTurnAuthority now excludes that same turn
// from current-turn resolution (AC-2/AC-3). GET .../turns
// (internal/task/handlers/task_http_handlers.go) calls ListTurnsBySession
// directly and DTO-converts every row it returns with no further filtering,
// so a lifecycle turn present here is a lifecycle turn present in that
// response.
func TestListTurnsBySessionKeepsLifecycleTurnVisible(t *testing.T) {
repo := newRepoForSessionTests(t)
ctx := context.Background()
seedSessionForTurns(t, repo, "task-turn-history-lifecycle", "session-turn-history-lifecycle")
base := time.Date(2026, 8, 24, 9, 0, 0, 0, time.UTC)
lifecycleTurn := &models.Turn{
ID: "turn-lifecycle-history",
TaskSessionID: "session-turn-history-lifecycle",
TaskID: "task-turn-history-lifecycle",
StartedAt: base,
CreatedAt: base,
CompletedAt: &base,
Metadata: map[string]interface{}{models.TurnMetaKeyLifecycleOnly: true},
}
conversationalTurn := &models.Turn{
ID: "turn-conversational-history",
TaskSessionID: "session-turn-history-lifecycle",
TaskID: "task-turn-history-lifecycle",
StartedAt: base.Add(time.Minute),
CreatedAt: base.Add(time.Minute),
}
for _, turn := range []*models.Turn{lifecycleTurn, conversationalTurn} {
if err := repo.CreateTurn(ctx, turn); err != nil {
t.Fatalf("CreateTurn(%s): %v", turn.ID, err)
}
}
turns, err := repo.ListTurnsBySession(ctx, "session-turn-history-lifecycle")
if err != nil {
t.Fatalf("ListTurnsBySession: %v", err)
}
ids := make(map[string]*models.Turn, len(turns))
for _, turn := range turns {
ids[turn.ID] = turn
}
if len(turns) != 2 {
t.Fatalf("ListTurnsBySession returned %d turns %+v, want both the lifecycle and conversational turn", len(turns), turns)
}
got, ok := ids[lifecycleTurn.ID]
if !ok {
t.Fatalf("ListTurnsBySession dropped the lifecycle turn %q; turnHistoryPredicate must keep it visible", lifecycleTurn.ID)
}
if lifecycleOnly, ok := got.Metadata[models.TurnMetaKeyLifecycleOnly]; !ok || lifecycleOnly != true {
t.Fatalf("returned lifecycle turn metadata[%q] = %v, want true", models.TurnMetaKeyLifecycleOnly, lifecycleOnly)
}
if _, ok := ids[conversationalTurn.ID]; !ok {
t.Fatalf("ListTurnsBySession dropped the conversational turn %q", conversationalTurn.ID)
}
}