Metadata-Version: 2.5
Name: django-quickset
Version: 0.1.0
Summary: Serve a Django-Bolt read route from SQL captured once, in Python or from Rust, with the same response as before.
Project-URL: Repository, https://github.com/YasserShkeir/quickset
Project-URL: Documentation, https://github.com/YasserShkeir/quickset/tree/main/docs
Project-URL: Issues, https://github.com/YasserShkeir/quickset/issues
Project-URL: Changelog, https://github.com/YasserShkeir/quickset/blob/main/CHANGELOG.md
Author: Yasser Shkeir
License-Expression: MIT
License-File: LICENSE
Keywords: django,django-bolt,orm,performance,postgresql,queryset,rust
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Database
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: django-bolt>=0.13
Requires-Dist: django>=5.2
Requires-Dist: msgspec>=0.20
Description-Content-Type: text/markdown

<p align="center">
  <img src="https://raw.githubusercontent.com/YasserShkeir/quickset/v0.1.0/docs/assets/logo.svg" width="96" alt="quickset">
</p>

# quickset

Serve a Django-Bolt read route from SQL that is captured once, on Django's
own connection or from a Rust executor, with the same response as before.

> **Status: alpha (0.1).** The `plan` tier works with the Django-Bolt that PyPI
> has. Its event-loop form and the `native` tier need Django-Bolt's master
> branch. The table under "Install" has the details.

```python
from django_bolt import BoltAPI
from quickset import Quickset

api = BoltAPI()
quickset = Quickset(api)


@quickset.get("/articles")
async def list_articles(min_score: int = 0) -> list[ArticleOut]:
    return Article.objects.filter(published=True, score__gte=min_score).order_by("id")
```

