agentleFS
JasperFxJasperFx/marten/CLAUDE.md

marten

CLAUDE.md3.5k starsChanged 9 months agoMITView on GitHub

.NET transactional document database and event store on PostgreSQL. Uses PostgreSQL's JSONB support for document storage with ACID guarantees and a full event sourcing implementation with projections. Repository: https://github.com/JasperFx/marten Version: 9.0.0-alpha.1 (Directory.Build.props:4) — 9.0 long-lived dev branch License: MIT An assembly compiled against the previous Marten release must keep working when the new Marten is dropped underneath it, without being recompiled. Source compatibility is not enough. Never add an optional parameter to an existing public method. Optional arguments are resolved…

  • Installs packages

Adopted by

Steady: 0 new projects took it in the last 4 weeks, none the 4 weeks before.thin data

Week of Sep 20: 0 new projectsWeek of Sep 27: 0 new projectsWeek of Oct 4: 0 new projectsWeek of Oct 11: 0 new projectsWeek of Oct 18: 0 new projectsWeek of Oct 25: 0 new projectsWeek of Nov 1: 0 new projectsWeek of Nov 8: 0 new projects
Sep 2026Oct 2026Nov 2026
New projects taking a version of this file each week, over the 8 weeks our latest run read: only 0 in all, so this is a hint, not a trend.

Who's talking about JasperFx/marten

The biggest 5 of 55 mentions linking to the repository that our crawl found. Each line is their own headline.

See all 55

Talked about on GitHub and Stack Overflow (55 times).

On GitHub · 50

45 more on GitHub

The file

We split this CLAUDE.md into the rules it gives an agent

11 rules. About 0 are common, 4 are distinctive, and 7 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 7

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Naming: Use PascalCasing for all public or internal members (types, methods, properties, fields, events).

    line 20
  2. Distinctive:

    Do this instead, in order of preference:

    line 44
  3. Distinctive:

    When a change's binding is not obvious, settle it with a throwaway repro that prints which overload binds, rather than by reasoning about …

    line 51
  4. Very specific:

    Test targets run through Bobcat's supervisor rather than dotnet test (build/SupervisedTests.cs, #5096, extended for JasperFx/bobcat#565).

    line 136
  5. Very specific:

    Before raising a suite's count, read the bug shapes in Bobcat's docs/parallel-ready-suites.md: a test that hard-codes marten_testing or a …

    line 155
  6. Very specific:

    Run DaemonTests through ./build.sh test-daemon or its built executable (src/DaemonTests/bin/Release/net10.0/DaemonTests --filter-class …).

    line 181
  7. Very specific:

    Default test connection: Host=localhost;Port=5432;Database=marten_testing;Username=postgres;password=postgres (build/build.cs:28).

    line 187
  8. Very specific:

    If your assertions depend on a document type holding only what your test wrote, say so explicitly.

    line 270
  9. Distinctive:

    If you exclude another suite, write the reason down in both places.

    line 338
  10. Very specific:

    cspell unknown words: Add legitimate technical terms to docs/cSpell.json's words array rather than papering over with <!-- cspell:ignore ...

    line 358
  11. Distinctive:

    When working on specific areas, check these files for patterns and conventions:

    line 362

≈ “Common” is an estimate: at least 1 in 5 of the 27,641 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

Marten

.NET transactional document database and event store on PostgreSQL. Uses PostgreSQL's JSONB support for document storage with ACID guarantees and a full event sourcing implementation with projections.

Repository: https://github.com/JasperFx/marten Version: 9.0.0-alpha.1 (Directory.Build.props:4) — 9.0 long-lived dev branch License: MIT

Tech Stack

  • Language: C# 13.0, targets net9.0 / net10.0 (Directory.Build.props:5,12)
  • Database: PostgreSQL 13+ (via Npgsql)
  • Key deps: JasperFx, JasperFx.Events, JasperFx.RuntimeCompiler, Weasel.Postgresql, Newtonsoft.Json (src/Marten/Marten.csproj:39-46)
  • Build system: Nuke (build/build.cs)
  • Test framework: xUnit + Shouldly
  • Docs: VitePress (docs/)

