Skip to content

Query Errors

deep_db_agents.query_errors

Turns query execution exceptions into feedback for the agent.

When the LLM generates an invalid query (syntax error, non-existent table/column/field, incompatible operator or type, ...), the database driver raises an exception. Instead of propagating it opaquely — interrupting the agent's turn — the tools convert it into a structured message the agent can read to fix the query on the next attempt: error handling becomes part of the feedback loop, not a terminal failure.

Whitelist/scope violations (QueryNotAllowedError: out-of-scope index/collection, disallowed stage or write clauses, malformed query) also flow through here and become feedback: the forbidden operation is still not executed — it is blocked before reaching the driver — but the rejection is communicated to the agent as a corrective message rather than interrupting the turn. The EXPLAIN row-estimate guardrail (EstimateExceededError) is handled the same way by format_estimate_block: the query is not executed, but the agent is asked to refine or aggregate and retry. The session row budget (RowBudgetExceededError from SessionBudget) is likewise turned into feedback by format_budget_block: the query did run, but its result is not returned, and the agent is asked to aggregate/summarize or start a new session.

Failures while preparing the session (SessionSetupError: connection or timeout setup) are the exception to "fix and retry": they are not caused by the query, so format_setup_error tells the agent to stop and report them instead of looping. Drivers that connect lazily (MongoDB, Neo4j, Elasticsearch, OpenSearch) only reach the server on the first operation, so their connection/auth errors are recognized by setup_failures.

format_budget_block

format_budget_block(exc: RowBudgetExceededError, *, what: str = 'query') -> str

Format a session row-budget exhaustion as corrective feedback.

Turns the RowBudgetExceededError raised by SessionBudget.charge into a message the agent can act on: the query did run, but its result is not returned because the cumulative session row budget is exhausted, so the agent should aggregate/summarize in the database or start a new session instead of extracting more rows.

Parameters:

Name Type Description Default
exc RowBudgetExceededError

The guardrail exception raised when the budget was exceeded; its message already describes the consumed rows and the budget.

required
what str

Label for the blocked construct ("query", "search", ...), used in the message.

'query'

Returns:

Name Type Description
str str

A message describing the block, suitable for returning to the agent as tool

str

output.

Source code in src/deep_db_agents/query_errors.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def format_budget_block(exc: RowBudgetExceededError, *, what: str = "query") -> str:
    """Format a session row-budget exhaustion as corrective feedback.

    Turns the ``RowBudgetExceededError`` raised by ``SessionBudget.charge`` into a message
    the agent can act on: the query did run, but its result is **not returned** because the
    cumulative session row budget is exhausted, so the agent should aggregate/summarize in
    the database or start a new session instead of extracting more rows.

    Args:
        exc: The guardrail exception raised when the budget was exceeded; its message already
            describes the consumed rows and the budget.
        what: Label for the blocked construct (``"query"``, ``"search"``, ...), used in the
            message.

    Returns:
        str: A message describing the block, suitable for returning to the agent as tool
        output.
    """
    detail = str(exc).strip() or "(no detail provided)"
    # The block is corrective feedback for the agent, but also an observable event on the
    # operator side: logged alongside the reflected message.
    _logger.warning("%s blocked by the session row budget: %s", what, detail)
    return "\n".join(
        [
            f"Warning: the {what} result is NOT returned — the session row budget is exhausted.",
            f"Detail: {detail}",
            "Stop extracting rows: aggregate or summarize in the database to reduce volume, "
            "or start a new session to reset the budget.",
        ]
    )

format_estimate_block

format_estimate_block(exc: EstimateExceededError, *, what: str = 'query') -> str

Format an EXPLAIN row-estimate guardrail block as corrective feedback.

Turns the EstimateExceededError raised by GuardrailConfig.check_estimate into a message the agent can act on: the query was not executed because its estimated result set is too large, so the agent should refine its filters or aggregate and retry.

