# Database environments for RL and evals

> One seeded database, thousands of identical copies, reset per episode.

The pattern: build the starting state once, take a checkpoint, give every episode its own copy, and reset or discard copies between episodes.

```python
from elefork import Client
import psycopg

c = Client()
project = c.project_by_name("rl")["id"]

# 1. Build the starting state once.
seed = c.create_branch(project, template="pg18", name="seed", ttl_seconds=0)
with psycopg.connect(c.credentials(seed["id"])["uri"]) as db:
    db.execute(open("schema_and_data.sql").read())
start = c.checkpoint(seed["id"], "episode-start")

# 2. One branch per parallel worker, all identical.
envs = c.create_branches(project, checkpoint=start["id"], count=100, name="worker", ttl_seconds=6 * 3600)
# A branch resets only to its own checkpoints, so each worker takes one of its start state.
env_start = {env["id"]: c.checkpoint(env["id"], "episode-start")["id"] for env in envs}

# 3. Each episode: run the agent against its branch, score it, reset.
for env in envs:
    uri = c.credentials(env["id"], ttl_seconds=3600)["uri"]
    ...                                   # agent works against `uri`
    c.reset(env["id"], env_start[env["id"]])   # back to the exact starting state
```

Tips:

- **Reset to the branch's own checkpoint.** `reset` accepts only checkpoints of that branch. To restart from another branch's checkpoint, create a new branch from it instead.
- **Reset instead of re-creating.** A branch keeps its id and hostname across resets, so workers don't need new connection details (new credentials are only needed when the old ones expire).
- **Score from the outside.** An agent connected as superuser can change anything in its database, including tables you would use to score it. Keep expected results outside the episode database, or let Elefork do it: see [Scored evaluations](/docs/guides/evaluations/).
- **Keep failures.** Before resetting a failed episode, `checkpoint` it so you can reproduce it later.
- **Set TTLs.** Branches with a `ttl_seconds` clean themselves up if your job dies.