Coding Conventions

  • Naming: Use PascalCasing for all public or internal members (types, methods, properties, fields, events). Use camelCasing for all protected and private members. (Private fields keep the conventional leading underscore, e.g. _workTracker.)

API compatibility — do not break binary compatibility

An assembly compiled against the previous Marten release must keep working when the new Marten is dropped underneath it, without being recompiled. Source compatibility is not enough.

Never add an optional parameter to an existing public method. Optional arguments are resolved by the compiler at the call site, so the caller's IL hard-codes the full signature. Adding a parameter changes the method's signature in metadata, and every caller that was not recompiled throws MissingMethodException at runtime — even though their source still compiles unchanged. This is only acceptable in a major version bump.

It bites hardest where you cannot see it: a prebuilt assembly between the app and Marten — a Wolverine integration, CritterWatch, a company-internal extension package — compiled against the old version and never rebuilt. It breaks in production on what looked like a routine patch bump.

Adding an optional parameter is also not additive at the source level. It changes overload resolution: C# prefers the candidate with no omitted optional parameters, so widening a parameterless overload steals calls from its single-argument sibling. In #5404, giving AddMarten() an optional string silently rebound every AddMarten(connectionString) call — the connection string landed in the new parameter and the store was left with no tenancy. It compiled clean, with no ambiguity error.

Do this instead, in order of preference:

  1. Put new configuration on StoreOptions. Adding a member is binary compatible. This is how EventModelName is configured — opts.EventModelName = "Ledgers", not an AddMarten argument.
  2. Add a new overload and leave the existing signature in place, if it genuinely has to be an argument. Check what the new overload does to resolution for every existing call shape first.

When a change's binding is not obvious, settle it with a throwaway repro that prints which overload binds, rather than by reasoning about the spec.

Project Structure

src/
  Marten/                  - Core library (document store, event store, LINQ, sessions)
  Marten.AspNetCore/       - ASP.NET Core integration (streaming endpoints)
  Marten.NodaTime/         - NodaTime date/time support
  Marten.Testing/          - Shared test harness: fixtures, base classes, helpers
  CoreTests/               - Schema management, retries, core services
  DocumentDbTests/         - Document storage features
  EventSourcingTests/      - Event sourcing, projections, daemon
  LinqTests/               - LINQ-to-SQL translation
  MultiTenancyTests/       - Multi-tenancy isolation
  PatchingTests/           - Partial document updates
  ValueTypeTests/          - Strongly-typed ID support
  DaemonTests/             - Async projection daemon
  CommandLineRunner/       - CLI for codegen and DB management
  TestingSupport/          - Shared test infrastructure
build/                     - Nuke build automation
docs/                      - VitePress documentation site

Key Source Directories Within src/Marten/

DirectoryPurpose
Events/Event sourcing: appenders, projections, aggregation, daemon
Internal/Sessions/Session implementations (lightweight, identity map, dirty tracking)
Internal/Storage/Document storage variants and providers
Internal/Operations/Storage operations (insert, update, upsert, delete)
Internal/CodeGeneration/Runtime code generation for storage providers
Linq/LINQ query parsing, SQL generation, compiled queries
Schema/Document mapping, indexes, DDL generation
Storage/Tenancy strategies, database management
Patching/Fluent partial-update API
Subscriptions/Event subscription processing
Metadata/Metadata policies (versioning, soft delete, timestamps)

Build & Test

Prerequisites: .NET SDK 8.0+, PostgreSQL 13+ (Docker recommended)

# Start PostgreSQL
docker-compose up -d

# Build
./build.sh compile

# Run all tests
./build.sh test

# The tests.yml suites at once, through Bobcat's local gate (see "Local gate" below)
./build.sh LocalGate