Parameters:

Name Type Description Default
exc EstimateExceededError

The guardrail exception raised when the estimate exceeded the threshold; its message already describes the estimate and the threshold.

required
what str

Label for the blocked construct ("query", "search", ...), used in the message.

'query'

Returns:

Name Type Description
str str

A message describing the block, suitable for returning to the agent as tool

str

output.

Source code in src/deep_db_agents/query_errors.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def format_estimate_block(exc: EstimateExceededError, *, what: str = "query") -> str:
    """Format an EXPLAIN row-estimate guardrail block as corrective feedback.

    Turns the ``EstimateExceededError`` raised by ``GuardrailConfig.check_estimate`` into
    a message the agent can act on: the query was **not executed** because its estimated
    result set is too large, so the agent should refine its filters or aggregate and retry.

    Args:
        exc: The guardrail exception raised when the estimate exceeded the threshold; its
            message already describes the estimate and the threshold.
        what: Label for the blocked construct (``"query"``, ``"search"``, ...), used in
            the message.

    Returns:
        str: A message describing the block, suitable for returning to the agent as tool
        output.
    """
    detail = str(exc).strip() or "(no detail provided)"
    # The block is corrective feedback for the agent, but also an observable event on the
    # operator side: logged alongside the reflected message.
    _logger.warning("%s blocked by the estimate guardrail: %s", what, detail)
    return "\n".join(
        [
            f"Warning: the {what} was NOT executed by the database.",
            f"Detail: {detail}",
            f"Narrow the {what} with more selective filters or aggregate in the database "
            "to reduce the estimated result set, then retry.",
        ]
    )

format_query_error

format_query_error(exc: Exception, *, query: str | None = None, what: str = 'query') -> str

Format a driver exception as corrective feedback for the agent.

Parameters:

Name Type Description Default
exc Exception

The exception raised during execution (database driver error).

required
query str | None

The text of the submitted query/pipeline; included in the feedback if present, so the agent sees exactly what it got wrong.

None
what str

Label for the executed construct ("query", "pipeline", "Cypher query"), used in the message.

'query'

Returns:

Name Type Description
str str

A multi-line message describing the failure, suitable for returning to

str

the agent as tool output.

Source code in src/deep_db_agents/query_errors.py
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def format_query_error(exc: Exception, *, query: str | None = None, what: str = "query") -> str:
    """Format a driver exception as corrective feedback for the agent.

    Args:
        exc: The exception raised during execution (database driver error).
        query: The text of the submitted query/pipeline; included in the feedback if
            present, so the agent sees exactly what it got wrong.
        what: Label for the executed construct (``"query"``, ``"pipeline"``,
            ``"Cypher query"``), used in the message.

    Returns:
        str: A multi-line message describing the failure, suitable for returning to
        the agent as tool output.
    """
    detail = _redact_secrets(str(exc).strip()) or "(no detail provided by the driver)"
    # The error becomes feedback for the agent, but it is also an observable event on
    # the operator side (failed or blocked query): logged with credentials already
    # redacted from the detail.
    _logger.warning("%s not executed: %s: %s", what, type(exc).__name__, detail)
    lines = [
        f"Error: the {what} was NOT executed by the database.",
        f"Error type: {type(exc).__name__}",
        f"Detail: {detail}",
    ]
    if query:
        text = query.strip()
        if len(text) > _MAX_QUERY_CHARS:
            text = text[:_MAX_QUERY_CHARS] + " …[truncated]"
        lines.append(f"{what.capitalize()} submitted:\n{text}")
    lines.append(
        f"The database rejected the request. Fix the {what} based on the error "
        "detail (syntax, table/column/field names, types or operators) and retry; "
        "if needed, inspect the schema first with the exploration tools."
    )
    return "\n".join(lines)

format_setup_error

format_setup_error(exc: SessionSetupError, *, what: str = 'query') -> str

