===== ISTEM =====
Our nightly export job crashed. Here is the log:

```
2026-09-18 02:00:01 INFO  export: starting nightly export (batch=500)
2026-09-18 02:00:03 INFO  export: fetched 1500 rows from orders
2026-09-18 02:00:03 INFO  export: writing batch 1/3
2026-09-18 02:00:04 INFO  export: writing batch 2/3
2026-09-18 02:00:04 ERROR export: unhandled exception
Traceback (most recent call last):
  File "/srv/jobs/export.py", line 88, in run
    write_batch(rows[i:i + BATCH], out)
  File "/srv/jobs/export.py", line 41, in write_batch
    out.write(f"{r['id']},{r['total']:.2f},{r['currency']}\n")
KeyError: 'currency'
```

What is the root cause, and at which line of our code does it fail?

===== HAM YANIT =====
The root cause of the issue is that one or more rows in the `orders` data do not have a key named 'currency'. When the code attempts to access `r['currency']` in the `write_batch` function, it raises a `KeyError` because the key 'currency' is not present in the dictionary `r`.

This error occurs at line 41 in the `export.py` file, specifically in the `write_batch` function when the following line is executed:

```python
out.write(f"{r['id']},{r['total']:.2f},{r['currency']}\n")
```

To fix this issue, you can add error handling to check if the key 'currency' exists in the dictionary before attempting to access it. For example:

```python
if 'currency' in r:
    out.write(f"{r['id']},{r['total']:.2f},{r['currency']}\n")
else:
    out.write(f"{r['id']},{r['total']:.2f},UNKNOWN\n")
```

This way, if the 'currency' key is missing, the code will default to writing 'UNKNOWN' as the currency value, instead of crashing with a `KeyError`.