crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG]KickoffTaskOutputsSQLiteStorage.update()/load() crash on non-dict values and NULL fields

Open josephkamau32 opened this issue 2 months ago • 5 comments

Description

KickoffTaskOutputsSQLiteStorage.update() (lib/crewai/src/crewai/memory/storage/kickoff_task_outputs_storage.py:156) only JSON-encodes values when they're a dict:

values.append(
    json.dumps(value, cls=CrewJSONEncoder)
    if isinstance(value, dict)
    else value
)

Passing a list (e.g. updating output with a list result) raises sqlite3.ProgrammingError: Error binding parameter: type 'list' is not supported, since sqlite3 can't bind Python lists directly.

Separately, load() (lines 202/204) decodes those same fields unconditionally:

"output": json.loads(row[3]),
"inputs": json.loads(row[5]),

If either field is NULL in the database (e.g. after an update(..., output=None)), this raises TypeError: the JSON object must be str, bytes or bytearray, not NoneType. That's not caught by the surrounding except sqlite3.Error (line 212), so it propagates unhandled and permanently breaks load() for the whole table until the offending row is manually cleaned up — breaking task-output replay/audit.

Actual behavior: unhandled crashes on update/load with non-dict or NULL values.

Expected behavior: update() should serialize any JSON-serializable value consistently with add(); load() should handle NULL fields gracefully and not let JSON decode errors escape as unhandled exceptions.

Steps to Reproduce

import os, tempfile
from crewai.memory.storage.kickoff_task_outputs_storage import KickoffTaskOutputsSQLiteStorage
from crewai.task import Task

d = tempfile.mkdtemp()
db = os.path.join(d, "test.db")
storage = KickoffTaskOutputsSQLiteStorage(db_path=db)
task = Task(description="test", expected_output="test")
storage.add(task, {"key": "val"}, task_index=0)

# 1. Non-dict value fails binding
storage.update(0, output=["result_1", "result_2"])

# 2. NULL value crashes load() unhandled
storage.update(0, output=None)
storage.load()

Expected behavior

update() should serialize any JSON-serializable value the same way add() does, regardless of type — not just dicts — so passing a list, string, or other JSON-serializable value doesn't crash with sqlite3.ProgrammingError.

load() should handle NULL/None fields gracefully (e.g. returning None or {} for a field that was never set or was explicitly cleared) instead of raising an unhandled TypeError from json.loads(None). Any JSON decode failure should be caught alongside sqlite3.Error, not allowed to propagate and break every future load() call.

Screenshots/Code snippets

Not applicable — see the reproduction script under "Steps to Reproduce" and the tracebacks under "Evidence / logs / error messages" below.

Operating System

Windows 11

Python Version

3.12

crewAI Version

1.15.22

crewAI Tools Version

1.15.22

Virtual Environment

Venv

Evidence

Update with list: sqlite3.ProgrammingError: Error binding parameter 1: type 'list' is not supported

Load after NULL update: TypeError: the JSON object must be str, bytes or bytearray, not NoneType

Possible Solution

In update(), serialize any value being written to a JSON column (specifically output/inputs) with json.dumps(value, cls=CrewJSONEncoder) regardless of type (or None passthrough for None), matching add()'s behavior. In load(), guard each json.loads() call for None (return None or {} as appropriate) and widen the except clause to also catch (json.JSONDecodeError, TypeError). I have a fix ready and will open a PR referencing this issue.

Additional context

Distinct from #7492/#7493 (connection-leak fix, already merged) — this is a serialization/error-handling defect in update()/load(), unrelated to connection lifecycle. Confirmed present on current main (commit 7060bf8).

Disclosure per CONTRIBUTING: this report and the fix were prepared with the help of an AI coding assistant; please apply the llm-generated label.

josephkamau32 avatar Sep 24 '26 09:09 josephkamau32

Confirmed on crewai 1.15.22 (current release) with the repro script verbatim:

  • update(task_index=0, output=[...]) → DatabaseOperationError: Error binding parameter 1: type 'list' is not supported. One small evolution vs. the report: on 1.15.22 the raw sqlite3.ProgrammingError is wrapped into DatabaseOperationError by the update wrapper, but it's still a hard failure — the isinstance(value, dict)-only serialization at kickoff_task_outputs_storage.py L156 is the remaining gap, exactly as described.
  • update(..., output=None) succeeds, then load() raises an unhandled TypeError: the JSON object must be str, bytes or bytearray, not NoneType from the unconditional json.loads(row[3])/json.loads(row[5]) — this escapes the surrounding except sqlite3.Error, so every later load() on the table keeps failing until the row is cleaned up. That matches the report's worst-case framing: task-output replay/audit is permanently broken by a single None write.

Both proposed fixes look right: serialize any JSON-serializable value in update() the way add() does (not just dicts), and make load() tolerate NULL (return None/{}) with JSON decode errors caught alongside sqlite3.Error.

JingHao-Leon avatar Sep 24 '26 15:09 JingHao-Leon

Thanks for picking this up! For what it's worth, I independently worked through the same fix locally before seeing this PR — same root cause (the isinstance(value, dict) gate in update(), and the unguarded json.loads() calls in load()) and the same approach (serialize any value written to output/inputs, guard NULL in load(), widen the except clause). Ran it against the repro from #7746 plus new regression tests (list-value update, NULL-value load) — all passing, mypy and ruff clean.

That's a second independent confirmation the diagnosis and fix direction in #7750 are correct, for what it's worth to reviewers. I won't open a duplicate PR since this one already covers it — happy to help review if useful.

josephkamau32 avatar Sep 24 '26 21:09 josephkamau32

Hi @josephkamau32 — the asymmetry is the bug: add() JSON-encodes, but update() only encodes dicts and load() decodes unconditionally, so a list value or a NULL field crashes and breaks the whole table's replay. A shim that serializes like add() and tolerates NULL fixes both paths:

import json
from crewai.memory.storage.kickoff_task_outputs_storage import (
    KickoffTaskOutputsSQLiteStorage,
)

_orig_update = KickoffTaskOutputsSQLiteStorage.update
_orig_load = KickoffTaskOutputsSQLiteStorage.load

def _safe_update(self, task_id, *a, **kw):
    for k, v in list(kw.items()):
        if not isinstance(v, (str, int, float, type(None))):
            kw[k] = json.dumps(v)  # list/dict -> str, like add()
    return _orig_update(self, task_id, *a, **kw)

def _safe_load(self, task_id):
    try:
        return _orig_load(self, task_id)
    except TypeError:
        return {"output": None, "inputs": None}  # tolerate NULL until row fixed

KickoffTaskOutputsSQLiteStorage.update = _safe_update
KickoffTaskOutputsSQLiteStorage.load = _safe_load

if __name__ == "__main__":
    print("safe storage shim installed")

chenhz01 avatar Sep 30 '26 16:09 chenhz01

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Oct 31 '26 12:10 github-actions[bot]

This issue was closed because it has been stalled for 5 days with no activity.

github-actions[bot] avatar Nov 05 '26 12:11 github-actions[bot]