← Back to Pull requests

fix: report journal-derived execution state #228

Merged
ridhoq merged 32 files (1549 lines) on Oct 28, 2026 17:56 UTC
View on GitHub
ridhoq ridhoq commented on Oct 27, 2026 20:22 UTC
Author

Summary

Fixes agent-primitives/sessions#79.

  • Report the latest execution's journal-derived state consistently in every Session response: PENDING before execution, RUNNING while unfinished or uncertain, COMPLETED after END, FAILED after ERROR, and AWAITING for a valid owned pending approval.

  • Extend the existing execution/approval projection with an outcome maintained atomically during append. Reads use the shared projection with conservative guards for stale or inconsistent evidence, rather than folding event payloads on every Get/List.

  • Migrate SQLite from schema v6/v7/v8 to v9, preserving the upstream allocation and verified-approver migrations. Rebuild the projection without changing journal bytes, hashes, sequence numbers, or fences. Stop all older hosts and embedded CLIs before upgrading; mixed-version writes are unsupported.

  • Treat ID-less non-lifecycle records after modern execution as sticky reporting corruption during append and migration: report RUNNING and withhold pending approvals, while retaining genuine legacy-prefix compatibility. Include exec_state explicitly in the SessionStore/STORE-2 append-transaction contract.

  • Preserve execution identity and outcome semantics across recovery, compute lifecycle transitions, deletion, and historical forks. RUNNING is not a controller-liveness guarantee; liveness remains tracked separately in agent-primitives/sessions#213.

  • Expose execution state in agentctl get/list and lifecycle/approval status output. Update the public contract, migration notes, and manual-testing documentation.
  • Validation

  • Full root go test -race -shuffle=on ./..., build, vet, lint, govulncheck, and dependency neutrality checks passed.

  • The separate integrations/substrate module passed race tests, vet, and lint.

  • Real local Substrate micro-VM stateless, stateful/fork, deletion, and long-idle regressions passed.

  • Seven independently runnable live E2E cases cover pending sessions, successful turns, new turns after completion, durable failures, recovery, Suspend/Resume, and mid-execution forks; CI selects all seven.

  • Migration regressions cover v6/v7/v8 upgrades, read-only/fault rollback, verified-approver journal preservation, and legacy/modern identity-boundary violations.

  • Proto lint/breaking, regeneration drift checks, module tidy, provenance verifiers, documentation checks, and formatting passed.

  • Manual CLI checks and an independent adversarial correctness review completed. Corrected the review's mixed-version upgrade-warning finding and the CLI smoke-test expectations; the exact previously failing smoke test and a fresh full root race suite then passed.
  • Diff: 1549 lines (+1393 / -156) across 32 files Reviewer: aramase Review duration: 1293m
    All Vouch review confidence checks passed
    Residual risk 0.17 = Change Risk (0.72) × (1 − Review Confidence (0.76)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.72 · 1549 lines diff across 32 files
    0.72
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.52 · 5 substantive comment(s)
    0.52
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    75%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    13 items
    Copilot Copilot commented on code on Oct 27, 2026 20:28 UTC
    Code Review
    sqlitelog/execution_projection.go:1
    @@ -0,0 +1,43 @@
    +package sqlitelog
    +
    +import (
    +	"database/sql"
    +
    +	"github.com/agent-primitives/sessions/api"
    +)
    +
    +func migrateV6ToV7(tx *sql.Tx) error {
    +	if _, err := tx.Exec(`
    +ALTER TABLE approval_executions ADD COLUMN outcome TEXT NOT NULL DEFAULT 'RUNNING';
    +DELETE FROM approval_calls;
    +DELETE FROM approval_executions;
    +UPDATE sessions SET last_seq=0, latest_execution='', reporting_fork_seq=0,
    + approval_corrupt=0, invalid_approval_executions=0;`); err != nil {
    +		return err
    +	}
    +	// Rebuild the shared projection, including records from already-open older writers.
    +	return backfillExecutions(tx, projectExecution)
    +}
    +
    +func projectExecution(tx *sql.Tx, uid string, seq int64, ev api.Event) error {
    +	if err := projectApproval(tx, uid, seq, ev); err != nil {
    +		return err
    +	}
    +	if ev.Kind == api.EventLifecycle {
    +		return nil
    +	}
    +	outcome := api.ExecRunning

    An ID-less END after a modern INPUT reports COMPLETED even though EXE-16 forbids ID-less execution records after the legacy prefix and Replay/Resume reject this history. A later ID-less INPUT can also leave a completed modern execution reported as COMPLETED when an earlier legacy row already exists. Mark this boundary violation as sticky reporting corruption during append and migration backfill so both cases report RUNNING, while preserving genuine legacy prefixes.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Oct 27, 2026 20:28 UTC
    Reviewer

    <!-- ccr-overview-v2 -->

    🟡 Changes recommended

    Execution projection can incorrectly report COMPLETED for invalid ID-less records after the legacy prefix, requiring sticky corruption handling during append and migration backfill so affected histories report RUNNING.

    <details open>
    <summary><strong>1 open issue</strong></summary>

  • <picture><source media="(prefers-color-scheme: dark)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-dark.svg"><source media="(prefers-color-scheme: light)" srcset="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.svg"><img src="https://github.githubassets.com/static/images/icons/copilot-code-review/high-v2-light.png" alt="High severity" width="62" height="18" align="texttop"></picture> Prevent ID-less END from masking modern execution state · New

  • </details>

    <details>
    <summary><strong>1 file not reviewed</strong></summary>

    <ul>
    <li><strong><code>api/genpb/session.pb.go</code></strong>: Generated file</li>
    </ul>
    </details>

    <details>
    <summary><strong>What changed in this PR</strong></summary>

    This PR replaces the nonempty-journal COMPLETED fallback with journal-derived execution state across Session responses and CLI output. RUNNING represents unfinished or uncertain work, not controller liveness.

    Changes:

  • Add an atomic execution-outcome projection and SQLite v7 migration without changing journal evidence.

  • Expose execution state consistently in API responses and CLI status output.

  • Add migration, recovery, lifecycle, and end-to-end coverage, plus contract and upgrade documentation.
  • | File | Description |
    | ---- | ----------- |
    | sqlitelog/​sqlitelog.go | Register schema v7 and project outcomes during append. |
    | sqlitelog/​sessions.go | Read guarded execution state from the shared projection. |
    | sqlitelog/​execution_projection.go | Add outcome reduction and migration backfill. |
    | sqlitelog/​execution_projection_test.go | Cover outcomes, migration, corruption, and rollback. |
    | sqlitelog/​deletion_v3_migration_test.go | Preserve migration assertions across the new column. |
    | sqlitelog/​approval_projection.go | Share backfill logic between projection migrations. |
    | spec.md | Define execution-state semantics and upgrade requirements. |
    | session/​service.go | Render the store-projected execution state. |
    | session/​service_test.go | Check state during execution and recovery. |
    | session/​run_status_test.go | Assert FAILED after a journaled error. |
    | session/​delete_error_test.go | Supply explicit execution state in rendering fixtures. |
    | session/​delete_approval_test.go | Expect RUNNING after approval without completion. |
    | integrations/​substrate/​e2e/​session_fixture_test.go | Extract a reusable Sessions API fixture. |
    | integrations/​substrate/​e2e/​execution_state_test.go | Add seven execution-state end-to-end cases. |
    | integrations/​substrate/​e2e/​delete_fixture_test.go | Reuse the shared API fixture. |
    | docs/​substrate-conformance.md | Describe execution-state conformance coverage. |
    | docs/​quickstart.md | Update CLI examples and add manual checks. |
    | docs/​concepts.md | Explain state derivation, recovery, and migration. |
    | docs/​api-reference.md | Update generated execution-state documentation. |
    | cmd/​agentsessionsd/​lifecycle_e2e_test.go | Update CLI smoke expectations for execution state. |
    | cmd/​agentctl/​main.go | Display execution state in get/list and lifecycle output. |
    | cmd/​agentctl/​main_test.go | Test execution-state display and persistence. |
    | cmd/​agentctl/​approval.go | Display execution state after approval decisions. |
    | cmd/​agentctl/​approval_test.go | Assert execution state in approval output. |
    | CHANGELOG.md | Document v0.4.0 behavior and upgrade precautions. |
    | api/​state.go | Clarify RUNNING and FAILED comments. |
    | api/​session.proto | Document execution-state semantics without wire changes. |
    | api/​genpb/​session.pb.go | Reflect updated proto comments. |
    | .github/​workflows/​substrate-e2e.yml | Include execution-state tests in the stateless pass. |
    </details>

    <sub>Review effort: Balanced</sub>

    aramase aramase commented on code on Oct 27, 2026 21:17 UTC
    Code Review
    sqlitelog/sqlitelog.go:1
    @@ -87,8 +87,8 @@ CREATE INDEX IF NOT EXISTS sessions_project_created
     // v0.1.2 shipped. Version 2 adds the harness registry; version 3 adds approval reporting;
     // version 4 adds permanent deletion intent; version 5 adds caller ownership and an authorization marker;
     // version 6 records explicit session model-policy eligibility; version 7 adds the allocation
    -// ledger and inventory completeness/evidence columns.
    -const SchemaVersion = 7
    +// ledger and inventory completeness/evidence columns; version 8 adds execution outcomes.
    +const SchemaVersion = 8

    This claims schema v8, but main already uses v8 for #226's rung (migrateV7ToV8). A v8 journal written by main and opened by this build skips migration, and every SessionInfo/ListSessions then fails with no such column: a.outcome; the reverse direction opens fine but leaves outcome stale. Could you rebase onto main, keep #226's v7->v8 rung, and add this as migrateV8ToV9 with SchemaVersion = 9 (spec §18, CHANGELOG and concepts.md updated to v9), with the migration test extended through both rungs?

    aramase aramase commented on code on Oct 27, 2026 21:17 UTC
    Code Review
    spec.md:1
    @@ -191,16 +191,34 @@ no flattened lifecycle enum.
     - `SES-7`: `exec_state` MUST be derived from the log at `last_seq`, by reading it or from a
       projection updated in the same transaction as the append (`LOG-8`), which is what the reference
       host reads. The value is:
    +  - `EXEC_RUNNING` when the projection lags the journal head, missed earlier records, or the

    nit (non-blocking): this says invalid execution structure reports RUNNING, but a modern START/INPUT/OUTPUT followed by an ID-less END reports COMPLETED (and EXE-16 calls that history invalid). Either narrow the wording to the checks the reducer actually does, or treat an ID-less non-lifecycle record after a modern row as corrupt in projectExecution.

    aramase aramase commented on code on Oct 27, 2026 21:17 UTC
    Code Review
    api/state.go:1
    @@ -8,10 +8,10 @@ type ExecState string
     
     const (
     	ExecPending   ExecState = "PENDING"
    -	ExecRunning   ExecState = "RUNNING"
    +	ExecRunning   ExecState = "RUNNING"  // unfinished or uncertain, not confirmed controller liveness
     	ExecAwaiting  ExecState = "AWAITING" // blocked on approval/input, resolved from the log
     	ExecCompleted ExecState = "COMPLETED"
    -	ExecFailed    ExecState = "FAILED"
    +	ExecFailed    ExecState = "FAILED" // recorded error; recovery remains possible

    nit (non-blocking): "recovery remains possible" after FAILED holds for modern executions only; for a legacy ID-less prefix ERROR finishes the turn (controller/resume.go:45). spec.md:216 already says "modern"; same qualifier here and in session.proto:23?

    aramase aramase requested changes on Oct 27, 2026 21:17 UTC
    Changes Requested Reviewer

    Once #224 lands, its SessionStore contract (store.go comment and STORE-2) lists only last_seq, compute_state and pending_approval as append-transaction projections; with this PR ExecState also comes from the store, so whichever lands second should add it there.

    ridhoq ridhoq commented on code on Oct 28, 2026 15:55 UTC
    Code Review
    spec.md:1
    @@ -191,16 +191,34 @@ no flattened lifecycle enum.
     - `SES-7`: `exec_state` MUST be derived from the log at `last_seq`, by reading it or from a
       projection updated in the same transaction as the append (`LOG-8`), which is what the reference
       host reads. The value is:
    +  - `EXEC_RUNNING` when the projection lags the journal head, missed earlier records, or the

    Fixed the reducer rather than narrowing the contract in 2b0d853. A missing-ID non-lifecycle record after modern execution now sets sticky reporting corruption, so Get/List report RUNNING and withhold pending approval references. The shared reducer applies this during both append and migration; genuine legacy prefixes and session-scoped lifecycle records remain supported.

    ridhoq ridhoq commented on code on Oct 28, 2026 15:55 UTC
    Code Review
    sqlitelog/execution_projection.go:1
    @@ -0,0 +1,43 @@
    +package sqlitelog
    +
    +import (
    +	"database/sql"
    +
    +	"github.com/agent-primitives/sessions/api"
    +)
    +
    +func migrateV6ToV7(tx *sql.Tx) error {
    +	if _, err := tx.Exec(`
    +ALTER TABLE approval_executions ADD COLUMN outcome TEXT NOT NULL DEFAULT 'RUNNING';
    +DELETE FROM approval_calls;
    +DELETE FROM approval_executions;
    +UPDATE sessions SET last_seq=0, latest_execution='', reporting_fork_seq=0,
    + approval_corrupt=0, invalid_approval_executions=0;`); err != nil {
    +		return err
    +	}
    +	// Rebuild the shared projection, including records from already-open older writers.
    +	return backfillExecutions(tx, projectExecution)
    +}
    +
    +func projectExecution(tx *sql.Tx, uid string, seq int64, ev api.Event) error {
    +	if err := projectApproval(tx, uid, seq, ev); err != nil {
    +		return err
    +	}
    +	if ev.Kind == api.EventLifecycle {
    +		return nil
    +	}
    +	outcome := api.ExecRunning

    Fixed in 2b0d853. ID-less non-lifecycle records after modern execution now mark sticky session-level reporting corruption during append and migration. Later END records or newer executions cannot restore success or pending approvals. Added regressions for both reported histories, approval suppression, reopen, and genuine legacy-prefix compatibility.

    ridhoq ridhoq commented on code on Oct 28, 2026 15:55 UTC
    Code Review
    api/state.go:1
    @@ -8,10 +8,10 @@ type ExecState string
     
     const (
     	ExecPending   ExecState = "PENDING"
    -	ExecRunning   ExecState = "RUNNING"
    +	ExecRunning   ExecState = "RUNNING"  // unfinished or uncertain, not confirmed controller liveness
     	ExecAwaiting  ExecState = "AWAITING" // blocked on approval/input, resolved from the log
     	ExecCompleted ExecState = "COMPLETED"
    -	ExecFailed    ExecState = "FAILED"
    +	ExecFailed    ExecState = "FAILED" // recorded error; recovery remains possible

    Fixed in 2b0d853. Qualified recovery as modern-only in api/state.go and session.proto, including the Session field comment, and regenerated the derived documentation. concepts.md now explicitly explains that ERROR finishes a legacy turn for recovery purposes, so Resume does not rerun it.

    ridhoq ridhoq commented on code on Oct 28, 2026 15:55 UTC
    Code Review
    sqlitelog/sqlitelog.go:1
    @@ -87,8 +87,8 @@ CREATE INDEX IF NOT EXISTS sessions_project_created
     // v0.1.2 shipped. Version 2 adds the harness registry; version 3 adds approval reporting;
     // version 4 adds permanent deletion intent; version 5 adds caller ownership and an authorization marker;
     // version 6 records explicit session model-policy eligibility; version 7 adds the allocation
    -// ledger and inventory completeness/evidence columns.
    -const SchemaVersion = 7
    +// ledger and inventory completeness/evidence columns; version 8 adds execution outcomes.
    +const SchemaVersion = 8

    Fixed in 2b0d853: merged current main, kept migrateV7ToV8 unchanged, and moved execution outcomes to migrateV8ToV9 with SchemaVersion = 9. Migration coverage now starts at v6, v7 and v8, checks read-only/fault rollback, and preserves verified-approver journal bytes/hashes and allocation/inventory evidence. Updated the spec, concepts and changelog fragments under the new release workflow.

    ridhoq ridhoq commented on Oct 28, 2026 15:55 UTC
    Author

    Addressed the SessionStore follow-up now that #224 has landed: session/store.go and STORE-2 explicitly include ExecState / exec_state among the projections committed atomically with journal appends. This and the inline review fixes are in 2b0d853.

    aramase aramase approved these changes on Oct 28, 2026 17:53 UTC
    Approved Reviewer

    LGTM. The schema now moves v8 to v9 on top of #226, and the migration, rollback and docs line up.

    One nit outside the diff: docs/interaction-model.md:177 still links to concepts.md "for the compatibility fallback", which this PR removes. Consider changing the link text to "for execution-state derivation".

    Reviewers
    Assignees
    ridhoq ridhoq
    Labels
    risk: low confidence: 75.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 71.5% (HIGH) · Higher = larger blast radius
    71.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 75.8% · Lower = rushed or shallow review
    75.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.3% · Safe to merge
    17.3%