small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
albedo robot-docs writing-tests.md
12 kB · 221 lines
Markdown
at main

Write tests #

This page is the project's test policy. It says which tests to write, keep, or delete, and how to check that a test earns its place. Test execution covers how the suites run: tiers by location, property seeds and budgets, contracts, discovery runs, and gate limits.

Keep a test only when it fails for a plausible defect in required behavior, and no cheaper test already fails for that defect. Every test costs gate time, memory, and an edit on each refactor. Skip a test whose maintenance cost exceeds the failures it is likely to catch. Say in the change which significant behavior you left untested.

Pick the cheapest tier that can see the defect #

Test through the narrowest interface that exposes the failure.

  1. Pure logic. Codecs, parsers, line and offset arithmetic, budgets, ordering, deduplication, data migrations. Test the public function in its own package.
  2. State machines in process. Session admission, turns, kernel jobs, compaction, history edits, transfer. Write the interaction as a list of operations, replay it against the owner and against a simple model, and compare after each step. Inject the clock, the provider, and failures.
  3. Contracts across a language or wire boundary. Values between Gleam and Python, SSE, ACP, the HTTP API. Generate many values, pass the whole batch through each side once, and compare. Start each process once per batch, not once per case. See cross-language contracts.
  4. The real daemon end to end (e2e). Wiring that exists only in the assembled system: boot, restart and recovery, a real turn through the CLI or web transport, moves between versions, and discovery of installed extensions. Keep one scenario per seam or user journey. Do not use end-to-end scenarios to enumerate the cases of logic a lower tier can reach.

When an owner cannot be tested in tier 1 or 2 because it reads the clock, the network, or a process directly, add that seam. Do not write an end-to-end scenario for each case instead.

Use the property frameworks #

Write a test of logic that takes a range of inputs as a property or model test. That covers pure functions, codecs, parsers, budgets, state machines, and wire contracts. Use the project's framework for the language, through its wrapper:

Language Library Call it through
Gleam qcheck albedo_property.run
Go rapid property.Check
Python Hypothesis hypothesis_profiles
Web fast-check check from property.mjs
Rust proptest property::config

Write a hand-picked example only in these cases:

  • It is a named regression: a shrunk counterexample or a fixed bug.
  • The contract fixes one specific answer, such as a documented error for one input.
  • It is an end-to-end scenario through the real daemon.

When you change an area whose tests are lists of examples, replace them with a property and keep the regressions among them as named examples.

Do not call a library directly, and do not add another property library. The wrappers apply the gate's fixed seed and budget, the discovery overrides, and the rule that no failure store enters the tree. A direct call runs a random seed in the gate, so its CI failure cannot be replayed from the log. test/property_wrappers.py refuses a direct call or another library, and test/quick.sh runs it. See seeds and budgets for each wrapper's API.

Choose the oracle #

Derive expected results from the documented contract or from examples worked out by hand. Never copy the implementation's logic into an assertion or a model.

  • Example. Use one only as the property frameworks section allows. A regression test must fail on the original defect and pass with the fix. Check this before committing it.
  • Property. State a rule that holds for every input: encode then decode returns the value, normalizing twice equals normalizing once, input order does not change the result, an invariant survives every operation.
  • Reference model. Compare with something too simple to share the bug: a list for an index, a full recomputation for an incremental summary, a linear scan for a query, exhaustive search over small instances for a planner.
  • Operation sequences. For caches, queues, lifecycles, and other state machines, replay generated histories against a model such as a map. They catch ordering and interleaving bugs that single-operation examples miss.
  • Conformance suite. When provider adapters, storage backends, or a fake and the real thing must agree, run one parametrized suite against all of them. Prefer a fake checked by that suite to a mock. A Go fake daemon is checked against the OpenAPI document this way. See fake daemons in Go.
  • Compatibility fixtures. Commit payloads and databases written by old versions and check that current code reads them. Record them on a build from before the change, never with current code, which only tests the code against itself. See storage migrations.

Assert what the contract requires. Check exact strings, structure, or call order only when the contract fixes them. Check error kinds or codes, not messages. After an error, check the postconditions too: state unchanged, no partial write, and a retry that is idempotent where promised. Use a snapshot only when the captured output is itself the behavior.