# Run individual test suites — one target per test project
./build.sh test-base-lib                     # Marten.Testing
./build.sh test-core                         # CoreTests
./build.sh test-document-db                  # DocumentDbTests
./build.sh test-event-sourcing               # EventSourcingTests
./build.sh test-daemon                       # DaemonTests
./build.sh test-linq                         # LinqTests
./build.sh test-multi-tenancy                # MultiTenancyTests
./build.sh test-patching                     # PatchingTests
./build.sh test-value-types                  # ValueTypeTests
./build.sh test-modular-config               # ModularConfigTests
./build.sh test-tenant-partitioned-events    # TenantPartitionedEventsTests
./build.sh test-container-scoped-projections # ContainerScopedProjectionTests
./build.sh test-stress                       # StressTests (not in CI, see below)
./build.sh test-compiled-queries             # CompiledQueryTests
./build.sh test-source-generator             # Marten.SourceGenerator.Tests (no database)
./build.sh test-multi-host                   # MultiHostTests (needs its own compose, see below)
./build.sh test-extensions                   # NodaTime, AspNetCore, PostGIS, PgVector,
                                             #   TimescaleDB, EntityFrameworkCore, MemoryPack

# MultiHostTests needs a primary/standby pair on 5440/5441 rather than the ordinary database
docker compose -f src/MultiHostTests/docker-compose.yaml up -d

# Docs
npm install && npm run docs

Test targets run through Bobcat's supervisor rather than dotnet test (build/SupervisedTests.cs, #5096, extended for JasperFx/bobcat#565). What it does:

  • Retries are opt-in, and always in a fresh process. A failing test is retried only when it carries [Trait("Retry", "N")] (or [Trait("Isolated", "true")]); anything else that fails is red. This is Bobcat's own default policy since 1.0 (bobcat#661); never add [Trait("RetryWarm", "true")], which would retry in the same process, over a half-built store. A test that only passes on a retry is reported as flaky — in the log, in the GitHub job summary and in the JSON ledger under artifacts/test-ledger/ — never folded into a clean pass. A test earns a Retry trait with evidence from the flakiness roll-up, and the trait carries a comment saying what that evidence was. Never add one to hide a deterministic failure.
  • N in Retry=N can only lower the run-wide ceiling of 3 attempts (MaxAttemptsPerTest), never raise it: the operator, not the test, owns how long a run may take.
  • --disable-test-retry turns every retry off. Measure a suite's real stability with this on.
  • Worker processes, a database each. A target may pass workers: N: the suite is split across N test hosts, partitioned by test CLASS, and each lane gets its own database (marten_testing_w0..N-1, created on demand, handed over through marten_testing_database). The count is clamped to ProcessorCount / 2 on the machine running; --test-workers N overrides both the target's count and the clamp (--test-workers 1 is the sequential baseline). Before raising a suite's count, read the bug shapes in Bobcat's docs/parallel-ready-suites.md: a test that hard-codes marten_testing or a port ignores its lane.
  • Stalls and a heartbeat (report-only): a test in flight for five minutes is named as [STALLED], and a progress line every 30s says how far the run got.
  • Lane balancing from the previous master run's ledger (a CI artifact, nothing committed). Each test job downloads the folded-test-ledgers artifact of the newest successful master run into artifacts/previous-test-ledger/; its per-test durations (Bobcat's TestLedger, keyed by display name since Bobcat 1.0) balance the lanes, and the run writes the folded ledger to artifacts/test-ledger/durations/, which the flakiness job gathers for the next run. Locally, --previous-test-ledger <dir> points at a downloaded copy; with none, lanes balance by test count. The run report's first line says how many durations matched.

This requires each test project to build as a Microsoft.Testing.Platform host, which <UseMicrosoftTestingPlatformRunner> in src/Tests.props turns on for every project importing it. A new test project must import src/Tests.props.