This is an ordinary [Django-Bolt](https://github.com/dj-bolt/django-bolt)
handler that returns a QuerySet. The only change is the decorator:
`@quickset.get` in place of `@api.get`.

## Install

```bash
pip install django-quickset
```

The development version installs from this repository:
`pip install "django-quickset @ git+https://github.com/YasserShkeir/quickset"`.

Add `"quickset"` to `INSTALLED_APPS`, for the command
`python manage.py quickset check`. It needs Python 3.12 or later and Django 5.2
or later. PostgreSQL is the only database that is tested.

What you get depends on your Django-Bolt:

| With | You get |
| --- | --- |
| django-bolt 0.13.0, the release on PyPI | The `plan` tier, on threads. On a 10-row route it answered 5,499 requests a second where Django-Bolt answered 2,745. |
| django-bolt's master branch, and `BOLT_ASYNC_ORM_ON_LOOP = True` | The `plan` tier on the event loop |
| django-bolt's master branch, and the executor built from this repository | The `native` tier |

The executor of the `native` tier has no wheel yet, because Django-Bolt has
not released native routes. Build it from this repository. It needs a Rust
toolchain, which building django-bolt's master branch needs as well:

```bash
pip install "quickset-native @ git+https://github.com/YasserShkeir/quickset#subdirectory=native"
```

[examples/blog](https://github.com/YasserShkeir/quickset/blob/v0.1.0/examples/blog) is a small project that starts with one command.

## What changes for a request

<p align="center"><img src="https://raw.githubusercontent.com/YasserShkeir/quickset/v0.1.0/docs/assets/request-path.svg" width="880" alt="Three lanes, one for each way to serve a request. Django-Bolt alone reads the request, builds the QuerySet, compiles it to SQL, runs the query, then checks the rows and writes the JSON. On the plan tier of quickset, building and compiling are replaced by one step: pick the recorded statement and bind the values. On the native tier, everything except the query runs in Rust. Each lane shows its measured CPU time."></p>

With `@api.get`, every request builds the QuerySet and compiles it to SQL
again, and the SQL is almost always the same text. That is most of the work:
in a loop with no HTTP, on SQLite, a 10-row read took 200 µs through the ORM
and 42 µs with the same SQL on Django's cursor
([docs/FINDINGS.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/FINDINGS.md)).

With `@quickset.get`, that work happens a few times when the server starts.
Each request then runs the recorded statement:

- on the **`plan` tier**, in Python, on a connection of Django;
- on the **`native` tier**, in Rust, with no Python for the request.

quickset does this only when it can show that the response stays the same:
the same status, the same content type and the same bytes. When it cannot,
the route is registered as a normal Django-Bolt route, and quickset says why.

## How it works

<p align="center"><img src="https://raw.githubusercontent.com/YasserShkeir/quickset/v0.1.0/docs/assets/how-it-works.svg" width="880" alt="Two phases. When the server starts, once for each route: check the code, run it twice with sample values, compare the SQL that Django wrote, and keep a plan. For each request: pick the case, bind the value, run the recorded SQL, and write the JSON. If a step cannot be proven safe, the route stays an ordinary Django-Bolt route."></p>

Nothing parses SQL, and no Python is translated to Rust. Django writes the
SQL, and quickset compares what it wrote.

**1. Check the code.** quickset reads the source of the function. It may
assign, return, call the Django ORM through a stock manager, and use its
parameters. A clock, the current request, a custom manager, a branch or a loop
is refused. The sample runs cannot detect a value that comes from one of them,
and the recording would freeze it:

```python
Article.objects.filter(day=date.today())          # the day of the capture, for ever
Article.objects.filter(tenant=current_tenant())   # the tenant of the capture, for every request
```

**2. Run it twice.** quickset calls the function with two different sample
values for each parameter, and asks Django to compile each QuerySet. This is
`list_articles` in the test project of this repository:

```text
run 1, min_score=1
    ... WHERE ("project_article"."published" AND "project_article"."score" >= %s) ORDER BY 1 ASC
    %s = Int4(1)

run 2, min_score=32766
    ... WHERE ("project_article"."published" AND "project_article"."score" >= %s) ORDER BY 1 ASC
    %s = Int4(32766)
```

**3. Compare the SQL.** The text is the same, and the placeholder holds the
sample of `min_score` in both runs. So that is where `min_score` is bound, with
the `Int4` wrapper that Django put around it. A placeholder with the same value
in both runs is a constant. Anything else is a value that Django derived from
the parameter (`icontains` wraps the text in `%`), and the route is not
eligible. The two runs also use different time zones, so a statement that
contains the active time zone is found and refused.

**4. Keep the plan.** Django does not always write the same text for one
QuerySet. It depends on the value:

| `min_score` | What Django writes | What the plan keeps |
| --- | --- | --- |
| below −2,147,483,648 | `WHERE published`. The condition is dropped, because every `integer` passes. | a statement with nothing to bind |
| −2,147,483,648 to 2,147,483,647 | `WHERE (published AND score >= %s)` | a statement that binds `min_score` |
| above 2,147,483,647 | no query. No `integer` can pass. | "empty": answered with no query |

One fixed statement would be wrong for two of the three ranges. So a plan
holds one statement for each range, and a request picks its range first. A
`bool` has two: `WHERE published` and `WHERE NOT published`.

**For each request.** `GET /articles?min_score=5` is in the second range. On
the `plan` tier, quickset binds 5 as Django would, runs the statement on
Django's connection, and hands the rows to Django-Bolt, which validates and
encodes them as before. On the `native` tier, the Rust executor does the same
and writes the JSON as msgspec does, byte for byte.

More detail, and the reason for each check: [docs/DESIGN.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/DESIGN.md).

## Which tier serves a route

<p align="center"><img src="https://raw.githubusercontent.com/YasserShkeir/quickset/v0.1.0/docs/assets/tiers.svg" width="880" alt="Four checks, in order. Does the function only build a QuerySet from its parameters? Does Django write the same SQL for every value in a range? A no to either keeps the route on the orm tier. Did you ask for the native tier? Is the route public, on PostgreSQL, with column types the executor writes? A no to either keeps the route on the plan tier. Four yeses give the native tier."></p>

| Tier | What it does | Needs |
| --- | --- | --- |
| `orm` | Django builds the query for each request. This is plain Django-Bolt. | nothing |
| `plan` | Runs the recorded statement on a connection of Django: on a thread, or on Django-Bolt's event loop when the project sets `BOLT_ASYNC_ORM_ON_LOOP`. Validation, JSON, authentication, logs and OpenAPI are unchanged. | django-bolt 0.13.0 or later; the event loop needs master |
| `native` | Runs the recorded statement from Rust and writes the JSON there. No Python runs for the request. | django-bolt master, PostgreSQL, a public route |

The default is `plan`. `native` is opt-in: `Quickset(api, tier="native")`, or
`tier="native"` on one route. `require="plan"` makes a route fail at startup
instead of falling back.

A command lists every route, its tier, and what keeps it off the next one.
With `--fail-under plan` it fails a CI build.

```text
$ python manage.py quickset check
GET /articles                            native  blog.api.list_articles
GET /prices                              plan    blog.api.prices
    not native: the column 'price' is a DecimalField, which the native executor does not read yet
GET /search                              orm     blog.api.search
    not plan: the query uses a value that is computed from a parameter (for example a contains lookup), which a fixed statement cannot reproduce
```

## Measured

<p align="center"><img src="https://raw.githubusercontent.com/YasserShkeir/quickset/v0.1.0/docs/assets/demo.gif" width="880" alt="A terminal recording. One Django-Bolt server on its master branch serves one route three ways. wrk measures plain Django-Bolt with event-loop reads at about 4,300 requests a second, the plan tier of quickset at about 17,000 and the native tier at about 63,000. Then curl and sha256sum show that all three return the same bytes."></p>

The recording is `bench/demo.sh`, as it ran: one server, single runs of three
seconds. The tables below are the medians of five runs of eight seconds each,
so their figures are a little lower.

<!-- benchmark:start -->
Requests per second, and the server's CPU time for one request, on
Django-Bolt's master branch:

| Served by | 10 rows | 100 rows | 1 row by its key |
| --- | ---: | ---: | ---: |
| Django-Bolt | 2,915 (391 µs) | 1,913 (611 µs) | 3,307 (349 µs) |
| Django-Bolt, reads on its event loop | 4,209 (238 µs) | 2,369 (423 µs) | 5,564 (180 µs) |
| quickset, `plan` tier | 5,281 (237 µs) | 2,703 (465 µs) | 6,072 (211 µs) |
| quickset, `plan` tier, reads on the event loop | 14,713 (68 µs) | 3,934 (254 µs) | 23,689 (42 µs) |
| quickset, `native` tier | 55,601 (42 µs) | 23,816 (106 µs) | 67,004 (34 µs) |

<p align="center"><img src="https://raw.githubusercontent.com/YasserShkeir/quickset/v0.1.0/docs/assets/benchmark-list-throughput.svg" width="720" alt="Requests per second on a 10-row route, for each variant"></p>
<!-- benchmark:end -->

<!-- released:start -->
On django-bolt 0.13.0, the release that PyPI has, where the `plan` tier runs on
threads:

| Served by | 10 rows | 100 rows | 1 row by its key |
| --- | ---: | ---: | ---: |
| Django-Bolt 0.13.0 | 2,745 (416 µs) | 1,790 (654 µs) | 3,470 (333 µs) |
| quickset, `plan` tier | 5,499 (226 µs) | 2,888 (430 µs) | 6,154 (206 µs) |
<!-- released:end -->

One server process, PostgreSQL in a second container, Docker on one laptop.
Every variant returned the same bytes. The numbers compare the variants on
that machine. They are not a forecast for another one. The full tables, the
conditions and how to read them are in
[docs/BENCHMARKS.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/BENCHMARKS.md).

Run it yourself: `make build`, then `make bench` for the first table and
`make bench-released` for the second. With fewer than 11 CPUs in Docker, the
benchmark runs without pinning the CPUs, and says so.

## What a route must be

A route reaches the `plan` tier when:

- its parameters are plain `int`, `str` or `bool`, from the path or the query;
- its response is `list[Struct]` or `Struct`, with no nested Struct;
- its function only builds a QuerySet from its parameters: no branch, no clock,
  no request state, no custom manager (see "Purity" in [docs/DESIGN.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/DESIGN.md));
- the SQL does not depend on a value in a way quickset cannot reproduce
  (`icontains`, a slice with a parameter, a `__date` lookup).

It reaches the `native` tier when, in addition, it has no authentication or
guards, its columns are integers, text, bools, `timestamptz`, `date` or `uuid`,
and PostgreSQL has described every statement. The full list is in
[docs/DESIGN.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/DESIGN.md).

Some common cases:

| The route has | It is served by | Why |
| --- | --- | --- |
| `filter(day=date.today())` | `orm` | The day would be frozen at startup. Use `Now()`, which the database evaluates for each query. |
| `filter(tenant=current_tenant())` | `orm` | Request state. Every request would get the tenant of the capture. |
| a custom manager, `Article.published.all()` | `orm` | A manager can hide a clock or request state. |
| `filter(title__icontains=q)` | `orm`, for now | Django derives the bound value from `q`. |
| a slice with a parameter, `[:limit]` | `orm`, for now | Django writes the number into the SQL text. |
| `auth=` or guards | `plan` | Django-Bolt runs no authentication for a native route. |
| a `DecimalField` or `JSONField` column | `plan`, for now | The native executor does not write them yet. |

## Run the tests and the benchmark

Everything runs in Docker. Nothing is installed on the host, and no port is published.

```bash
make build            # once: builds the image and compiles django-bolt from source (10 to 15 minutes)
make test             # every test: released django-bolt, its master branch, and master with reads on the event loop
make bench            # the benchmark, on django-bolt's master branch
make bench-released   # the benchmark, on django-bolt from PyPI
```

See [docs/TESTING.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/TESTING.md).

## Documents

- [docs/DESIGN.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/DESIGN.md): how it works and why
- [docs/PLAN.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/PLAN.md): what is done, what is next, what is decided
- [docs/TESTING.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/TESTING.md): the test environment and what is tested
- [docs/FINDINGS.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/FINDINGS.md): the facts it rests on, with sources
- [docs/BENCHMARKS.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/BENCHMARKS.md): the measurements
- [CHANGELOG.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/CHANGELOG.md), [CONTRIBUTING.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/CONTRIBUTING.md), [SECURITY.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/SECURITY.md)

## How it was built

quickset was built with a lot of help from an AI coding assistant, Claude
Code, which wrote most of the code. Do not take its correctness on trust for
that reason, or for any other. The rule of the project is that no request may
get a different answer, and the tests check it: each test route exists once
for every tier, every request goes to all of them, and the status, the content
type and the bytes must be equal ([docs/TESTING.md](https://github.com/YasserShkeir/quickset/blob/v0.1.0/docs/TESTING.md)).

## Licence

MIT. quickset is not affiliated with Django-Bolt or with Django.
