Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ jobs:
run: uv tool install meson && uv tool install ninja

# TSAN and ASAN are mutually exclusive, so this is a dedicated job with
# only the thread sanitizer. It exercises the concurrent torn-read test
# (design §7 #5); the library auto-selects its race-free payload copy
# under TSAN, so a clean run proves the synchronisation, not luck.
# only the thread sanitizer. It runs the concurrent torn-read tests
# described under Verification in docs/design.md. The library selects
# its race-free payload copy under TSAN, so a clean run checks the
# synchronisation itself.
- name: Configure (debug + thread sanitizer)
run: meson setup build-tsan --buildtype=debug -Dbuild_tests=true -Db_sanitize=thread

Expand Down
172 changes: 90 additions & 82 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# AGENTS.md

## Project-specific instructions
---

## 1) Project-specific instructions

**Project:** `seqlock`
**Primary goal:** Single-writer / multi-reader sequence lock (seqlock) for lock-free, internally consistent snapshots of a multi-word value. Readers never block the writer and never observe a torn tuple.
**Primary goal:** A C11 single-writer, multi-reader sequence lock: one producer publishes a multi-word value with a wait-free store, any number of readers take consistent copies with a lock-free load, and no reader ever accepts a mixture of two stores. No allocation, no system calls, no locks.

### Essential commands
### 1.1 Essential commands

#### Configure and build (library only)

Expand All @@ -17,7 +19,7 @@ meson compile -C build
#### Configure, build, and run unit tests

```sh
meson setup build --wipe --buildtype=debug -Dbuild_tests=true
meson setup build --wipe --buildtype=debug -Dbuild_tests=true -Db_sanitize=address,undefined
meson compile -C build
meson test -C build --verbose
```
Expand All @@ -29,104 +31,110 @@ meson setup build-tsan --wipe --buildtype=debug -Dbuild_tests=true -Db_sanitize=
meson test -C build-tsan --verbose
```

Run TSAN on an x86-64 host (or a 4K-page AArch64). TSAN cannot initialise on a
16K-page AArch64 kernel (47-bit VMA); use a native or ASAN/UBSan build there.
#### MISRA C:2023, once per atomic backend (reads `build/compile_commands.json`)

```sh
env -u MISRA_RULE_TEXTS misch run --baseline
env -u MISRA_RULE_TEXTS misch run --baseline --profile c11
env -u MISRA_RULE_TEXTS misch run --baseline --profile no_atomics
misch deviations
```

#### Formatting (pinned clang-format through `uvx`)

```sh
scripts/format.sh # check, as CI does
scripts/format.sh --fix # rewrite in place
```

### 1.2 Notes

- `meson setup` generates the optional `seqlock_version.h` into the build directory; `seqlock.h` does not include it.
- The build produces only a static library. The only Meson option is `build_tests`.
- `SEQLOCK_COUNTER_TYPE` and the backend macros must be identical for the library and every caller; nothing detects a mismatch. `seqlock.h` includes `seqlock_conf.h` with quotes, so configuration is by `-D` only, never by a replacement header.
- ThreadSanitizer needs a 4 KiB-page kernel with a 48-bit address space on AArch64, and AddressSanitizer does not start on a 39-bit one; use a plain native build there.

---

## 2) Non-negotiable design invariants

### CI / source of truth
- **Protocol.** Odd counter store, release fence (F1), payload copy, release store of the next even value. Reader: acquire load, copy, acquire fence, relaxed load, accept only on equality. Never remove F1 or weaken an ordering; a compiler barrier is not a substitute on weakly ordered CPUs.
- **One writer per cell.** `store` is never concurrent with another `store` on the same cell, and `init` is never concurrent with anything.
- **Type-erased core.** The protocol, fences and payload copy live once, in `src/seqlock.c`. `SEQLOCK_DEFINE` emits only `static inline` forwarders, and the cell layout `{ seqlock_hdr_t hdr; type payload; }` is part of the contract.
- **Selectable backend.** Every counter access and fence goes through the `seqlock_conf.h` macros. The two atomic backends must reject a counter that is not always lock-free at compile time.
- **Payload copy.** `memcpy` under `no_sanitize("thread")` by default, relaxed byte-wise atomics under ThreadSanitizer. A change to the copy keeps ThreadSanitizer clean and the mt and soak tests passing.
- No heap, no system calls, no blocking, no global state.

---

## 3) CI / source of truth

- CI definitions live in `.github/workflows/ci.yml`.
- A dedicated `tsan` job runs the thread sanitiser; ASAN and TSAN are mutually
exclusive, so it is separate from the ASAN/UBSan matrix.
- Prefer running the same commands locally as CI runs.
- If `pre-commit` is configured later, run it before committing.
- Prefer running the same commands locally as CI runs (see §1.1 above).
- Install Python tools (Meson, Ninja, gcovr, misch) with `uv tool install`, never `pip`; CI does the same through `astral-sh/setup-uv`. CI installs `cppcheck` from Homebrew because Ubuntu's 2.13 reports different findings.
- `misch run --baseline` must pass for the base configuration and both profiles; each has its own baseline in `analysis/baseline/`. Never regenerate a baseline to admit a new finding. Run it with `MISRA_RULE_TEXTS` unset, as CI does.
- The CI jobs are: tests under ASan/UBSan, the same tests under ThreadSanitizer, a release build, a 100 percent line and branch coverage gate merged across backends, a TI C2000 library build (CGT 22.6.2 and 25.11.1, COFF and EABI, warnings as errors), `clang-format`, and `misch` for each backend.

---

## 4) Docs / commit conventions

### Documentation layout

- `README.md` is a short landing page (about 85 lines). Put detail in `docs/`, never in the README; link to the owning file instead.
- `docs/integration.md` owns requirements, install methods, configuration consistency, building, sanitiser host limits, and cross builds.
- `docs/api.md` owns the API reference, the configuration macros and recipes. Change it together with the headers; keep signatures in fenced `c` blocks and describe them in prose, not function tables. Check every value an example states against a build.
- `docs/design.md` is the single authoritative design record: protocol, memory ordering, backends and their limits, payload copy, progress, counter wrap, failure behaviour, MISRA position, and verification.
- `CONTRIBUTING.md` documents the contributor workflow; `CHANGELOG.md` holds release history (Keep a Changelog); `.github/SECURITY.md` covers vulnerability reporting.
- Code blocks in `README.md`, `CONTRIBUTING.md`, and `docs/` are compiled by the `seqlock docs examples` test (`tests/docs/check_snippets.py`). Each document is compiled as one source file: a `c` fence is file-level code, `<!-- snippet: body -->` wraps statements, and `<!-- snippet: skip -->` excludes pseudo-code. Do not use `skip` to silence a broken example.
- Prose uses British spelling. Do not hard-wrap Markdown: write one line per paragraph. The 80-column limit applies to C source, not Markdown.

## Docs / commit conventions
### Commits

- Use Conventional Commits when asked to commit.
- Keep commits focused and explain why the change exists.
- **Never** commit unless the user explicitly asks.
- Use **Conventional Commits** format when asked to commit.
- Keep commits focused; explain *why* in the message body.

## C style expectations
---

### Build and configuration
## 5) C style expectations

- Use the Meson build system; do not introduce another build system.
- Update `meson.build` when adding or removing source files or public headers.
- `seqlock_conf.h` is a public configuration header; install it alongside
`seqlock.h`.
- The library is `both_libraries('seqlock', 'src/seqlock.c', ...)`: the compiled
core is a real translation unit, not an empty stub.
### Build & configuration

- Use the Meson build system. Do not introduce CMake, Make, or other systems.
- Update `meson.build` and `tests/meson.build` when adding or removing files.
- `seqlock_conf.h` is public and installed beside `seqlock.h`. Every option in it stays behind an `#ifndef` guard.

