Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(qveris): refuse bars whose adjustment it cannot state, and quotes that bound nothing

Haozhe Wudcf811369d0f
diff --git a/agent/backtest/loaders/qveris_loader.py b/agent/backtest/loaders/qveris_loader.py
index e32f45782..bb02ac70c 100644
--- a/agent/backtest/loaders/qveris_loader.py
+++ b/agent/backtest/loaders/qveris_loader.py
@@ -17,6 +17,7 @@ import json
import logging
import math
import os
+import re
import time
from dataclasses import dataclass
from pathlib import Path
@@ -25,12 +26,14 @@ from typing import Any, Dict, Iterable, List, Optional
import pandas as pd
import requests
+from backtest.engines._market_hooks import _detect_market
from backtest.loaders.base import (
+ NoAvailableSourceError,
cached_loader_fetch,
validate_date_range,
validate_ohlc,
)
-from backtest.loaders.registry import register
+from backtest.loaders.registry import market_has_corporate_actions, register
logger = logging.getLogger(__name__)
@@ -51,6 +54,14 @@ _DATE_KEYS = (
"time",
"period",
)
+#: A quote bounds the bill only when it is a flat price per call: "24.2
+#: credits", "1 credits/call", or a bare number. ``cn_financial_pro.
+#: history_quotation.v1`` quoted "1 credits/result" and billed 9.66 credits for
+#: one stock-year, 244 rows x 30 fields at 0.00132 credits a value (#1494), so
+#: a quote priced per any other unit, or in a shape not listed here, reserves
+#: nothing that caps the charge and prices as unknown.
+_FLAT_QUOTE = re.compile(r"(\d+(?:\.\d+)?)\s*(?:credits?)?\s*(?:(?:/|per)\s*(call|request))?")
+
#: The four fields that must all be present for a record to become a bar.
_PRICE_QUARTET = ("open", "high", "low", "close")
@@ -290,7 +301,7 @@ class DataLoader:
"""QVeris OHLCV loader, available only when explicitly configured."""
name = "qveris"
- markets = {"us_equity", "hk_equity", "a_share", "crypto", "forex", "fund", "macro"}
+ markets = {"crypto", "forex", "macro"}
requires_auth = True
def __init__(self) -> None:
@@ -326,9 +337,30 @@ class DataLoader:
Raises:
ValueError: If ``start_date`` > ``end_date``.
+ NoAvailableSourceError: If a symbol belongs to a market with
+ corporate actions, whose price adjustment this loader cannot
+ establish (#1494). Nothing is fetched or billed.
"""
del fields
validate_date_range(start_date, end_date)
+ # A market with splits and dividends would be served by whichever
+ # capability ranks first in search, and the ranking ignores adjustment:
+ # for 600519.SH the top pick was FMP's non_split_adjusted EOD, and
+ # mkt_bars_adjusted routed to a tool whose adj_close equalled the raw
+ # closes (#1494). No capability is pinned to a measured adjustment, so
+ # such a bar has no caliber anyone can state, and "unknown" stays out of
+ # every run-level caliber check. Refused before anything is billed.
+ refused = {code: _detect_market(code) for code in codes}
+ refused = {code: market for code, market in refused.items() if market_has_corporate_actions(market)}
+ if refused:
+ raise NoAvailableSourceError(
+ "source='qveris' does not serve markets with splits and dividends: it "
+ "picks a capability by search rank, which ignores price adjustment, so "
+ "these bars would reach the run at an adjustment nobody can state "
+ "(#1494). Refused: "
+ + ", ".join(f"{code} ({market})" for code, market in refused.items())
+ + ". Use a source with a measured price caliber for these symbols."
+ )
if not self.is_available():
logger.warning("qveris fetch skipped: disabled or %s not set", _API_KEY_ENV)
return {}
@@ -377,12 +409,16 @@ class DataLoader:
if not tool_id:
continue
quoted_cost = _expected_cost(capability.get("expected_cost"))
- if (
- not math.isfinite(quoted_cost)
- or quoted_cost < 0.0
- or budget_state["spent"] + quoted_cost
- > self._config.budget_credits_per_session
- ):
+ if not math.isfinite(quoted_cost):
+ logger.warning(
+ "QVeris capability %s skipped for %s: quote %r is not a flat "
+ "price per call, so no reservation bounds its bill",
+ tool_id,
+ code,
+ capability.get("expected_cost"),
+ )
+ continue
+ if budget_state["spent"] + quoted_cost > self._config.budget_credits_per_session:
logger.warning(
"QVeris paid capability skipped for %s: credit budget exceeded",
code,
@@ -496,20 +532,28 @@ def _success_rate(stats: Any) -> float:
return parsed / 100.0 if parsed > 1.0 else parsed
+def quoted_call_cost(value: Any) -> float | None:
+ """Return the credits one call can cost under ``value``, or None.
+
+ Args:
+ value: A capability's ``expected_cost`` quote.
+
+ Returns:
+ The flat per-call price, or None when the quote does not bound the
+ bill: absent, negative, priced per result/row/value, or in any shape
+ ``_FLAT_QUOTE`` does not describe.
+ """
+ if isinstance(value, bool) or value is None:
+ return None
+ if isinstance(value, (int, float)):
+ return float(value) if math.isfinite(value) and value >= 0 else None
+ match = _FLAT_QUOTE.fullmatch(str(value).strip().lower())
+ return float(match.group(1)) if match else None
+
+
def _expected_cost(value: Any) -> float:
- if value is None:
- return float("inf")
- text = str(value)
- number = ""
- for char in text:
- if char.isdigit() or char == ".":
- number += char
- elif number:
- break
- try:
- return float(number)
- except ValueError:
- return float("inf")
+ cost = quoted_call_cost(value)
+ return float("inf") if cost is None else cost
def _build_parameters(
@@ -529,7 +573,7 @@ def _build_parameters(
continue
lower = name.lower()
if _is_symbol_param(lower):
- parameters[name] = _provider_symbol(code)
+ parameters[name] = code.strip().upper()
elif _is_start_param(lower):
parameters[name] = start_date
elif _is_end_param(lower):
@@ -547,14 +591,6 @@ def _sample_parameters(capability: dict[str, Any]) -> dict[str, Any]:
return dict(sample) if isinstance(sample, dict) else {}
-def _provider_symbol(code: str) -> str:
- """Normalize common project US suffixes while preserving other markets."""
- upper = code.strip().upper()
- if upper.endswith(".US"):
- return upper[: -len(".US")]
- return upper
-
-
def _is_symbol_param(name: str) -> bool:
return any(token in name for token in ("symbol", "ticker", "instrument", "code"))
diff --git a/agent/backtest/loaders/registry.py b/agent/backtest/loaders/registry.py
index a28943221..8c55e61b4 100644
--- a/agent/backtest/loaders/registry.py
+++ b/agent/backtest/loaders/registry.py
@@ -335,6 +335,19 @@ _COMPARABLE_CALIBERS = frozenset(
_ADDITIVE_CALIBERS = frozenset({"split_dividend_additive"})
+def market_has_corporate_actions(market: str) -> bool:
+ """Whether prices in ``market`` depend on a split/dividend adjustment.
+
+ Args:
+ market: A market name as ``_detect_market`` returns it.
+
+ Returns:
+ False for the markets stamped "na" and for price indices, True for
+ every other market, so an unrecognized one is assumed to need it.
+ """
+ return market not in _NA_CALIBER_MARKETS and market not in _INDEX_CALIBER_MARKETS
+
+
def price_caliber(source: str, market: str | None = None, symbol: str | None = None) -> str:
"""Return the adjustment caliber of ``source``'s served prices.
diff --git a/agent/src/skills/qveris/SKILL.md b/agent/src/skills/qveris/SKILL.md
index 917cbbc08..87aee1f42 100644
--- a/agent/src/skills/qveris/SKILL.md
+++ b/agent/src/skills/qveris/SKILL.md
@@ -75,7 +75,15 @@ choosing among paid options.
- `mode="free"` means the original free public-data path stays active and
QVeris is hidden from agent/tool/backtest routing.
- `mode="paid"` permits QVeris discovery, inspect, and execute calls, bounded by
- `budget_credits_per_session`.
+ `budget_credits_per_session`. Only a flat per-call quote (`24.2 credits`,
+ `1 credits/call`) can be reserved against that budget. A quote priced per
+ result, row or value is refused as `quote_not_bounded`, because its leading
+ number is not the bill: `1 credits/result` charged 9.66 credits for one
+ stock-year.
+- `source: "qveris"` in a backtest or `get_market_data` serves crypto, forex,
+ futures and macro bars only. Stocks, ETFs and other markets with splits and
+ dividends are refused: the loader picks a capability by search rank, which
+ ignores price adjustment, so it could not say how the bars were adjusted.
- Never hide cost: every successful execute result should preserve `cost` and
`remaining_credits` for the user.
diff --git a/agent/src/tools/qveris_tool.py b/agent/src/tools/qveris_tool.py
index 08b83e9cb..cf15559a2 100644
--- a/agent/src/tools/qveris_tool.py
+++ b/agent/src/tools/qveris_tool.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import json
import math
import os
-import re
import tempfile
import threading
import time
@@ -16,6 +15,7 @@ from typing import Any
import httpx
+from backtest.loaders.qveris_loader import quoted_call_cost
from src.agent.tools import BaseTool
SIGNUP_URL = "https://qveris.ai/?ref=Vyjjo5G_1cAHJA"
@@ -176,15 +176,13 @@ def _unconfigured_message(config: QVerisConfig | None = None) -> str:
def _parse_expected_cost(value: Any) -> float | None:
- """Extract a numeric expected-cost hint from QVeris metadata."""
- if value is None:
- return None
- if isinstance(value, (int, float)):
- return float(value)
- match = re.search(r"-?\d+(?:\.\d+)?", str(value))
- if not match:
- return None
- return float(match.group(0))
+ """Return the flat per-call price a QVeris quote states, or None.
+
+ The leading number of a quote is not a price when the quote is per result:
+ "1 credits/result" billed 9.66 credits for one stock-year (#1494). Shared
+ with the bar loader so the two budget gates read a quote the same way.
+ """
+ return quoted_call_cost(value)
def _quote_from_tool(tool: dict[str, Any] | None) -> dict[str, Any]:
@@ -539,8 +537,12 @@ class QVerisExecuteTool(_QVerisBaseTool):
server_quote = _quote_from_tool(first)
server_cost = _parse_expected_cost(server_quote.get("expected_cost"))
+ # A marketplace quote that is not a flat per-call price bounds nothing,
+ # and a caller hint must not stand in for it: a written number would
+ # then buy a call whose bill the budget cannot cap.
+ server_unbounded = server_quote.get("expected_cost") is not None and server_cost is None
candidates = [cost for cost in (supplied, server_cost) if cost is not None]
- effective = max(candidates) if candidates else None
+ effective = None if server_unbounded else (max(candidates) if candidates else None)
quote = dict(server_quote)
quote["tool_id"] = tool_id
@@ -550,7 +552,9 @@ class QVerisExecuteTool(_QVerisBaseTool):
)
quote["server_attested"] = server_cost is not None
quote["caller_supplied_cost"] = supplied
- if server_cost is not None and supplied is not None and supplied < server_cost:
+ if server_unbounded:
+ quote["quote_source"] = "server_quote_not_per_call"
+ elif server_cost is not None and supplied is not None and supplied < server_cost:
quote["quote_source"] = "server_overrode_lower_caller_quote"
elif server_cost is not None:
quote["quote_source"] = "server"
@@ -608,6 +612,20 @@ class QVerisExecuteTool(_QVerisBaseTool):
and math.isfinite(expected)
and (expected > 0.0 or (expected == 0.0 and quote.get("server_attested")))
)
+ if expected is None and (
+ quote.get("quote_source") == "server_quote_not_per_call"
+ or kwargs.get("expected_cost") is not None
+ ):
+ return _json_response(
+ {
+ "ok": False,
+ "status": "quote_not_bounded",
+ "error": "the quote is not a flat price per call, so the "
+ "session credit budget cannot bound this call's bill (#1494)",
+ "budget_credits_per_session": budget,
+ "quote": quote,
+ }
+ )
if (
not valid_quote
or spent >= budget
diff --git a/agent/tests/test_qveris_loader.py b/agent/tests/test_qveris_loader.py
index cca61bbdd..401eef5b4 100644
--- a/agent/tests/test_qveris_loader.py
+++ b/agent/tests/test_qveris_loader.py
@@ -148,14 +148,14 @@ class TestFetch:
def test_returns_empty_without_availability_and_makes_no_http(self, monkeypatch):
session = _install_session(monkeypatch, [])
- assert qv.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31") == {}
+ assert qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31") == {}
assert session.calls == []
def test_free_mode_keeps_qveris_loader_unavailable(self, monkeypatch):
_write_config(qv._CONFIG_PATH, enabled=True, api_key="sk_test", mode="free")
session = _install_session(monkeypatch, [])
- assert qv.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31") == {}
+ assert qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31") == {}
assert session.calls == []
def test_zero_budget_allows_search_but_blocks_paid_execute(self, monkeypatch):
@@ -166,7 +166,7 @@ class TestFetch:
)
result = qv.DataLoader().fetch(
- ["AAPL.US"], "2024-01-01", "2024-01-31"
+ ["BTC-USDT"], "2024-01-01", "2024-01-31"
)
assert result == {}
@@ -197,10 +197,10 @@ class TestFetch:
)
result = qv.DataLoader().fetch(
- ["AAPL.US", "MSFT.US"], "2024-01-01", "2024-01-31"
+ ["BTC-USDT", "ETH-USDT"], "2024-01-01", "2024-01-31"
)
- assert list(result) == ["AAPL.US"]
+ assert list(result) == ["BTC-USDT"]
execute_calls = [call for call in session.calls if "/tools/execute" in call["url"]]
assert len(execute_calls) == 1
@@ -239,10 +239,10 @@ class TestFetch:
],
)
- out = qv.DataLoader().fetch(["AAPL.US"], "2024-01-01", "2024-01-31")
+ out = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")
- assert list(out) == ["AAPL.US"]
- df = out["AAPL.US"]
+ assert list(out) == ["BTC-USDT"]
+ df = out["BTC-USDT"]
assert list(df.columns) == ["open", "high", "low", "close", "volume"]
assert df.index.name == "trade_date"
assert isinstance(df.index, pd.DatetimeIndex)
@@ -255,7 +255,7 @@ class TestFetch:
assert session.calls[1]["url"].endswith("/tools/execute?tool_id=cheap")
execute_body = session.calls[1]["kwargs"]["json"]
assert execute_body["search_id"] == "s_123"
- assert execute_body["parameters"]["symbol"] == "AAPL"
+ assert execute_body["parameters"]["symbol"] == "BTC-USDT"
assert execute_body["parameters"]["start_date"] == "2024-01-01"
assert execute_body["parameters"]["end_date"] == "2024-01-31"
assert execute_body["parameters"]["adjusted"] is True
@@ -290,10 +290,10 @@ class TestFetch:
],
)
- out = qv.DataLoader().fetch(["MSFT"], "2024-01-01", "2024-01-31")
+ out = qv.DataLoader().fetch(["ETH-USDT"], "2024-01-01", "2024-01-31")
- assert list(out) == ["MSFT"]
- assert pd.isna(out["MSFT"].loc["2024-01-02", "volume"])
+ assert list(out) == ["ETH-USDT"]
+ assert pd.isna(out["ETH-USDT"].loc["2024-01-02", "volume"])
assert session.calls[2]["method"] == "get"
assert session.calls[2]["url"] == "https://oss.qveris.cn/full.json"
assert "Authorization" not in session.calls[2]["kwargs"]["headers"]
@@ -320,7 +320,7 @@ class TestFetch:
],
)
- assert qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31") == {}
+ assert qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31") == {}
assert len(session.calls) == 1
def test_date_filtering_and_ohlc_validation(self, monkeypatch):
@@ -345,7 +345,7 @@ class TestFetch:
],
)
- df = qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")["AAPL"]
+ df = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")["BTC-USDT"]
assert [d.strftime("%Y-%m-%d") for d in df.index] == ["2024-01-02"]
assert df.loc["2024-01-02", "open"] == 2.0
@@ -354,7 +354,7 @@ class TestFetch:
def test_invalid_date_range_raises(self):
_write_config(qv._CONFIG_PATH)
with pytest.raises(ValueError):
- qv.DataLoader().fetch(["AAPL"], "2024-02-01", "2024-01-01")
+ qv.DataLoader().fetch(["BTC-USDT"], "2024-02-01", "2024-01-01")
class TestParameterMapping:
@@ -449,9 +449,9 @@ class TestCapabilitySelection:
],
)
- data = qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")
+ data = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")
- assert "AAPL" in data
+ assert "BTC-USDT" in data
execute_url = session.calls[1]["url"]
assert "tiingo.core.eod.v1" in execute_url
@@ -485,9 +485,9 @@ class TestCapabilitySelection:
],
)
- data = qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")
+ data = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")
- assert "AAPL" in data
+ assert "BTC-USDT" in data
assert "daily_bad" in session.calls[1]["url"]
assert "daily_good" in session.calls[2]["url"]
@@ -518,10 +518,10 @@ class TestCapabilitySelection:
],
)
- data = qv.DataLoader().fetch(["AAPL"], "2024-01-01", "2024-01-31")
+ data = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")
- assert "AAPL" in data
- assert float(data["AAPL"]["close"].iloc[0]) == 1.5
+ assert "BTC-USDT" in data
+ assert float(data["BTC-USDT"]["close"].iloc[0]) == 1.5
assert len(session.calls) == 2
@@ -729,3 +729,101 @@ def test_a_response_whose_rows_carry_both_families_uses_the_unadjusted_one():
frame = qv._result_to_frame(result, "2024-01-01", "2024-01-05")
assert list(frame["close"]) == pytest.approx([10.5, 10.7])
+
+
+class TestMarketsWithCorporateActions:
+ """Search rank ignores adjustment, so those markets are refused (#1494)."""
+
+ @pytest.mark.parametrize(
+ "code", ["600519.SH", "600519", "AAPL.US", "AAPL", "00700.HK", "RELIANCE.NS", "510300.SH"]
+ )
+ def test_refused_before_any_request(self, monkeypatch, code):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(monkeypatch, [])
+
+ with pytest.raises(NoAvailableSourceError, match="#1494") as excinfo:
+ qv.DataLoader().fetch([code], "2024-01-01", "2024-01-31")
+
+ assert code in str(excinfo.value)
+ assert session.calls == []
+
+ def test_one_refused_symbol_refuses_the_request(self, monkeypatch):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(monkeypatch, [])
+
+ with pytest.raises(NoAvailableSourceError) as excinfo:
+ qv.DataLoader().fetch(["BTC-USDT", "600519.SH"], "2024-01-01", "2024-01-31")
+
+ assert "600519.SH (a_share)" in str(excinfo.value)
+ assert "BTC-USDT" not in str(excinfo.value)
+ assert session.calls == []
+
+ @pytest.mark.parametrize("code", ["BTC-USDT", "EURUSD", "RB2410.SHFE", "^GSPC"])
+ def test_markets_with_nothing_to_adjust_still_search(self, monkeypatch, code):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(monkeypatch, [_FakeResponse({"search_id": "s", "results": []})])
+
+ assert qv.DataLoader().fetch([code], "2024-01-01", "2024-01-31") == {}
+ assert [call["url"] for call in session.calls] == ["https://qveris.test/api/v1/search"]
+
+
+class TestQuotedCallCost:
+ """Only a flat per-call quote bounds a bill (#1494)."""
+
+ @pytest.mark.parametrize(
+ ("quote", "cost"),
+ [
+ ("24.2 credits", 24.2),
+ ("1 credits/call", 1.0),
+ ("5 credits per call", 5.0),
+ ("0.5 credit", 0.5),
+ ("1", 1.0),
+ ("0 credits", 0.0),
+ (3, 3.0),
+ ],
+ )
+ def test_a_flat_quote_is_its_price(self, quote, cost):
+ assert qv.quoted_call_cost(quote) == cost
+
+ @pytest.mark.parametrize(
+ "quote",
+ ["1 credits/result", "0.00132 credits/value", "1 credit per row", "1-24.2 credits/call", "-1", "free", None, True, float("nan")],
+ )
+ def test_any_other_quote_prices_as_unknown(self, quote):
+ assert qv.quoted_call_cost(quote) is None
+
+ def test_a_per_result_quote_is_skipped_and_a_flat_one_runs(self, monkeypatch, caplog):
+ _write_config(qv._CONFIG_PATH)
+ rows = {"data": [{"date": "2024-01-02", "open": 1, "high": 2, "low": 1, "close": 2, "volume": 5}]}
+ session = _install_session(
+ monkeypatch,
+ [
+ _FakeResponse(
+ {
+ "search_id": "s",
+ "results": [
+ _capability("per_result", expected_cost="0.1 credits/result"),
+ _capability("flat", expected_cost="5 credits/call"),
+ ],
+ }
+ ),
+ _FakeResponse({"success": True, "cost": 5.0, "result": rows}),
+ ],
+ )
+
+ out = qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31")
+
+ assert list(out) == ["BTC-USDT"]
+ executed = [call["url"] for call in session.calls if "/tools/execute" in call["url"]]
+ assert executed == ["https://qveris.test/api/v1/tools/execute?tool_id=flat"]
+
+ def test_a_lone_per_result_quote_bills_nothing(self, monkeypatch, caplog):
+ _write_config(qv._CONFIG_PATH)
+ session = _install_session(
+ monkeypatch,
+ [_FakeResponse({"search_id": "s", "results": [_capability("per_result", expected_cost="1 credits/result")]})],
+ )
+
+ assert qv.DataLoader().fetch(["BTC-USDT"], "2024-01-01", "2024-01-31") == {}
+ assert len(session.calls) == 1
+ assert "not a flat price per call" in caplog.text
diff --git a/agent/tests/test_qveris_tool.py b/agent/tests/test_qveris_tool.py
index ad6b5424e..2cf45e1d1 100644
--- a/agent/tests/test_qveris_tool.py
+++ b/agent/tests/test_qveris_tool.py
@@ -413,3 +413,76 @@ def test_an_honest_caller_quote_is_still_honoured(monkeypatch):
assert payload["ok"] is True
assert qt._SESSION_SPEND["honest"] == pytest.approx(1.0)
+
+
+def _paid(budget: float) -> None:
+ qt.save_qveris_config(
+ qt.QVerisConfig(enabled=True, api_key="sk-live", mode="paid", budget_credits_per_session=budget)
+ )
+
+
+class _QuotedClient:
+ def __init__(self, quote):
+ self.quote = quote
+ self.executed = 0
+
+ def inspect(self, *args, **kwargs):
+ del args, kwargs
+ return {"results": [{"tool_id": "tool_1", "expected_cost": self.quote}]}
+
+ def execute(self, *args, **kwargs):
+ del args, kwargs
+ self.executed += 1
+ return {"success": True, "cost": 1.0, "result": {}}
+
+
+def test_a_per_result_server_quote_is_refused_whatever_the_caller_writes(monkeypatch):
+ """ "1 credits/result" billed 9.66 credits for one stock-year (#1494): its
+ leading number is not a price, and a caller-written flat quote must not
+ stand in for it."""
+ _paid(50.0)
+ client = _QuotedClient("1 credits/result")
+ monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: client)
+
+ for hint in (None, "2 credits"):
+ kwargs = {"tool_id": "tool_1", "parameters": {}, "session_id": "per_result"}
+ if hint is not None:
+ kwargs["expected_cost"] = hint
+ payload = json.loads(qt.QVerisExecuteTool().execute(**kwargs))
+ assert payload["status"] == "quote_not_bounded"
+ assert payload["quote"]["quote_source"] == "server_quote_not_per_call"
+
+ assert client.executed == 0
+ assert qt._SESSION_SPEND.get("per_result", 0.0) == 0.0
+
+
+def test_a_per_result_caller_quote_without_a_server_quote_is_refused(monkeypatch):
+ _paid(50.0)
+
+ class _Offline(_QuotedClient):
+ def inspect(self, *args, **kwargs):
+ raise RuntimeError("marketplace unreachable")
+
+ client = _Offline(None)
+ monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: client)
+
+ payload = json.loads(
+ qt.QVerisExecuteTool().execute(
+ tool_id="tool_1", parameters={}, session_id="s", expected_cost="1 credits/result"
+ )
+ )
+
+ assert payload["status"] == "quote_not_bounded"
+ assert client.executed == 0
+
+
+def test_a_flat_per_call_server_quote_still_runs(monkeypatch):
+ _paid(50.0)
+ client = _QuotedClient("24.2 credits/call")
+ monkeypatch.setattr(qt.QVerisExecuteTool, "_client", lambda self: client)
+
+ payload = json.loads(qt.QVerisExecuteTool().execute(tool_id="tool_1", parameters={}, session_id="flat"))
+
+ assert payload["ok"] is True
+ assert client.executed == 1
+ assert qt._SESSION_SPEND["flat"] == pytest.approx(1.0)