Write generated tests that find bugs #

  • Make operands interact. Use small key and value domains so overwrites, duplicates, and reuse happen. Mix existing, missing, removed, and fresh ids. Favor empty, single, duplicate, unsorted, maximum-size, and multibyte inputs.
  • Vary how a state is reached, not only what it contains. Vary when reads happen, since a read can fill a cache or force deferred work and hide the bug.
  • Build valid structures, then break one constraint at a time. Fuzz every parser and decoder that accepts untrusted input with unconstrained input as well, and assert it neither crashes nor hangs.
  • Look at what the generator produces. Count the interesting events, such as overwrites, cache hits after a change, and rejected inputs. More cases do not fix a generator that rarely builds the interaction. Enforce such counts only at the gate's seed, as seeds and budgets describes.
  • Keep the gate deterministic: a fixed seed, a small budget, and a replay of every saved counterexample. Print the seed on failure so the log alone reproduces it. Run fresh seeds and long budgets with discovery runs, outside the gate.
  • Commit each shrunk counterexample as a named example regression. A later generator change may stop producing it. See counterexamples.

Large exploratory suites belong on a discovery branch, not on main. That includes unoptimized models, operation grammars, and fault schedules meant to run for hours. Each confirmed bug leaves that branch as one change: a deterministic regression test in the cheapest tier and the smallest complete fix.

Check that a test can fail #

Plant a plausible defect for each test you add or keep, such as a skipped invalidation, a dropped overwrite, or a removed guard. Confirm the test fails, then revert the defect. A test that still passes is blind. Fix it or delete it.

When a new test replaces old ones, plant the defects the old tests guarded and confirm the new test fails for each before deleting them. Name the defects the remaining tests cover in the commit message.

Fix what the tests find #

A failure that shows the product breaking its contract is a bug, not a test problem. Fix the product in the owning module, keep the failing case as a named regression, and update the canonical page when the fix changes documented behavior. When the contract is ambiguous, choose the behavior a caller would expect, document it, and test it.

Do not weaken an assertion, raise a budget, or add a retry to make a real failure pass.

Wait on events, not time #

A test that waits on real time fails when the machine is busy. CI runs many suites side by side, so a wait that fits an idle laptop can miss there.

  • Wait for the event itself: a log line, a row, a status, a message. Do not sleep and then check.
  • Give a wait for an expected event a deadline of at least 10 seconds. The deadline only bounds a hang. A passing run returns as soon as the event arrives.
  • Keep a check that something does not happen short. Its wait is the test's cost on every run, and a busy machine only makes it more lenient.
  • When the deadline itself is the behavior under test, inject the clock or scale the timer, and keep the inner and outer waits consistent.
  • Before changing a deadline for an intermittent failure, reproduce it under load with python3 test/manual/stress.py <command> and measure the slow operation. Do not hide a race with a longer wait.

Delete, or don't write #

  • No plausible defect fails it. It asserts constants, copy, defaults, formatting, source text, or record plumbing.
  • It restates the implementation, so a refactor breaks it and a bug does not.
  • It mocks the unit under test, or mocks more than the external boundary.
  • Another test already fails for the same defect. Extend an existing test before adding an overlapping one. When a property or model test covers a group of example tests, delete the examples and keep the named regressions.
  • It snapshots rendered output with no rule behind it.
  • It sleeps to wait for asynchronous work, or waits on a deadline that is not the behavior under test.

To decide on a test whose value is unclear, plant the defect it claims to catch. Delete the test if nothing fails, or if a cheaper or broader test fails too. Prune one area per change and run the affected suites. When you delete a test module, delete the support modules, probes, and fake servers that only it used.

Conventions #

  • Name the behavior in the test name. Start each module with a docstring that names the defect class it catches and why a cheaper tier cannot. Comment a test only when its reason is not obvious.
  • Write tests and test support in Gleam for the daemon. See write Gleam.
  • One area per end-to-end file, named after that area. ./test.sh selects end-to-end files by name and by e2e/areas.toml.
  • End-to-end tests share one daemon. Isolate each with its own session, workspace, and provider route. Mark a test @exclusive when it changes global state (config.json, extensions.json, creds, the environment) or restarts the daemon. Mark a class @exclusive_class when its tests prepare the same environment and only need to be alone on a daemon. Get a fake server whose address goes into settings from daemon_resource(name, make), and a second daemon from peer_daemon(name). Never boot a daemon yourself. Keep fixture state on the test instance, never in module globals. Read the harness docstring for the API.
  • Signal only processes the test can show are its own. See gate and resource limits.
  • No live network or credentials. Those experiments belong in test/manual.
  • Every check that must pass is listed in test.sh. Add new suites there.
  • Run the affected suites and report real results before calling the work done.