DaemonTests is on a different xUnit line from every other suite (JasperFx/bobcat#562). It renders its tests as Bobcat specifications through Bobcat.Xunit 1.0, which requires xunit.v3 4.x on Microsoft.Testing.Platform 2.x, while the rest of the repo stays on xunit.v3 3.x. The two lines cannot share a test project, so DaemonTests and DaemonTests.ManualOnly take 4.x through VersionOverride (BobcatXunitV3Version in Directory.Packages.props). Consequences:

  • Never add a ProjectReference to DaemonTests from another test project: it drags xunit 4 into that project. CoreTests had one, used only for a transitive Lamar, and lost it for this reason.
  • On 4.x, [assembly: CollectionBehavior(DisableTestParallelization = true)] is a compile error; DaemonTests uses [assembly: Xunit.v3.Parallelization(Mode = Xunit.Sdk.ParallelMode.None)].
  • Run DaemonTests through ./build.sh test-daemon or its built executable (src/DaemonTests/bin/Release/net10.0/DaemonTests --filter-class …). dotnet test on an MTP 2.x host needs global.json's "test": { "runner": "Microsoft.Testing.Platform" }, a repo-wide switch not made here.
  • The rendered specifications print at exit. In CI, set BOBCAT_SPEC_CONSOLE_FILE=<path> to get them as a file; since Bobcat 1.0.0-rc.1 (bobcat#717) a redirected stdout gets them too, instead of nothing.

Default test connection: Host=localhost;Port=5432;Database=marten_testing;Username=postgres;password=postgres (build/build.cs:28). Override with marten_testing_database env var.

Local gate: the whole matrix before a push

./build.sh LocalGate (build/LocalGate.cs, #5725) runs the logical suites of tests.yml on this machine through Bobcat's local gate (GateDeclaration in Bobcat.Supervisor, see Bobcat's local gates). It needs only docker compose up -d.

./build.sh LocalGate                                  # every default suite, newest TFM (net10.0)
./build.sh LocalGate --framework all                  # net9.0 and net10.0 units
./build.sh LocalGate --gate-only Linq EventSourcing   # a subset, by matrix name or project name
./build.sh LocalGate --gate-skip-build                # reuse the Release build already on disk

What it does, in order: Init once (clean, connection.txt, AssemblyInfo.cs); a preflight of the Postgres server; one dotnet build src/Marten.slnx -c Release; then one supervised run per (project, framework) unit, longest first, never more worker processes at once than the budget; then a report with one line per unit and the full run report of every unit that was not clean. Every unit runs even when another fails. The target fails when any unit failed or could not run.

  • Same supervisor as CI. Each unit gets the configuration its Test* target uses (configureSupervisor in build/SupervisedTests.cs): retries only for [Trait("Retry", "N")], in a fresh process, the stall report, the heartbeat, and the same worker counts (EventSourcing and Linq at 4). --disable-test-retry and --test-workers apply as they do there.
  • A database per lane. Each unit runs on its own databases, marten_testing_<project>_<tfm>_w{n}, handed over through marten_testing_database, so two suites never share a schema.
  • Tracks for fixed names. Some suites create whole databases with fixed names on the server, or reach for the default database directly. Those suites hold an exclusive track while they run, so the gate never runs two of them that share a name at once: tenant-databases (tenant1..tenant6 and database1: Core, Daemon, MultiTenancy, Stress), shard-databases (marten_shard_*: MultiTenancy, TenantPartitionedEvents) and default-database (EventSourcingTests' testing_projections hard-codes localhost:5432/marten_testing; Stress).
  • The worker budget is half the cores, lowered to what the server's free connections hold at about 40 per worker. A stock Postgres allows 100 connections, which gives a budget of 2. docker-compose.yml sets max_connections=500, so recreate an older container once (docker compose up -d --force-recreate) to run at the full budget. --gate-worker-budget N sets the budget directly.
  • Durations. .bobcat/gate-durations.json (ignored) records each unit's wall clock on this machine and orders the next run. .bobcat/test-ledger/ keeps the folded test ledgers that balance lanes.
  • BOBCAT_RUN_TAG is the prefix: each unit publishes to the monitor as <tag>/<project>.<tfm>.

Options that need more than the ordinary database are opt-in:

OptionWhat it adds
--gate-include postgisMarten.PostGIS.Tests. The docker-compose.yml image includes PostGIS.
--gate-include timescaledbMarten.TimescaleDB.Tests on docker-compose.timescaledb.yml (port 5433, which Wolverine's Postgres also uses; the preflight checks the extension). --gate-timescale-database points it elsewhere.
--gate-include multihostMultiHostTests on the replication pair in src/MultiHostTests/docker-compose.yaml (5440/5441). The preflight logs in with the suite's credentials, so another container on those ports fails it.
--gate-include stressStressTests, which has no CI job. It holds every fixed-name track.
--gate-serializer splitCI's pairing: net9.0 units on Newtonsoft, net10.0 units on System.Text.Json. Newtonsoft or SystemTextJson sets one serializer for every unit. With no option, the suites use their default, Newtonsoft.
--gate-database <conn>Another Postgres server for the lanes. For the PG15 leg, start a Postgres 15 container and run --gate-database "Host=localhost;Port=<port>;Database=marten_testing;Username=postgres;password=postgres" --framework net9.0 --gate-serializer Newtonsoft.

Measured on this 18-core machine at net10.0. With a 500-connection server (budget 9), the default gate takes about 8 minutes end to end. The units themselves take 7m40s, against 13m20s of unit time one after the other. DaemonTests is the longest unit at about 6m45s and sets the wall clock. CoreTests and MultiTenancyTests share its tenant-databases track, so they run after it. On a stock 100-connection server (budget 2) the units take 11m30s.

Test Harness

Base classes in src/Marten.Testing/Harness/:

  • IntegrationContext (IntegrationContext.cs:49) - Standard integration tests. Shared DocumentStore, data is NOT cleared between tests. Uses [Collection("integration")].
  • DestructiveIntegrationContext - Wipes entire public schema between tests.
  • OneOffConfigurationsContext - Creates isolated DocumentStore with custom schema per test.
  • BugIntegrationContext - Like OneOffConfigurationsContext, but pins every bug test to one shared bugs schema.
  • StoreFixture / StoreContext<T> - Share DocumentStore across tests via collection fixtures.
  • SessionTypesAttribute (IntegrationContext.cs:36) - Theory data source for testing across None/IdentityOnly/DirtyTracking session modes.

Clearing data between tests

IntegrationContext does not clear the store between tests. DefaultStoreFixture calls CompletelyRemoveAllAsync() exactly once, when the fixture is created — never per test. The same is true of OneOffConfigurationsContext within its collection.

That is deliberate: resetting everywhere would cost more than it is worth. The consequence is that a test asserting on a global count or ordering — Query<Target>().CountAsync() with no filter, say — only passes while it happens to run before its siblings, and any change to test ordering turns that into a failure. Several tests had to be fixed for exactly this reason; see #5070.

If your assertions depend on a document type holding only what your test wrote, say so explicitly. On IntegrationContext and StoreContext<T>, declare the types — they are cleared before each test in that class:

protected override IEnumerable<Type> ClearedBeforeEachTest => [typeof(Target)];

OneOffConfigurationsContext and BugIntegrationContext build their store lazily from the test's own StoreOptions(...) call, so there is nothing to clear that early. Those clear inline, after configuring the store:

await theStore.Advanced.Clean.DeleteDocumentsByTypeAsync(typeof(Target));

Either way, name the types you actually depend on rather than reaching for ResetAllData().

Note BugIntegrationContext pins every bug test across every suite to the single bugs schema, and CI runs several test projects sequentially against one database, so a global count there can pick up rows written by an entirely different project.

Environment Variables

VariablePurpose
marten_testing_databaseOverride test connection string
DEFAULT_SERIALIZERSystemTextJson or Newtonsoft. Note this is the test harness default (TestsSettings.cs), not the product's — Marten itself defaults to System.Text.Json, and Newtonsoft is the opt-in Marten.Newtonsoft package
postgresql_versionEnforce specific PostgreSQL version detection

There is deliberately no DISABLE_TEST_PARALLELIZATION here (#5529). It used to be listed and set in CI, and nothing in the repository ever read it — so it looked like a control and was not one, which cost real debugging time when it was used to wrongly rule out in-process parallelism as a cause. Parallel execution is disabled by [assembly: CollectionBehavior(DisableTestParallelization = true)] in src/CoreTests/AssemblyInfo.cs and src/Marten.Testing/AssemblyInfo.cs.

CI

.github/workflows/tests.yml is one job per test project (#5096). Each matrix entry carries its own target framework, serializer and Postgres image, and gets its own runner and its own database, so suites never contend and adding coverage costs no wall clock. The core suites keep both combinations they always had — net9.0/PG15/Newtonsoft and net10.0/PGlatest/System.Text.Json — and the extension suites each name the image they need (postgis, pgvector, timescaledb). Tests run in Release with in-process parallelization disabled; EventSourcingTests and LinqTests are split across worker processes instead (workers: 4 in build/build.cs, clamped to 2 on a 4-vCPU hosted runner), each worker on its own database. DaemonTests is still at one worker: under JasperFx/bobcat#562 it ran green at two lanes locally (374/374 twice, 5m10s against 7m09s at one, retries off), but that was not judged enough evidence to change the gate on the most timing-sensitive suite.

Adding a test project means two edits: a target in build/build.cs AND an entry in tests.yml. The previous shape was a hand-maintained list of steps inside a handful of monolithic jobs, and a project was in CI only if somebody remembered to add a step; ten suites (~780 tests) turned out to be running nowhere at all. The matrix is now the single answer to "what does CI run", so keep it that way.

A flakiness roll-up job downloads every job's retry ledger and reports the aggregate on the run page — which suites spent retries, and which tests only passed on one.

Two targets deliberately have no CI job, and both say why where they are declared in build/build.cs rather than only by being absent:

  • TestStress (StressTests) — excluded 2026-08-08. It calls ResetAllData mid-run and creates and drops whole databases, which makes it a poor gate on a pull request even though it passes cleanly. Run it with ./build.sh test-stress; ./build.sh test still includes it.
  • TestMultiHost — has a job, but needs the primary/standby pair from src/MultiHostTests/docker-compose.yaml rather than the ordinary database, so it is the one entry carrying a compose: field.

If you exclude another suite, write the reason down in both places. An exclusion nobody recorded a reason for is how ten suites went dark before #5096, and a commented-out step reads as a settled decision long after everyone has forgotten there was one.

Documentation linting (run locally before pushing doc changes)

The Documentation PRs workflow (.github/workflows/docs-prs.yml) runs markdownlint and cspell over every file under docs/. Both are fast and cheap to run locally — do so whenever a commit touches docs/**/*.md (or a source file whose comment is pulled into a <!-- snippet: ... --> block) before pushing, so the PR doesn't have to wait on CI to surface lint failures:

# markdownlint — same args CI uses
npx --yes markdownlint-cli@latest --disable MD009 -- "docs/**/*.md"

# cspell — same args CI uses (requires Node >= 22; use nvm if your default is older)
npx --yes cspell --config ./docs/cSpell.json "docs/**/*.md"

Common issues to watch for:

  • MD051 (link-fragments). Heading slugs are generated from the heading text after stripping markdown but including trailing inline components like <Badge type="tip" text="9.0" />, which leaves a trailing hyphen on the slug. If you intend to link to a heading section, either drop the <Badge> from the heading (use a ::: tip callout under it instead) or write the link with the trailing-hyphen slug.
  • Snippet drift. Snippet blocks (<!-- snippet: sample_* -->) are mechanically regenerated from #region sample_* markers in the source tree. Edit the source comment, not the doc markdown copy, or the next snippet refresh wipes the markdown change.
  • cspell unknown words. Add legitimate technical terms to docs/cSpell.json's words array rather than papering over with <!-- cspell:ignore ... -->.

Additional Documentation

When working on specific areas, check these files for patterns and conventions:

  • Architectural Patterns - Design patterns, DI conventions, session model, code generation, event sourcing patterns, and testing conventions used across the codebase.
  • VitePress Docs - User-facing documentation with code samples referenced via <!-- snippet: sample_* --> markers tied to #region sample_* blocks in source.
  • CONTRIBUTING.md - Contribution workflow, PR guidelines, git rebase strategy.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.