rtk-ai/rtk · error

Failed to query first seen timestamp

Error message

Failed to query first seen timestamp: {e}

What it means

When computing usage statistics, tracking queries `SELECT MIN(timestamp) FROM commands` to find the first recorded command. Any rusqlite error other than an empty result set is wrapped in this anyhow error, meaning the DB could not be queried as expected.

Solutions

  1. Close other rtk processes and retry (SQLite lock contention is transient).
  2. Back up and delete the recall database so rtk recreates it with a fresh schema.
  3. Check the file permissions of the database file and its containing directory.
  4. Run `sqlite3 <db> 'PRAGMA integrity_check;'` to confirm corruption before deleting.

Example fix

// before
rm ~/.local/share/rtk/recall.db   # last resort only
// after
fuser ~/.local/share/rtk/recall.db  # find competing process, kill it, then retry
Defensive patterns

Strategy: retry

Validate before calling

import sqlite3
db = sqlite3.connect('~/.local/share/rtk/recall.db')
db.execute('SELECT MIN(timestamp) FROM commands')  # fails early if corrupted/locked
db.execute('PRAGMA integrity_check')

Try / catch

match tracking.first_seen() {
    Err(e) if e.to_string().contains("Failed to query first seen") => {
        // wait and retry once (lock contention), else recreate the db
    }
    other => other,
}

Prevention

When it happens

Trigger: Calling the gain/stats routine when the commands table is corrupted, locked by another process, the timestamp column has unexpected type, or the database file is unreadable — anything making query_row return a non-NoRows error.

Common situations: Concurrent rtk processes holding the SQLite lock; a corrupted ~/.local/share/rtk recall.db; a schema migrated by an incompatible rtk version; disk I/O errors.

Understand the failure class

Background: Database query failed: Internal Server Error 500s wrapping SQL, Prisma, and connection failures — what to check first — this error's family across 16 libraries.

Related errors


AI-assisted analysis of rtk-ai/rtk@0924356b4c (2026-09-19). Data as JSON: /api/errors/ac9c5819f13d4b08. Report an issue: GitHub.

Appendix: source

Thrown at src/core/tracking.rs:1402

        let pattern = format!("rtk {}", name);
        let count: i64 = self.conn.query_row(
            "SELECT COUNT(*) FROM commands WHERE rtk_cmd LIKE ?1 || '%'",
            params![pattern],
            |row| row.get(0),
        )?;
        Ok(count)
    }

    /// Days since first recorded command (installation age).
    pub fn first_seen_days(&self) -> Result<i64> {
        let oldest: Option<String> =
            match self
                .conn
                .query_row("SELECT MIN(timestamp) FROM commands", [], |row| row.get(0))
            {
                Ok(v) => v,
                Err(rusqlite::Error::QueryReturnedNoRows) => None,
                Err(e) => return Err(anyhow::anyhow!("Failed to query first seen timestamp: {e}")),
            };
        match oldest {
            Some(ts) => {
                let first = chrono::NaiveDateTime::parse_from_str(&ts, "%Y-%m-%dT%H:%M:%S")
                    .or_else(|_| chrono::NaiveDateTime::parse_from_str(&ts, "%Y-%m-%d %H:%M:%S"))
                    .map(|dt| dt.and_utc())
                    .unwrap_or_else(|_| chrono::Utc::now());
                let days = (chrono::Utc::now() - first).num_days();
                Ok(days.max(0))
            }
            None => Ok(0),
        }
    }

    /// Number of distinct active days in the last 30 days.
    pub fn active_days_30d(&self) -> Result<i64> {
        let since = (chrono::Utc::now() - chrono::Duration::days(30))
            .format("%Y-%m-%dT%H:%M:%S")

View on GitHub (pinned to 0924356b4c)