Format a session setup failure as feedback that stops the agent from retrying.

Unlike :func:format_query_error, the failure happened while opening the connection or configuring the session (e.g. the query timeout), so it is not caused by the agent's request: telling the agent to fix and retry would only make it rewrite a correct query in a loop. The message tells it to stop and report the problem instead.

Parameters:

Name Type Description Default
exc SessionSetupError

The setup exception; the driver exception, if any, is its __cause__.

required
what str

Label for the construct that was not executed ("query", "count", ...), used in the message.

'query'

Returns:

Name Type Description
str str

A multi-line message describing the failure, suitable for returning to the

str

agent as tool output.

Source code in src/deep_db_agents/query_errors.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def format_setup_error(exc: SessionSetupError, *, what: str = "query") -> str:
    """Format a session setup failure as feedback that stops the agent from retrying.

    Unlike :func:`format_query_error`, the failure happened while opening the connection
    or configuring the session (e.g. the query timeout), so it is **not** caused by the
    agent's request: telling the agent to fix and retry would only make it rewrite a
    correct query in a loop. The message tells it to stop and report the problem instead.

    Args:
        exc: The setup exception; the driver exception, if any, is its ``__cause__``.
        what: Label for the construct that was not executed (``"query"``, ``"count"``,
            ...), used in the message.

    Returns:
        str: A multi-line message describing the failure, suitable for returning to the
        agent as tool output.
    """
    cause = exc.__cause__ or exc
    detail = str(exc).strip()
    if cause is not exc:
        cause_detail = str(cause).strip() or "(no detail provided by the driver)"
        detail = f"{detail} {cause_detail}".strip()
    detail = _redact_secrets(detail) or "(no detail provided)"
    _logger.error("database session setup failed: %s: %s", type(cause).__name__, detail)
    return "\n".join(
        [
            f"Error: the database session could not be prepared; the {what} was NOT executed.",
            f"Error type: {type(cause).__name__}",
            f"Detail: {detail}",
            "This is a connection or configuration problem, NOT caused by your "
            f"{what}. Do not modify or retry the {what}: stop and report this error "
            "to the user.",
        ]
    )

setup_failures

setup_failures(is_setup_failure: Callable[[Exception], bool]) -> Iterator[None]

Re-raise the connection/auth failures raised inside the block as SessionSetupError.

Drivers with a lazy client (pymongo, neo4j, elasticsearch-py, opensearch-py) contact the server only on the first operation, so connection and authentication errors surface there, mixed with real query errors: the dialect-specific classifier tells them apart.

Parameters:

Name Type Description Default
is_setup_failure Callable[[Exception], bool]

Returns True for a driver exception caused by the connection or the credentials rather than by the agent's request.

required

Yields:

Type Description
None

None.

Raises:

Type Description
SessionSetupError

If the block raises an exception classified as a setup failure; the driver exception is chained as __cause__. Other exceptions propagate unchanged.

Source code in src/deep_db_agents/query_errors.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
@contextmanager
def setup_failures(is_setup_failure: Callable[[Exception], bool]) -> Iterator[None]:
    """Re-raise the connection/auth failures raised inside the block as ``SessionSetupError``.

    Drivers with a lazy client (pymongo, neo4j, elasticsearch-py, opensearch-py) contact the
    server only on the first operation, so connection and authentication errors surface there,
    mixed with real query errors: the dialect-specific classifier tells them apart.

    Args:
        is_setup_failure: Returns ``True`` for a driver exception caused by the connection or
            the credentials rather than by the agent's request.

    Yields:
        None.

    Raises:
        SessionSetupError: If the block raises an exception classified as a setup failure; the
            driver exception is chained as ``__cause__``. Other exceptions propagate unchanged.
    """
    try:
        yield
    except Exception as exc:
        if is_setup_failure(exc):
            raise SessionSetupError(
                "Could not connect to or authenticate with the database."
            ) from exc
        raise