Skip to content

BUG: session_message.seq NOT NULL constraint failed on agent-switched sessions #31204

Closed

Description

@High-cla

Description

SQLiteError: NOT NULL constraint failed: session_message.seq

After the latest OpenCode update (migrations from June 3-5 adding session_message projection table), any session that triggers an agent switch crashes with this error. The �ppendMessage() function's code path for session.next.agent.switched does not provide a seq value when inserting into the session_message table, but the column is defined as INTEGER NOT NULL with no default value.

Error stack trace:
SQLiteError: NOT NULL constraint failed: session_message.seq at run (unknown) at #run (bun:sqlite:185:20) at appendMessage (B:/~BUN/root/chunk-j582v44c.js:2:62480) at session.next.agent.switched (B:/~BUN/root/chunk-j582v44c.js:2:56601) at SessionPrompt.createUserMessage (B:/~BUN/root/chunk-rsc45ft5.js:1677:366)

Root cause:
The session_message table schema has seq integer NOT NULL with NO DEFAULT. When �ppendMessage() is called during session.next.agent.switched, it inserts into session_message without providing the seq field.

Relevant migrations:

  • 20260603001617_session_message_projection_indexes
  • 20260603040000_session_message_projection_order
  • 20260603160727_jittery_ezekiel_stane

Evidence:

  • session_message table has 0 rows (every insert fails)
  • Old message table has 680+ rows (old system still works)
  • Error only triggers on session.next.agent.switched path
  • seq column has NOT NULL but NO DEFAULT

Workaround:
sql ALTER TABLE session_message RENAME TO session_message_old; CREATE TABLE session_message ( id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL, seq integer NOT NULL DEFAULT 0, CONSTRAINT fk_session_message_session_id_session_id_fk FOREIGN KEY (session_id) REFERENCES session(id) ON DELETE CASCADE ); INSERT INTO session_message SELECT * FROM session_message_old; DROP TABLE session_message_old;

Plugins

oh-my-openagent, opencode-agent-skills, aegis

OpenCode version

Recent build (auto-updated ~June 6, 2026)

Steps to reproduce

  1. Run OpenCode with oh-my-openagent plugin (agent switching behavior)
  2. Trigger a workflow that causes session.next.agent.switched
  3. Observe the error: NOT NULL constraint failed: session_message.seq

Operating System

Windows 11

Terminal

Windows Terminal / PowerShell 7