### Formatting

- `.clang-format` is present and should be used on modified `.c` and `.h` files.
- `.clang-format` is present and **mandatory**. Run `scripts/format.sh --fix` before committing. It runs the clang-format release pinned in the script through `uvx`. Do not use a system `clang-format`: another release can format the same code differently.
- Do not reformat unrelated code.
- Key settings: 8-space indent, `BreakBeforeBraces: Linux`, column limit 80.
- Avoid em dashes in comments, doc-comments, and prose.

### Style and correctness

- Match the conventions in the existing files.
- All public identifiers use the `seqlock_` / `SEQLOCK_` prefix.
- Keep public headers minimal and stable; do not expose internal helpers.
- Prefer explicit fixed-width integer types when ABI or serialisation matters.
- No dynamic memory, no syscalls, no blocking anywhere in the library.
- Compile-time validation via `_Static_assert` (lock-free counter, non-empty and
non-over-aligned payload); the primitive must fail to compile rather than
degrade silently.
- Public symbols carry Doxygen annotations with full contract information
(preconditions, concurrency, return semantics).
- Use `seqlock_conf.h` for compile-time configuration options. It is included
automatically by `seqlock.h` and every option is `#ifndef`-guarded so a
consumer can override it (e.g. via a project `config/seqlock_conf.h`).
- **Do not** preserve backwards compatibility unless the user explicitly asks.

### Architecture / API design

