awais.io

pronounced like the first two syllables of oasis.

Is code the correct abstraction?

Early in my career I thought of code as a sequence of instructions given to a computer. Later, I thought of code as a material, as clay, that can be shaped into solid objects like queues, caches, and database transactions to achieve a given set of behaviors and guarantees. If I'm building a system that moves money around, I care that money is never created or destroyed, but I don't need to know exactly which set of CPU instructions is needed to achieve that end.

Under the hood, a program is fundamentally a sequence of instructions, but that abstraction is too low level to be useful. If I asked you how to bake a cake and you told me to first take a teaspoon out of the drawer, then open the fridge and remove an egg, then ..., your explanation would be far too low level to be useful even if your instructions did result in a cake at the end. What I need to know is to mix the batter and bake it at 180°C for 30 minutes.

Take the code below, what is it telling me? (see if you can find all the bugs!)

@endpoint.post("/orders")
def handle_create_order(req, store):
    user = req.require_user()

    key = req.headers.get('Idempotency-Key')
    saved = store.get(key)
    if saved:
        return (saved["code"], saved["body"]) if saved["done"] else (409, "In progress")
    store.set(key, {"done": False}, ttl=86400)
    
    try:
        order = logic.create_order(user, req.body)
    except OrderException:
        store.delete(key)  # Let the client try again
        raise

    result = {"done": True, "code": 201, "body": {"order_id": order.id}}
    store.set(key, result, ttl=86400)
    return result["code"], result["body"]

The questions I have about the code are:

  1. Who is allowed to call this endpoint? What permissions do they need?
  2. What if the order is sent twice by accident? Is the idempotency behavior implemented correctly? When is it safe to retry a failed order?
  3. What happens if we don't have enough inventory to satisfy the order?
  4. Given that we're managing inventory, are there any race conditions?
  5. What if the user doesn't have enough money to place the order?
  6. What are all the possible states the system could end up in?
  7. What are all the return codes I might need to handle?

Now, the code contains the answers to all my questions, but it doesn't scream these answers out to me. To get to these answer, a reader who has built up a skillset over several years needs to be paying close attention as they sleuth through the code.

Specify the contract

But imagine an alternative world, where the code above was written like the contract below, and an LLM was responsible for implementing the low-level code correctly:

ENDPOINT POST /orders — create one order

AUTH
  caller MUST be authenticated
  caller MUST have permission orders:create

INPUT
  body matches OrderSchema
  header Idempotency-Key 1..128 chars of [A-Za-z0-9_-]

OUTCOMES
  201 {order_id}          order created: stock reserved, payment captured
  400                     body or key is invalid
  401 / 403               not authenticated / no permission
  402 PAYMENT_DECLINED    payment failed
  409 IN_PROGRESS         same key, first request is not finished
  409 OUT_OF_STOCK        not enough stock for one or more items
  422 KEY_REUSED          same key, different body

IDEMPOTENCY
  same (caller, key, body)  => at most one order, same final response
  final outcomes (201, 402, OUT_OF_STOCK) are saved for 24h
  server failures (5xx) are not saved; caller can retry safely

GUARANTEES
  atomic order and payment
  user balance never goes below zero
  stock never goes below zero
  one order at a time per (caller, key, body)

In doing this exercise, I am realizing that it is very difficult to write a contract that is sufficiently precise while also being flexible enough to represent all the different states that the code can represent. If I were to try to implement the contract as a programming language I would have to address a lot of difficult questions, for example is "atomic" a language-level keyword? If so, what precisely does it mean?

However, in an LLM-first world, I don't need this contract to be a Turing complete programming language. I can have deterministic keywords (for better language tooling and autocomplete), and also sections of free text that the LLM reads and implements. In the spirit of the human owning the interface, and the LLM owning the implementation, all I need to do is maintain the contract, and trust that the LLM will make sure all of the low-level code details are implemented correctly.

The LLM's task therefore becomes:

  1. Write the code based on the semi-structured contract above
  2. Respond to contract updates (diffs), by generating code patches (code diffs)

It stands to reason that an LLM may be much better at these two tasks than it is at converting a freeform natural language prompt into a complete program. This process will also leave a much better audit trail for verification and maintainability.

I'll continue to explore...

Appendix

For anyone who is curious, a much better implementation of the endpoint above might look like this:

@endpoint.post("/orders")
def handle_create_order(req, store):
    user = req.require_user(permissions=[CAN_CREATE_ORDER])  # 401 / 403
    body = req.require_valid_body(OrderSchema)               # 400
    idem = req.require_idempotency_key()                     # 400 if missing or invalid
    key = f"idem:{user.id}:{idem}"                    # Scope: endpoint + user
    fp = fingerprint(body)

    if saved := store.set_if_absent(key, {"done": False, "fp": fp}, ttl=PENDING_TTL):
        if saved["fp"] != fp:
            return 422, "This key was used with a different body"
        if not saved["done"]:
            return 409, "In progress"
        return saved["code"], saved["body"]

    try:
        order = logic.create_order(user, body, idempotency_key=key)
        code, resp = 201, {"order_id": order.id}
    except OrderValidationError as e:
        code, resp = 422, {"error": str(e)}  # 4xx: save it, so a retry gets the same answer.
    except Exception:
        store.delete(key)                    # 5xx: let the client try again.
        raise

    store.set(key, {"done": True, "fp": fp, "code": code, "body": resp}, ttl=DONE_TTL)
    return code, resp

Comments 0