SokoFlow AI Build Log, Week 6 of 6: two bugs from my own code review, a before-and-after demo, and what's still unproven
Six weeks ago, a shopkeeper asking SokoFlow "How much did I sell this week?" got this back: "Type 'add product', 'record sale', or 'check stock' to begin."
Today it answers the question.
But the most useful thing I did this week wasn't the demo. It was reading my own Week 5 code and finding two bugs that stay invisible until the provider has a bad day.
TL;DR
- Moving one cleanup line out of a
finallyblock when I added retries meant HTTP clients would stay open on every failure path: timeouts, connection errors, exhausted retries and cancelled tasks.- My
Retry-Afterhandling trusted a header value completely. A huge, negative, non-numeric, infinite or date-formatted value could hang a request or fire a retry instantly.- Both bugs share a lesson: adding retry logic doesn't just add requests, it adds new ways out of the function, and cleanup has to survive all of them.
- The full flow works end to end in the simulator. The honest scorecard, including what's still unproven, is near the end.
Where we are
SokoFlow is a headless WhatsApp ERP for Kenyan SMEs. I've been building it for about five months. There's no app and no UI to learn; for a shopkeeper, the conversation is the interface. Phase 3 added one AI feature: natural-language shop analytics. A shopkeeper asks "which products are running low?" or "how does this week compare to last week?", and an LLM, using function calling against SokoFlow's existing services, figures out which query to run. This is the last build log of this six-week phase.
Last week I built a 30-turn evaluation harness and ran it against plausible shopkeeper questions. The KPI was hit, but it wasn't the cleanest run, because I tuned the system against that same dev set. A separate held-out headline set, which will show the true picture, is in progress, but it won't make it into this MVP.
Bug 1: the cleanup that moved
During my Week 6 code review, I found that the retry logic I'd added in Week 5 had quietly created an HTTP client resource leak.
Here's how it happened. Before Week 5, _post_payload() made a single HTTP request and used a try/finally block to close the temporary httpx.AsyncClient it created. That worked because the method either returned or raised, and the finally ran either way.
Week 5 added bounded retries for HTTP 429 responses (and only 429s): wait for the provider's Retry-After header, or back off exponentially with jitter if it's missing. But in that change I moved the client cleanup out of the finally block and placed it after the retry loop.
That's the subtle part. Cleanup now depended on the method reaching the end of the loop. Anything that exits the loop early skips it:
- a timeout,
- a connection error,
- exhausted retries,
- a cancelled task.
Why does a skipped cleanup matter? An AsyncClient owns a connection pool, and each open connection is a socket, which is a file descriptor on the operating system. Closing the client releases them. If failures repeatedly leave clients unclosed, open connections and file descriptors can pile up until the process hits errors like OSError: [Errno 24] Too many open files.
That would hit the default production path, where LLMClient creates its own HTTP client when none is injected. And since one process serves messages for every shop, a leak isn't one shop's problem.
The fix: restore the try/finally boundary around the whole request and response lifecycle, retry loop included.
try: # Request execution, retry handling, # and response processing. ... finally: if client_created: await client.aclose() Now locally created clients are closed whether the call succeeds, exhausts its retries, raises a transport exception or is cancelled. I also added tests for timeout, connection failure and HTTP 429 retry exhaustion, to check that the temporary client is closed on each failure path.
The lesson: adding retry logic changes more than how many requests a method can make. It changes its execution paths and its resource lifecycle. The failure paths are where cleanup quietly breaks.
Bug 2: a sleep with no ceiling
The second bug came from how I parsed the Retry-After header, which tells a client how long to wait before sending a follow-up request. My code looked like this:
retry_after = response.headers.get("Retry-After") try: wait_seconds = float(retry_after) except (TypeError, ValueError): # Exponential backoff with jitter wait_seconds = backoff + jitter await asyncio.sleep(wait_seconds) attempt += 1 continue # retry the request It looks reasonable. But it treats a value from the network as if it were safe. The problems I found:
- No upper bound. A response with
Retry-After: 86400(24 hours) orRetry-After: 999999999makes the coroutine sleep for that long. That could hang a production request handler and hold a worker slot. It's a failure mode that could come from an outage or a misconfigured server. I never saw it from Groq, and I didn't want to wait for it to happen. - Negative values.
float("-5")is valid.asyncio.sleepwith a negative number returns immediately, so the retry fires instantly, potentially before the provider is ready. - HTTP-date format. The spec for
Retry-Afterallows either a number of seconds or an HTTP date (for exampleWed, 25 Nov 2026 12:00:00 GMT; see RFC 9110, section 10.2.3).float()raisesValueErroron a date, so it fell through to exponential backoff. That's acceptable behaviour, but it was accidental. It should handle each format on purpose. - NaN and infinity.
float("inf")andfloat("nan")are valid Python floats.asyncio.sleep(float("inf"))sleeps forever, and the behaviour fornanis undefined. - No overall deadline. The loop had no wall-clock deadline at all. With
max_retries=3and largeRetry-Aftervalues, a single LLM call could take hours.
Three fixes, each aimed at a different problem:
- A dedicated parser. A new method,
_retry_after_seconds(...), handles both delta-seconds and HTTP-date formats and rejects anything invalid. The key check:
if not math.isfinite(seconds) or seconds < 0: return None math.isfinite rejects both nan and inf, and the seconds < 0 test rejects negatives. A None return means "I can't trust this header", and the retry logic falls back to exponential backoff. That's better than clamping a negative to zero, which would mean an immediate retry, the exact problem in item 2.
- Cap the wait. Whatever survives parsing can never be negative and never exceeds a safe maximum:
wait_seconds = min(max(wait_seconds, 0.0), MAX_RETRY_AFTER_SECONDS) - An overall deadline. There's now a configurable 60-second deadline on the whole provider call, covering the HTTP attempts and the retry waits. If it expires, the client raises
LLMProviderTimeoutError. The per-attempt HTTP timeout and the cappedRetry-Afterstay in place underneath it.
Note how the layers fit. The parser decides whether a header can be trusted, the cap limits any single wait, and the deadline limits the whole call, so no combination of retries can take longer than the deadline.
Looking back, this follows the theme of the whole series. In Week 1 I wrote "never trust the client, even when the client is an LLM". The provider's response headers deserve the same rule: anything that arrives over the network is untrusted input, including the headers that are supposed to help you behave politely.
Trying out the full flow
I also fixed a few smaller things, mostly code-design practice and adding logging to more components for visibility. Then came the part I'd been waiting six weeks for: running the whole flow in the simulator.
Six weeks ago, an analytics question like "How much did I sell this week?" got the generic fallback, because the regex intent resolver classified it as Intent.UNKNOWN:
Six weeks later, I sent the same message:
The system now answers with a sales summary for the current calendar week. Only one test transaction was recorded for the demo, so the numbers are small, but it shows the week's total revenue in local currency and the number of transactions.
The second message tests another supported flow: "What was my best selling product this week?" The system correctly replies with the top product and its units sold.
The third message is the trickier one: "What about last week?" That question means nothing without context. The system has to remember what it was just handling. Thanks to the Week 3 design, it had stored last_analytics_call in the session context, so it knew this was still a get_top_products query and only the period had changed.
None of this was possible six weeks ago.
Where things stand
The original objective was:
Let a shopkeeper ask natural-language questions over WhatsApp — "How much did I sell today?" or "What's my stock on sugar?" — and receive accurate answers by having an LLM call functions against SokoFlow's existing service layer. No new data store, no separate frontend, and no fine-tuning.
That objective is achieved. Here's how it lines up against the "definition of done" I wrote at the start, and what it does and doesn't prove:
| Definition of done | Where it landed |
|---|---|
| All 7 tools live | Wired through the WhatsApp flow in Week 3 |
| Eval pass rate ≥85% | 90% mean across three runs (range 86.67%–93.33%) on the 30-turn set |
| Guardrails: rate limit, cost cap, argument validation, fallback | Per-shop daily cap, a per-call token ceiling, schema and domain validation, fallbacks, and an InteractionLogger. 25 of 25 failure-mode phrasings were handled safely |
| No LLM-triggered mutation path | All seven tools are read-only |
| Demo recorded, blog published | Done |
And some numbers behind those rows:
- Cost: about $0.00005 per query on average, against a self-set ceiling of $0.004.
- Latency: in Week 3, the full path from conversation entry to formatted reply measured p50 1.20 s and p95 2.27 s on 7 requests. The Week 5 evaluation numbers aren't comparable. The harness measures the wall-clock time around
LLMClient.generate, so it includes local token-bucket waits and any HTTP 429 backoff sleeps, and it runs a direct orchestrator path with a mock database. Early eval runs looked slow (around 19.5 s) mostly because of those waits.
What the scorecard doesn't prove:
- The eval number isn't held-out. I tuned prompts, tool descriptions and the answer key against the same set. The held-out headline set is the next step.
- Cost "enforcement" is a bound, not a meter. It's a daily query cap plus a token ceiling per call, not real-time dollar tracking.
- Seven requests is a baseline, not a latency benchmark.
A correction to Week 5
Last week I described two of the three stubborn eval failures as mismatches involving "unexpected arguments", and I noted that the repair loop never fired. After publishing, I traced both failures properly, and that description was misleading.
Both calls passed validation. In turn 3, the model supplied ranking_dimension: "units" to get_top_products. In turn 5, it supplied a comparison_period for last month to get_sales_trend. Both are supported optional arguments, and the executor accepted both. The orchestrator only retries when the executor returns a SchemaValidationError, so there was nothing to repair. The "Unexpected extra arguments" label came from my evaluation scorer, which compared the actual arguments against an answer key that happened to omit them.
So these were answer-key strictness problems, not model failures or execution failures. It's the second time this harness has had a bug in the exam itself, after the product UUID in Week 5. It also means the repair path still hasn't been tested by a real case.
I'm now rebuilding the harness with separate handling for required and optional arguments, better latency measurement and a held-out headline set. I'll write that up as its own post.
What I'd do differently
- Review failure paths the moment I add a retry loop. I introduced both bugs in Week 5 and found them a week later, by reading. Next time, the same commit that adds retries should list every way out of the function and test each one.
- Treat every network value as untrusted input from the start, including headers from a provider I trust.
- Build the held-out evaluation set before tuning, not after. I knew the contamination risk in Week 5 and still tuned on the same set.
What's next
SokoFlow is up and running, and you can watch the full demo here.
The code is open source under the MIT licence and available on GitHub. You can explore it, run it locally with the simulator, open pull requests or share suggestions.
This isn't the end of SokoFlow. The next phase turns the engineering decisions documented over these weeks into product improvements, starting with the held-out evaluation set. The ADRs in the docs/ directory are the roadmap for most of it.
The longer-term goal hasn't changed: a trusted tool that lets Kenyan shopkeepers manage inventory, record sales, check stock levels and receive daily reports just by sending messages to a WhatsApp number.
No app to download. No training session. No complicated interface to navigate.
The interface is the conversation.
Finally, thank you to everyone who has followed this journey, from the original 16-week ERP build to these six weeks of AI engineering. Your reads, comments and feedback have made sharing the process worthwhile.
There's more to build. Stay tuned!



