Kimi Agent Action Verification: Test State Versions Before a Write
A Kimi-family proposal is checked against tenant and current row version before a synthetic SQLite transition. Six local cases cover stale state, replay and invalid fields.

An agent proposal should not authorize its own side effect. Validate the proposal, bind it to trusted identity, and make the final state check part of the same database write that applies the change.
Crazyrouter is the gateway used for one kimi-k2.5 action proposal; a guarded local SQLite update changed a synthetic task from open version 1 to closed version 2.
By Jeff M · Tested November 3, 2026
How do I verify a Kimi agent action before executing it?#
Accept only the intended schema, derive the tenant outside the model response, and update only when the current row version and state match the proposal. The SQL WHERE clause is the final condition at write time. A row count of zero means the change was not applied; it is not permission to overwrite newer state.
Separate the old article model from the tested route#
This page originally discussed Kimi K2 Thinking. The November 3 credential-scoped catalog did not expose kimi-k2-thinking; it did expose kimi-k2.5. The live example explicitly uses kimi-k2.5. It does not prove current availability or equivalent behavior for the older identifier.
The official Kimi repository provides family context. The local action boundary is deliberately model-independent. No external incident was reproduced, and this revision does not call the synthetic test a production postmortem.
November 3 test results#
The tests ran on Windows with Python 3.10.2 and synthetic inputs. The API host was https://api.crazyrouter.com; the complete request path, model and parameters appear in the runnable code below. These are dated observations, not a guarantee of future behavior.
| Case | HTTP | Finish | Exact fixture | Observed output |
|---|---|---|---|---|
| 1 | 200 | stop | Pass | {"id":"LIVE-1421","version":1,"status":"closed"} |
Local fixtures: 6 passed. The live-response criteria are evaluated separately.
Observed response or request IDs (including failed-output responses):
830690fd-63aa-4b43-8f50-58c09679155f

Make the write conditional on trusted state#
The proposal contains only id, integer version and status closed. The tenant comes from application context. The UPDATE requires the matching tenant, expected version and current open state, then increments the version in the same statement. Boolean versions are rejected even though Python treats bool as an int subclass in many contexts.
Six local cases cover another tenant, stale version, extra fields, a boolean version, a valid transition and duplicate replay. Only the valid transition applies. Replaying the old proposal cannot match the new version and closed state. This is optimistic concurrency control for a local row, not a general idempotency service for payments or external tools.
Require complete generation before considering a proposal#
The live prompt asks for a small JSON proposal for LIVE-1421. The script only parses it after finish_reason stop, then applies the same validator and SQL condition as the local cases. It records both the decision and the final database state; a model saying “done” would not count as evidence of a write.
All side effects occur in an in-memory SQLite database created for this run. For a real workflow, derive authorization from trusted application state and define risk-specific approval requirements before invoking an external operation. The example does not require human approval for every action, and it does not bypass whatever approval a real operation needs.
Reproduce the test#
Install requests, set CRAZYROUTER_API_KEY in the process environment, save the complete script below, and run it with Python. It sends the synthetic requests shown in the code using your own authorized credential. It does not print authorization headers. Output includes the observed fixture outcomes; completing the script does not mean every model answer passed.
import json
import os
import time
import requests
BASE = "https://api.crazyrouter.com/v1"
def chat(model, messages, **options):
client=requests.Session();client.trust_env=False
payload={"model":model,"messages":messages,**options}
start=time.perf_counter()
record={"model":model,"request":payload}
try:
r=client.post(BASE+"/chat/completions",headers={"Authorization":"Bearer "+os.environ["CRAZYROUTER_API_KEY"]},json=payload,timeout=(10,45),allow_redirects=False)
record["http"]=r.status_code
if r.status_code!=200:
record["error"]="HTTP_"+str(r.status_code)
else:
data=r.json();choice=data["choices"][0]
record.update(response_id=data.get("id"),output=choice["message"].get("content"),finish_reason=choice.get("finish_reason"),usage=data.get("usage",{}))
except (requests.RequestException,ValueError,KeyError,IndexError) as e:
record["error"]=type(e).__name__
finally:client.close()
record["seconds"]=round(time.perf_counter()-start,3)
return record
def catalog_selection(legacy,selected):
client=requests.Session();client.trust_env=False
try:
r=client.get(BASE+"/models",headers={"Authorization":"Bearer "+os.environ["CRAZYROUTER_API_KEY"]},timeout=(10,30),allow_redirects=False)
r.raise_for_status();names={x["id"] for x in r.json()["data"]}
if selected not in names:raise ValueError("Selected model is not visible to this credential")
return {"legacy_id":legacy,"legacy_visible":legacy in names,"selected_id":selected,"selected_visible":True,"scope":"this credential at test time"}
finally:client.close()
import sqlite3
def apply(db,proposal,tenant):
if type(proposal) is not dict or set(proposal)!={"id","version","status"}:return "invalid"
if type(proposal["version"]) is not int or not isinstance(proposal["id"],str) or proposal["status"]!="closed":return "invalid"
with db:
count=db.execute("UPDATE tasks SET status='closed',version=version+1 WHERE id=? AND tenant=? AND version=? AND status='open'",(proposal["id"],tenant,proposal["version"])).rowcount
return "applied" if count==1 else "not_applied"
def main():
db=sqlite3.connect(":memory:");db.execute("CREATE TABLE tasks(id TEXT PRIMARY KEY,tenant TEXT,version INTEGER,status TEXT)")
db.execute("INSERT INTO tasks VALUES('TASK-1421','A',1,'open')");db.commit()
proposal={"id":"TASK-1421","version":1,"status":"closed"};tests=[]
for name,p,tenant,expected in [("wrong tenant",proposal,"B","not_applied"),("stale version",dict(proposal,version=0),"A","not_applied"),("extra field",dict(proposal,tenant="A"),"A","invalid"),("boolean version",dict(proposal,version=True),"A","invalid"),("valid transition",proposal,"A","applied"),("duplicate replay",proposal,"A","not_applied")]:
actual=apply(db,p,tenant);assert actual==expected;tests.append({"case":name,"passed":True,"decision":actual})
db.execute("INSERT INTO tasks VALUES('LIVE-1421','A',1,'open')");db.commit()
catalog=catalog_selection("kimi-k2-thinking","kimi-k2.5")
r=chat("kimi-k2.5",[{"role":"user","content":'Return only JSON with id LIVE-1421, integer version 1, and status closed. No other fields.'}],max_tokens=1024)
try:action=json.loads(r.get("output") or "null") if r.get("finish_reason")=="stop" else None
except ValueError:action=None
decision=apply(db,action,"A");r["action_decision"]=decision
r["passed"]=decision=="applied" and r.get("finish_reason")=="stop"
state=db.execute("SELECT status,version FROM tasks WHERE id='LIVE-1421'").fetchone();db.close()
print(json.dumps({"endpoint":BASE+"/chat/completions","catalog":catalog,"local_tests":tests,"requests":[r],"final_state":state,"side_effect":"In-memory synthetic task only; no external write"}))
if __name__=="__main__":main()

Sources and related implementation guides#
Official references checked November 3, 2026: Official Kimi repository, Python SQLite documentation. Their documented behavior is distinct from the gateway results measured here.
- Authorize LLM Tool Calls: Tenant Isolation with a Tested Python Executor
- Claude tool_use_id Errors: Fix Missing and Misordered tool_result Blocks
- Function Calling Across AI Models: Two Completed Loops and One Timeout
- AI API Retries in Python: Retry-After, Timeouts, and Safe Replay
- AI Guardrails in Python: Reject Invalid Outputs After Prompt Injection
FAQ#
Was Kimi K2 Thinking itself tested?#
No. Its old identifier was absent from this credential’s catalog. The live proposal used kimi-k2.5 and is labelled accordingly.
Does a reasoning model authorize a write?#
No. The application checks schema, trusted tenant and current state before applying the proposal.
Why include the row version?#
It prevents a proposal based on an old state from overwriting a newer state that no longer matches the condition.
What happens on duplicate replay?#
The tested second application returns not_applied because version and status have already changed.
Was a real customer record changed?#
No. Only synthetic rows in a temporary in-memory database were used.
Does this provide exactly-once external execution?#
No. External side effects need their own transactional, reconciliation or idempotency design.
Last actually tested: November 3, 2026. This API-dependent article is due for review December 3, 2026.
Implementation Guides
Podcast
AI Dev Tools: The Crazyrouter Podcast
Short episodes for developers on AI APIs, gateways, cost control and coding tools.
Latest episodes
EP196 · Oct 29, 2026 · 6:53
AI API Security Posture — Turn Controls Into Continuous Evidence
A practical guide to AI API security posture: inventory exposure, verify controls continuously, protect keys and data, constrain tools, and turn security assumptions into evidence that operators can act on.
EP195 · Oct 28, 2026 · 7:21
AI API Policy Drift — Detect When Production Rules Stop Matching Intent
A practical guide to policy drift in AI APIs: version routing and safety rules, detect stale enforcement, compare intended and observed behavior, and restore control before small gaps become incidents.