- Hybrid layout: a type-erased core (`seqlock_core_*` in `src/seqlock.c`) holds
all correctness-critical logic, and `SEQLOCK_DEFINE(name, type)` emits thin
`static inline` typed shims that forward to it. Keep the protocol, fences, and
TSAN handling in the core, in one place; the shims only add type safety.
- The generated cell layout is fixed and part of the contract:
`{ seqlock_hdr_t hdr; type payload; }`, `hdr` first.
- Single-producer: at most one thread calls `store()` per cell; concurrent
writers are undefined behaviour.
- `load()` / `try_load()` are safe for any number of readers concurrent with the
writer. The payload must be trivially copyable POD, stored by value.
- `init()` is setup-only and must not run concurrently with `store()`/`load()`.
- `try_load()` returns `false` on bound exhaustion; `*out` is then unspecified
(no scratch buffer is allocated). Callers branch on the return value.

### Concurrency correctness (read before touching the protocol)

- The writer's release fence after the odd increment (F1) is **mandatory** on
weakly-ordered CPUs; a plain compiler barrier is NOT sufficient. Do not
"simplify" it away.
- The even increment publishes via a release store; the reader's first load is
acquire and its second load is preceded by an acquire fence. Do not weaken
these orderings.
- Payload-copy race handling uses a benign `no_sanitize("thread")` `memcpy`
normally, and a race-free relaxed-atomic copy under TSAN (auto-selected via
`SEQLOCK_ATOMIC_PAYLOAD_COPY`). If you change the copy, the TSAN test must
stay clean and the deterministic torn-read test must still pass.
- All atomics and fences go through the `seqlock_conf.h` macros so the backend
(`__atomic`, C11, or uniprocessor fallback) stays swappable.
- Keep each file's existing `/* ==== NAME ==== */` section banners.

### Style & correctness

- Match conventions in the existing files (indentation, braces, naming).
- Every public identifier uses the `seqlock_` or `SEQLOCK_` prefix. Keep public headers minimal; do not expose internal helpers.
- Validate pointer arguments at every public API boundary. Public functions return `void` or `bool`; no `errno`.
- Use fixed-width types from `<stdint.h>`; never plain `int` for a fixed-width quantity.
- Reject an unusable configuration with `_Static_assert` or `#error` rather than degrading at run time.
- Public symbols carry Doxygen with the full contract: preconditions, concurrency, and return semantics.

### MISRA deviations

- Prefer compliant code; never restructure only to hide a finding. Deviate at the point of use with `/* cppcheck-suppress misra-c2012-<rule> ; @deviation <rationale> */`, or project-wide in `analysis/deviations/misra-deviations.txt` for a house-style rule.

### Comment placement (Doxygen)

- Inline trailing annotations (`/**< ... */`) on `enum`/`struct` members are allowed only when the resulting line fits the 80-column limit.
- If any member's annotation would overrun, move **all** of that aggregate's member docs into a single structured Doxygen block above the type, as an `@details` list of `- ::SYMBOL description` entries.
- Never mix inline and block forms within one aggregate, and never leave a trailing comment that clang-format would wrap onto a second line.
- After editing, verify with a `clang-format --style=file` no-reformat diff and an 80-column scan.
- After editing, run `scripts/format.sh` and an 80-column scan.

### Testing

- Run `meson test -C build` after changes; also run the TSAN build for any
change to the protocol or the payload copy.
- Tests live in `tests/test_*.c` using the built-in harness in
`tests/seqlock_test.h` (`TEST_CASE` / `TEST_ASSERT` / `run_test`). Do not add
Unity or other external test dependencies.
- The multi-threaded torn-read test (`tests/test_seqlock_mt.c`) doubles as the
TSAN gate; its payload carries a self-checking invariant so any torn read is
detected at runtime, independent of the sanitiser.
- Run `meson test -C build` after every change, and the ThreadSanitizer build for any change to the protocol, a backend or the payload copy.
- Tests use the harness in `tests/seqlock_test.h` (`TEST_CASE`, `TEST_ASSERT`, `run_test`). Do not add Unity or another external framework.
- Concurrency tests assert an invariant, never a timing. Reach new branches deterministically in a single thread, as `tests/test_seqlock_retry.c` does.
- Add a test case for each bug fix and each new feature.
- Keep `src/` and `include/` at the coverage gate (100 percent line and branch).
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
- `scripts/format.sh`, which pins the clang-format release and runs it with `uvx`. CI checks formatting through it.
- CI runs the MISRA C:2023 analysis with `misch` for each atomic backend, fails on any finding outside that backend's recorded baseline, and prints the deviation record.
- CI compiles the library with warnings as errors using two releases of a vendor C11 compiler for a 16-bit-MAU DSP target, under both of its object formats. That compiler selects the uniprocessor backend.
- `docs/integration.md`, `docs/api.md` and `docs/design.md`. The design record covers the protocol and its memory-ordering argument, the limits of the uniprocessor backend, progress guarantees, counter wrap, and verification. The README is now a landing page.
- A `seqlock docs examples` test that compiles every C example in the documentation against the public headers.

### Changed

Expand Down
Loading
Loading