Activity

  1. gutierrezje commented on Jun 7, 2026

    @gutierrezje

    Reproduced on OpenCode 1.16.2 under WSL2 with no plugins. An SDK session.promptAsync() call that supplies a system prompt triggers session.next.agent.switched, then fails inserting into session_message because seq is omitted. PRAGMA integrity_check returns ok; session_message contains zero rows. Resetting the database seems to resolve the issue because the fresh 1.16.2 schema no longer contains seq.

  2. tiffanychum commented on Jun 7, 2026

    @tiffanychum

    I'd like to work on this. Two issues in insertMessage in projector.ts: (1) time_updated is not provided on INSERT — the column is NOT NULL but only has $onUpdate (no $default); (2) the seq guard uses === undefined and misses null values from deserialized events. Fix: explicitly set time_updated and change guard to == null. PR coming shortly.

  3. KirillDeviatka commented on Jun 8, 2026

    @KirillDeviatka

    I originally suspected issue #31204 (missing seq population), but in my environment the immediate operational cause was runtime/schema skew. Upgrading the CLI to the same release family as the database migration owner (1.16.2) immediately restored normal operation and new session_message rows were written successfully.

    Let me give details here:

    Root Cause Analysis: session_message.seq failures caused by schema/runtime version mismatch after June 2026 migrations
    Summary

    It was investigated recurring failures of the form:

    text SQLiteError: NOT NULL constraint failed: session_message.seq

    and initially suspected a broken insert path in the current runtime.
    After a full forensic audit of the production database, migration history, installed binaries, and isolated reproductions, the root cause appears to be a schema/runtime version mismatch rather than database corruption.

    Findings

    Production environment contained:
    text CLI binary: OpenCode 1.15.7 Desktop app: OpenCode 1.16.2 Database: migrated with June 2026 migrations

    The production database contained migration:
    text 20260603040000_session_message_projection_order

    which introduces:
    sql ALTER TABLE session_message ADD COLUMN seq INTEGER NOT NULL;

    and creates:
    sql CREATE UNIQUE INDEX session_message_session_seq_idx ON session_message(session_id, seq);

    The live database confirmed:
    text session_message.seq exists seq is NOT NULL (session_id, seq) unique index exists

    However, OpenCode CLI 1.15.7 predates those migrations.

    Evidence
    Production DB:
    text migration table: 32 rows __drizzle_migrations: 21 rows

    June 2026 migrations existed in migration but were not part of the older CLI migration bundle.

    Database schema:
    text session_message: id session_id type time_created time_updated data seq INTEGER NOT NULL

    CLI versions discovered:
    text ~/.opencode/bin/opencode 1.15.7 /opt/homebrew/bin/opencode 1.14.19 OpenCode Desktop 1.16.2

    Reproduction
    A clean isolated database created by OpenCode 1.15.7 does NOT contain the seq column.

    Fresh schema:
    text session_message: id session_id type time_created time_updated data

    No seq column exists.
    Running OpenCode 1.15.7 against that clean schema does not trigger the failure.
    The failure only appears when:
    text old runtime (1.15.7) + newer database schema (seq migration applied)

    Observed failure
    When CLI 1.15.7 attempts to write session_message rows against the migrated schema:
    text SQLiteError: NOT NULL constraint failed: session_message.seq

    because the older runtime does not populate seq while the database requires it.

    What likely happened
    A newer OpenCode build (Desktop 1.16.2 or equivalent runtime) migrated the shared database and applied June 2026 schema changes.
    The CLI remained on 1.15.7.
    After that:
    text Database schema = new CLI runtime = old

    which created an unsupported combination.
    Workaround used
    The successful workaround was:
    text Upgrade CLI from 1.15.7 to 1.16.2

    Command:

    bash ~/.opencode/bin/opencode upgrade v1.16.2

    Verification
    Before upgrade:
    text session_message rows: 22 opencode run: fails NOT NULL constraint failed: session_message.seq

    After upgrade:
    text CLI version: 1.16.2 opencode run: success session_message rows: 22 -> 24 exit code: 0

    Minimal test:
    bash OPENCODE_RUN=1 opencode run \ --format json \ "Reply with one word: ok"

    returned successfully and new session_message rows were written.

    Impact
    This issue can occur whenever:
    text Database migrated by newer runtime CLI remains on older version
    especially when Desktop and CLI installations are upgraded independently.

    Suggested improvements

    1. Runtime startup compatibility check

    Detect:
    text DB schema version > runtime schema version
    and fail with a clear message.

    1. Migration ownership tracking
      Store runtime version alongside migration execution.

    2. Upgrade warning
      When Desktop upgrades a shared database, warn if older CLI binaries are detected.

    3. Explicit compatibility error
      Instead of:
      text NOT NULL constraint failed: session_message.seq
      return:
      text Database schema is newer than this OpenCode runtime. Please upgrade OpenCode CLI.

    Final conclusion
    The production database was not corrupted.
    The failure was caused by a version skew:
    text Database schema migrated by newer OpenCode runtime + CLI 1.15.7 executing against that schema

    Upgrading the CLI to the same version as the runtime that performed the migration resolved the issue without modifying user data.

  4. coygeek commented on Jun 8, 2026

    @coygeek

    Adding a second reproduction + workaround confirmation from macOS 26 (Apple Silicon), Homebrew-managed opencode 1.15.13 in /opt/homebrew/bin, no plugins:

    Reproduction (macOS 26, no plugins, model=opencode-go/minimax-m3):

    $ opencode run --model opencode-go/minimax-m3 --dir "$PWD" --dangerously-skip-permissions "echo hello"
    Error: { "name": "UnknownError", "data": { "message": "Unexpected server error.", "ref": "err_c822fa6f" } }
    
    # Server log:
    ERROR service=server ref=err_c822fa6f error=NOT NULL constraint failed: session_message.seq
      at appendMessage (chunk-9re0szbd.js:2:62522)
      at session.next.agent.switched (chunk-9re0szbd.js:2:56643)
      at SessionPrompt.createUserMessage
    

    Identical stack to the report above, but the trigger was the very first opencode run prompt — no agent switching was required. The same appendMessage path is reached on initial session creation.

    Two co-existing installs on this host:

    • /opt/homebrew/bin/opencode -> opencode-ai@1.15.13 (npm, broken)
    • /Users/chaos/.opencode/bin/opencode -> 1.16.2 (standalone, working)

    Workaround that worked: use the canonical 1.16.2 binary at $HOME/.opencode/bin/opencode (the path the upstream install script chooses per the README's priority 4). No DB migration or wipe was needed; the existing migrated schema was honored by the newer runtime and session_message rows started inserting normally.

    So: confirmed on a clean install with no plugins, the same root cause (CLI 1.15.x does not populate seq for the new projection migrations), and the same operational fix (upgrade the CLI to the same family that wrote the migration).

  5. NotSleeply commented on Jun 11, 2026

    @NotSleeply

    Adding another reproduction from Windows + Paseo's OpenCode provider.\n\nEnvironment:\n- Windows 10/11 host\n- Paseo 0.1.93 launching provider: opencode/cliproxyapi/gpt-5.5\n- opencode CLI on PATH: 1.15.13 at C:\Users\Administrator\.bun\bin\opencode.exe\n- Shared DB: C:\Users\Administrator\.local\share\opencode\opencode.db\n\nSymptom:\nCreating a new OpenCode-backed agent through Paseo fails immediately before model output. The first write path is session.next.agent.switched, then �ppendMessage fails with:\n\n\nSQLiteError: NOT NULL constraint failed: session_message.seq\n at appendMessage (...)\n at session.next.agent.switched (...)\n at SessionPrompt.createUserMessage (...)\n at SessionPrompt.prompt (...)\n\n\nLocal DB checks:\n- PRAGMA integrity_check returned ok\n- session_message schema included seq integer NOT NULL and unique index (session_id, seq)\n- New failed sessions had zero message rows, so this was not caused by a corrupt existing row\n\nThis matches the version-skew explanation above: a newer migration had added the seq requirement, while the runtime writing the initial �gent-switched message was still 1.15.13 and did not provide seq.\n\nTemporary local workaround used only to unblock Paseo: backed up the DB, relaxed session_message.seq to nullable, and added an AFTER INSERT trigger to fill missing seq as MAX(seq)+1 per session. After that, a new Paseo OpenCode smoke-test agent completed and wrote:\n- �gent-switched, seq=0\n- model-switched, seq=1\n\nThe better upstream fix still seems to be either runtime/schema compatibility detection or making the insert path handle missing/null seq for projected messages.

  6. JustSidus commented on Jun 12, 2026

    @JustSidus

    PR #31419 by @Cain-Brouwer is working on this exact issue - guarding against null event.seq when inserting session_messages.

  7. cjb1234567 commented on Jun 17, 2026

    @cjb1234567

    [verified] Upgrade opencode to the latest version, or downgrade to previous(if you are already using the latest version) will solve this problem.

    command:
    opencode upgrade v1.17.7
    or
    opencode upgrade v1.17.6

  8. mwgahed commented on Sep 14, 2026

    @mwgahed

    وصف

    خطأ في SQLite: فشل قيد NOT NULL: session_message.seq

    بعد آخر تحديث لـ OpenCode (عمليات الترحيل من 3 إلى 5 يونيو التي أضافت جدول عرض session_message)، تتعطل أي جلسة تُفعّل تبديل الوكيل مع ظهور هذا الخطأ. مسار الكود الخاص بدالة 'ppendMessage()' لـ session.next.agent.switched لا يُوفّر قيمة تسلسلية عند الإدراج في جدول session_message، مع العلم أن العمود مُعرّف كـ INTEGER NOT NULL بدون قيمة افتراضية.

    تتبع أخطاء النظام: SQLiteError: NOT NULL constraint failed: session_message.seq at run (unknown) at #run (bun:sqlite:185:20) at appendMessage (B:/~BUN/root/chunk-j582v44c.js:2:62480) at session.next.agent.switched (B:/~BUN/root/chunk-j582v44c.js:2:56601) at SessionPrompt.createUserMessage (B:/~BUN/root/chunk-rsc45ft5.js:1677:366)

    السبب الجذري: يحتوي مخطط جدول session_message على قيمة تسلسلية من نوع عدد صحيح غير فارغة (NO DEFAULT). عند استدعاء الدالة 'ppendMessage()' أثناء عملية تبديل الوكيل التالي (session.next.agent.switched)، يتم إدراج البيانات في جدول session_message دون تحديد الحقل التسلسلي (seq).

    عمليات الترحيل ذات الصلة:

    • 20260603001617_session_message_projection_indexes
    • 20260603040000_session_message_projection_order
    • 20260603160727_jittery_ezekiel_stane

    شهادة:

    • يحتوي جدول session_message على 0 صفوف (كل عملية إدخال تفشل)
    • يحتوي جدول الرسائل القديم على أكثر من 680 صفًا (لا يزال النظام القديم يعمل)
    • يحدث الخطأ فقط على مسار session.next.agent.switched
    • عمود التسلسل لا يحتوي على قيمة فارغة ولكن ليس له قيمة افتراضية

    الحل البديل: sql ALTER TABLE session_message RENAME TO session_message_old; CREATE TABLE session_message ( id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL, seq integer NOT NULL DEFAULT 0, CONSTRAINT fk_session_message_session_id_session_id_fk FOREIGN KEY (session_id) REFERENCES session(id) ON DELETE CASCADE ); INSERT INTO session_message SELECT * FROM session_message_old; DROP TABLE session_message_old;

    الإضافات

    oh-my-openagent, opencode-agent-skills, aegis

    إصدار مفتوح المصدر

    الإصدار الأخير (تم تحديثه تلقائيًا في 6 يونيو 2026 تقريبًا)

    خطوات إعادة الإنتاج

    1. تشغيل OpenCode باستخدام إضافة oh-my-openagent (سلوك تبديل الوكيل)
    2. تشغيل سير عمل يؤدي إلى تبديل الوكيل التالي في الجلسة
    3. لاحظ الخطأ: فشل قيد NOT NULL: session_message.seq

    نظام التشغيل

    ويندوز 11

    صالة

    ويندوز تيرمينال / باور شيل 7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions