aspace://guide/petclinic-fleet

Pet Clinic

A veterinary clinic with a triage nurse, a scheduler, and two vets who never call one another. They watch one shared space, each reacts to the entry it understands, and each writes the entry the next one is waiting for. This is the first guide of the example series, and the app is the smallest one that shows what coordinating through the space means.

agentspaces-petclinic-fleet 0.5.0AgentSpaces 0.5.0SPEC v0.1.24Java 215 peers in the demo, 6 in the test4 agents in the demo, 5 in the test1 spaceloopback TCP, no keysApache 2.0
The ideaOne visitThe settle windowRun it
aspace://guide/petclinic-fleet/idea

The idea: a clinic that runs itself

A pet owner phones the clinic. A front desk writes the request down, a nurse decides how urgent it is, a scheduler books a vet, and the vet writes the chart. In most software that sequence has a conductor: one service that calls the nurse, takes the answer, calls the scheduler with it, and so on down the line. Pet Clinic has no conductor. The four people share one record-keeping space, and each watches for the one kind of record that is its cue.

The clinic is deliberately small. It has four record types, four kinds of agent, one space, and one rule for every agent: react to the entry you understand and write the entry the next stage is waiting for. That rule is service choreography, and this guide uses the clinic to show how it works, how the binder carries the hard parts for the author, and where it needs care.

ORCHESTRATION: A CONDUCTOR CALLS EACH STAGECHOREOGRAPHY: EACH STAGE WATCHES THE SPACEconductorknows the whole ordernurseassessschedulerbookvetseethe order lives in one place: a new stage meansediting the conductor and everything that calls itclinic spaceVisitRequest, Triage, Appointment, VisitRecordnurseassessschedulerbookvetseeeach stage knows its cue and its output: a new stageis a new agent watching a type that already exists
Two ways to wire the same clinic. In orchestration a conductor holds the sequence and calls each stage, and every call returns to it. In choreography the stages share one space and none of them knows another exists. Pet Clinic is the second shape, so the clinic has no conductor, no queue, and no dispatcher.

Each agent is an ordinary object with one annotated method. The annotation names the space to watch, the method parameter names the entry type that is the cue, and the return value is the next entry. Nobody wires the graph: the nurse produces a Triage, the scheduler consumes a Triage, and the flow exists because those two types are the same.

front deskspace.write(...)nurse@SpaceNotifyscheduler@SpaceReducevet@SpaceNotify, two vetsVisitRequestTriageAppointmentVisitRecordwriteswatcheswritestakeswriteswatcheswritesNo arrow runs from one agent to another. Every arrow goes through the space: an agent writes a record,and the agent whose cue is that record type reacts when it arrives.
The clinic's four steps. The owner's request reaches the front desk, which writes a VisitRequest. The nurse watches for that type and writes a Triage; the scheduler takes the Triage and writes an Appointment; the vet addressed by the Appointment writes the VisitRecord, the finished chart.

Here is a whole agent, the nurse, in 9 lines. It reads a VisitRequest, rates the reason, and returns a Triage. It holds no queue, no thread, and no reference to the scheduler.

PetClinicFleet.java: the nurse
@AgentSpec(name = "triage-nurse", description = "Assigns acuity to each visit request",
        goals = {"triage"})
public static final class Nurse {
    @SpaceNotify(space = CLINIC, lease = "4h", resultLease = "4h")
    public Triage assess(VisitRequest request) {
        return new Triage(request.requestId(), request.petName(),
                triageAcuity(request.reason()), "triaged from: " + request.reason());
    }
}
✓ one cue (VisitRequest), one output (Triage), nothing else
Workflow orchestration Service choreography, as in this clinic
Where the order livesin one conductor that calls every stagein the record types: a Triage is the scheduler's cue because the nurse writes one
What a stage knows about the otherstheir addresses and their APIsnothing; it knows the type it watches and the type it writes
Adding a stageedit the conductorbind a new agent whose cue is a type that already exists, such as a billing agent watching VisitRecord
Where the work waitsin the conductor, or in a queue it ownsin the space, as entries with leases, until the next stage reacts

You have run the quick start, which is a two-stage flow of this shape. This guide takes it to four stages on 6 peers in the test and 5 in the demo. The next chapters introduce the cast, the way the peers form one group, the space and its records, and one visit end to end. Three chapters then go one level down: what the binder does for the author of a @SpaceNotify method (chapter 6), how the scheduler keeps its slot book in the space (chapter 7), and why the clinic's space waits 500 ms before it believes a take (chapter 8).

aspace://guide/petclinic-fleet/cast · chapter 1

The cast

Four kinds of seat make a clinic. The front desk is plain code that writes VisitRequest entries and reads VisitRecord charts; it has no agent. The other three are classes with an @AgentSpec and one cue annotation. The demo seats 5 peers and 4 agents. The test seats 6 peers and 5 agents, because it adds a second scheduler on its own peer so that two schedulers share one slot book (chapter 7).

ONE GROUP, 6 PEERS IN THE TEST (THE DEMO SEATS 5: NO scheduler-2)peer front-deskdemo :7781plain codethe seed: every other peer dials itwrites VisitRequest with space.writepeer triage-nursedemo :7782Nurse@SpaceNotifyassess(VisitRequest) returns Triagepeer schedulerdemo :7783Scheduler@SpaceReducebook(SlotBook, Triage) returns Entriespeer scheduler-2test onlyScheduler@SpaceReducethe same class on a second peerpeer dr-songdemo :7784Vet("dr-song")@SpaceNotifysee(Appointment) returns VisitRecordpeer dr-ruizdemo :7785Vet("dr-ruiz")@SpaceNotifysee(Appointment) returns VisitRecordevery peer holds a full replica of the one space, clinic; the agents on it are all the clinic has
The cast. Four kinds of seat. The front desk has no agent: it writes requests and reads charts. The nurse, the scheduler, and each vet are ordinary objects with one annotated method, bound on a peer of their own. The test adds a second scheduler on its own peer so two schedulers share one slot book.
Agent Peer Annotation Cue, then output
front desk, plain codefront-deskspace.writewrites VisitRequest; reads VisitRecord to print the charts
triage-nurse, class Nursetriage-nurse@SpaceNotifyVisitRequest, then Triage
scheduler, class Schedulerscheduler, and scheduler-2 in the test@SpaceReduceTriage and the current SlotBook, then a new SlotBook and an Appointment
vet, class Vetdr-song and dr-ruiz@SpaceNotifyAppointment, then a VisitRecord, or nothing for a pet booked with the other vet

The two vets are one class with a constructor argument. dr-song is the on-call vet: the scheduler sends every urgent and emergency case there. Both vets receive every Appointment, and the guard on the first line of see ignores the ones addressed to the other vet. That guard is all the routing the clinic has.

aspace://guide/petclinic-fleet/fleet · chapter 2

The peers and the group

A peer is a process with a key, a node on a port, and a replica of every space the group holds. PetClinicFleet.startPeer builds one, and the demo and the test call it once per seat: the demo for front-desk, triage-nurse, scheduler, dr-song, dr-ruiz, the test for front-desk, triage-nurse, scheduler, scheduler-2, dr-song, dr-ruiz. Each call names a TCP port and a seed port. The front desk starts first with seed port 0, so it has nobody to dial, and every later peer lists the front desk as its seed.

HOW A PEER JOINS: group petclinic-fleet, founding the literal petclinic-fleet-v1triage-nurseany later peerfront-deskfirst peer, no seedscheduler, vetslearned from the seed1 dial the seed127.0.0.1:7781, front-desk over tcp2 introducesigned peer ad, group id checked3 membershipthe newcomer is introduced to the members4 cards and adsagents, spaces, capabilities on one gossip stream5 spaces catch updigests, then rumorsthe group id is the SHA-256 of the founding text, so every peer derives the same id with no registry;the demo seeds on a fixed port (7781), the test on a free one; membership then spreads over gossip
How a peer joins. A new peer needs only a seed to dial. It proves a key, learns the members, hears every card, and its spaces fill from the replicas already there. No peer in the middle admits it and no registry holds it: the group id is the hash of the founding, and membership is what the members agree on.

The group is founded from a literal. group() hashes the text petclinic-fleet-v1, so every peer computes the same group id, aspace://zEfEgtojhKwEWzTtqr5f3Yfgkm7puv2JxhNXZAoA4VRCK, with no registry and no document to distribute. Each peer builds its own advertisement around that id with a throwaway issuer key, which changes nothing about the id. Because the founding is a text literal, the group has no signed founding document, so a peer joins it by dialing a seed address, as the figure shows.

PetClinicFleet.java: the group
public static GroupAdvertisement group() {
    GroupId groupId = GroupId.fromFounding(
            "petclinic-fleet-v1".getBytes(StandardCharsets.UTF_8));
    return new GroupAdvertisement("aspace://" + groupId.value(),
            PeerIdentity.generate().peerId(), groupId, Instant.EPOCH,
            Duration.ofDays(365), "petclinic-fleet",
            GroupAdvertisement.MembershipPolicy.OPEN, ConflictStrategyType.LEASE_RACE,
            GroupAdvertisement.GossipParameters.defaults());
}
✓ OPEN membership, LEASE_RACE as the default strategy, the library's gossip defaults
What Value Where it comes from
group namepetclinic-fleetgroup()
group idaspace://zEfEgtojhKwEWzTtqr5f3Yfgkm7puv2JxhNXZAoA4VRCKSHA-256 of the text petclinic-fleet-v1, base58btc
membership policyOPEN: anyone who dials may joinGroupAdvertisement.MembershipPolicy
default strategyLEASE_RACEgroup(); the clinic space inherits it
gossipfan-out 3, period 1 sGossipParameters.defaults()
membershipmember TTL 30 s, ping timeout 2 s, 2 indirect probesGroupMembership.Config in startPeer
transportTcpTransport on 127.0.0.1; the demo uses ports 7781 to 7785, the test asks the operating system for a free port per peerstartPeer, freePort() in the test
securityframes signed with each peer's Ed25519 key; no TLS, no profile, no keys to configurePeerNode.builder(identity).build() uses the default ChannelAuth.SIGNED
tick250 msnode.startTicking
ONE PEER: PetClinicFleet.startPeeridentityPeerIdentity.generate(): a fresh Ed25519 key per peernodePeerNode.builder(identity).build(); listen(TcpTransport, 127.0.0.1:port)groupjoinGroup(group(), Config(30 s, 2 s, 2), seeds): signed frames, no TLSclinic spaceReplicatedSpace, LEASE_RACE, settleWindow(500 ms)AgentSpacesregister(...), group.space(CLINIC, clinic): the binder knows the spaceticknode.startTicking(250 ms): the clock behind membership and gossipWHAT A TICK RUNSmembershipone probe round per groupself-advertisementrefreshed to the membersanti-entropyonce per gossip period (1 s)space replicasdigests, then deltasagents run on virtual threadsthat the binder starts
One peer. startPeer is the whole of a peer: a key, a node on a loopback port, the group, a replica of the clinic space, the facade the agents bind through, and a ticking clock. The agents come afterward, bound one call at a time.
PetClinicFleet.java: startPeer
PeerIdentity identity = PeerIdentity.generate();
PeerNode node = PeerNode.builder(identity).build();
node.listen(new TcpTransport(), HOST + ":" + port);
List<PeerAdvertisement.Endpoint> seeds = seedPort == 0 ? List.of()
        : List.of(new PeerAdvertisement.Endpoint("tcp", HOST + ":" + seedPort, 0));
GroupRuntime runtime = node.joinGroup(group(),
        new GroupMembership.Config(Duration.ofSeconds(30), Duration.ofSeconds(2), 2),
        seeds);
✓ identity, node, group, space, facade, tick

Everything the agents share is the clinic space that every peer builds in startPeer. The front desk keeps the ReplicatedSpace handle and reads and writes it directly; the other peers hand it to the facade, so the binder can find it by name. The agents are bound after the peer is up, with runNurse, runScheduler, and runVet, each of which is one call to group().bind(...).

PetClinicFleet.java: binding an agent
public static AutoCloseable runNurse(Peer peer) {
    return peer.group().bind(new Nurse());
}

public static AutoCloseable runScheduler(Peer peer) {
    return peer.group().bind(new Scheduler());
}
✓ seven AgentSpaces libraries, all on ${agentspaces.version} = 0.5.0, resolved from Maven Central
THE FIVE LAYERS, AND WHAT PET CLINIC STANDS ONagents and the binderAgentSpaces facade, binder: @SpaceNotify, @SpaceReduce, @AgentSpecLayer 4 capabilitiesvote, ordered log, aggregate, content, remote actionsLayer 3 spacesreplicated tuple spaces, leases, strategiesPet Clinicone ReplicatedSpace, clinic: LEASE_RACE, settle 500 msLayer 2 discoverycards, advertisements, locatorsPet Clinicgroup id from a founding literal; a seed endpoint; no cards publishedLayer 1 peeringmembership, gossip, transportsPet ClinicPeerNode, TcpTransport, GroupMembership, a 250 ms tickLayer 0 identityEd25519 keys, signed documents, groupsPet Clinica fresh PeerIdentity per peer; signed frames
The layers under the app. Each layer rests on the one below. A highlighted layer is one the app uses directly; the rest still run beneath it and need no configuration here.
aspace://guide/petclinic-fleet/find · chapter 3

How the agents find each other

The clinic's agents do not look for each other. Each agent looks for an entry type, and the space brings the entries. When the binder binds the nurse it reads the method's parameter type, VisitRequest, builds a template from it, and subscribes to the clinic space. Because the space replicates, a VisitRequest written on the front desk's peer appears on the nurse's peer a moment later and fires that subscription. The same holds for every other hop.

Entry type Who watches it How What happens
VisitRequestthe nurse@SpaceNotify on the parameter typewrites a Triage
Triagethe scheduler@SpaceReduce on the element typetakes it and writes a SlotBook and an Appointment
Appointmentboth vets@SpaceNotify plus a guard on vet()the addressed vet writes a VisitRecord, the other returns null
VisitRecordnobodythe front desk reads it with readAllthe chart is the end of the flow

The peers find each other once, at startup. A newcomer dials the seed, learns the members from it, and from then on gossip carries membership, advertisements, and the spaces' entries, as the join figure of chapter 2 shows. The demo waits 1500 ms after starting the five peers before it writes the first request, which gives the mesh time to form; the test waits the same.

Discovery through cards is the other way a fleet finds its services, and this app publishes none, on purpose. startPeer registers the group with a null discovery service, and the binder publishes an agent card only when it has one to publish to, so no card exists in this fleet. Code Fleet and Intake Fleet, the other two teaching fleets, make the same choice, because the entry types route the work and nothing in them reads a card. If you pass a DiscoveryService, the binder publishes one card per bound agent, each listing what the agent consumes and produces: triage-nurse consumes VisitRequest and produces Triage, scheduler consumes Triage and produces SlotBook and Appointment, and vet consumes Appointment and produces VisitRecord. A console or a planner could then list the clinic's services, as the figure shows with dashed boxes for the cards that do not exist here.

AGENT CARDS: NONE PUBLISHED (THE DISCOVERY SERVICE IS null)triage-nursewould consume VisitRequest, produce Triageschedulerwould consume Triage, produce SlotBook and Appointmentvetwould consume Appointment, produce VisitRecorda console or a plannerwould read the catalogue; there is noneentry typesthe address of every hopno card is read: VisitRequest, Triage,Appointment route the workCode Fleet and Intake Fleet publish no cards either. Pass a DiscoveryService to AgentSpaces.register and the binderpublishes one signed card per bound agent.
No cards in this fleet. When the group has a discovery service, the binder publishes one signed agent card per bound agent, listing what the agent consumes and produces. Pet Clinic registers its group with none, on purpose: the entry types route the work, so no card exists and no console or planner has a catalogue to read.
aspace://guide/petclinic-fleet/spaces · chapter 4

The clinic space

The clinic has one space, clinic, a replica on every peer. It uses the LEASE_RACE strategy: a take is decided by a claim race that waits one settle window (500 ms here, chapter 8). Five record types move through it. The Triage is consumed by a take, and only the scheduler writes and reads the SlotBook, so it is state rather than a message.

THE CLINIC SPACE AFTER EACH STEP, FOR ONE PETstart1 request2 triage3 booking4 chartVisitRequestliveliveliveliveTriagelivetaken, gonetaken, goneSlotBookliveliveAppointmentliveliveVisitRecordlive
What the space holds. The front desk's request stays in the space for its lease. The nurse's Triage lasts only until the scheduler takes it: the scheduler completes it with the new SlotBook, so the Triage is gone and the book and the Appointment remain. The vet's VisitRecord is the last entry of the flow.
Record Written by Read by Lease How it ends
VisitRequestthe front deskthe nurse4 hours, set by the front deskthe lease lapses
Triagethe nursethe scheduler, which takes it4 hours, the nurse's result leasethe scheduler completes it with the new SlotBook
SlotBookthe schedulerthe scheduler, and any peer through Reductions.current7 days, the reduce's accumulator leasethe next fold replaces it
Appointmentthe scheduler, after the bookboth vets7 days, the reduce's accumulator leasethe lease lapses
VisitRecordthe addressed vetthe front desk4 hours, the vet's result leasethe lease lapses
PetClinicFleet.java: the five records
public record VisitRequest(String requestId, String petName, String owner,
                           String species, String reason) {
}
✓ five records, all plain Java records; the space stores them through its CBOR codec
ONE ENTRY IN THE SPACE clinicAppointmentrequestId: "v-3"petName: "Rocky"vet: "dr-song"slot: "immediate"acuity: "EMERGENCY"space strategyLEASE_RACE, settle 500 mslease7 days, the reduce's accumulatorLeasesigned bythe scheduler agent, under its peer's key
An entry. Every shared fact in an AgentSpaces app is a typed record in a space. The space's strategy says how a take is decided, the lease says how long the entry lives, tags make it findable, and the signature says which agent wrote it and lets any member check that.
Behind the scenesThe scheduler's reduce also writes a small reserved JoinTicket entry per key to serialize its folds (chapter 7). It is the only entry type in the space the clinic's code does not declare.
aspace://guide/petclinic-fleet/run · chapter 5

One visit, end to end

The demo's front desk takes four requests, writes them, and walks away. Everything after the write is a reaction. The figure follows Rocky, the emergency, through the five peers of the demo: the front desk writes a request, the nurse rates it and writes a triage, the scheduler folds it into the slot book and writes an appointment, both vets receive the appointment, and the vet it names writes the chart.

ROCKY'S VISIT: ONE REQUEST CROSSES THE CLINIC IN FIVE STEPSfront-deskwrites, readstriage-nurseNurseschedulerSchedulerdr-songVet("dr-song")dr-ruizVet("dr-ruiz")1VisitRequestRocky, hit by carassess() returns Triage2TriageEMERGENCYbook() folds the book3Appointmentdr-song, immediatethe same entrysee() returns VisitRecordsee() returns null4VisitRecordstable after collision5readAll(VisitRecord)
One pet, end to end. Every arrow is the space replicating an entry; no agent calls another. The scheduler's Appointment reaches both vets. The vet it names writes the chart, and the other returns null, which writes nothing. The route for Rocky is fixed by the code: the nurse rates the reason an emergency and the scheduler books the on-call vet at once.

Step 1: the front desk writes

The demo files four requests. Nothing in them names an acuity or a vet: the owner gives a reason in free text, and the rest of the clinic works it out.

PetClinicFleet.java: the front desk
List<VisitRequest> requests = List.of(
        new VisitRequest("v-1", "Bella", "Ada", "dog", "overdue for annual checkup"),
        new VisitRequest("v-2", "Milo", "Ben", "cat", "not eating, lethargic 2 days"),
        new VisitRequest("v-3", "Rocky", "Cleo", "dog", "hit by car"),
        new VisitRequest("v-4", "Luna", "Dov", "rabbit", "routine vaccination booster"));
✓ 4 h lease on each request; after the loop the front desk only watches for charts

Step 2: the nurse rates the reason

The nurse's method runs once for each VisitRequest on the nurse's peer. The rule is a keyword check that stands in for a real triage protocol: it reads the reason and returns one of three acuity levels.

PetClinicFleet.java: the nurse and the triage rule
@AgentSpec(name = "triage-nurse", description = "Assigns acuity to each visit request",
        goals = {"triage"})
public static final class Nurse {
    @SpaceNotify(space = CLINIC, lease = "4h", resultLease = "4h")
    public Triage assess(VisitRequest request) {
        return new Triage(request.requestId(), request.petName(),
                triageAcuity(request.reason()), "triaged from: " + request.reason());
    }
}
✓ the binder writes the return value back as the next entry in the flow
Reading the annotationOn @SpaceNotify, lease = "4h" is the lifetime of the subscription, which the binder renews at half the lease while the agent stays bound, and resultLease = "4h" is the lifetime of the entry the method returns.

Step 3: the scheduler books

The scheduler takes each Triage, folds it into the slot book, and returns two entries: the new book and the Appointment. Urgent and emergency cases go to dr-song with the slot immediate. Routine cases alternate between the vets and take the next half hour, counted from 09:00 (chapter 7 tells how the book stays consistent).

PetClinicFleet.java: the scheduler and the slot labels
@AgentSpec(name = "scheduler", description = "Books each triaged visit with a vet",
        goals = {"schedule"})
public static final class Scheduler {
    @SpaceReduce(space = CLINIC, name = "slot-book", lease = "30s", accumulatorLease = "7d",
            produces = Appointment.class)
    public Entries book(SlotBook book, Triage triage) {
        SlotBook current = book == null ? new SlotBook(0, 0) : book;
        boolean urgent = triage.acuity().equals("EMERGENCY")
                || triage.acuity().equals("URGENT");
        String vet = urgent ? ON_CALL : VETS.get(current.routineTurn() % VETS.size());
        String slot = urgent ? "immediate" : slotLabel(current.nextSlot());
        SlotBook next = urgent ? current
                : new SlotBook(current.routineTurn() + 1, current.nextSlot() + 1);
        return Entries.of(next,
                new Appointment(triage.requestId(), triage.petName(), vet, slot, triage.acuity()));
    }
}
✓ an Entries fork: the first element is the accumulator, the others are side outputs

Step 4: the vets answer

Both vets receive every Appointment, because a notify subscription reports each entry to every agent bound on every peer. The vet the appointment names diagnoses the pet and returns a VisitRecord. The other vet returns null, and the binder writes nothing for a null.

PetClinicFleet.java: a vet
@AgentSpec(name = "vet", description = "Sees the pets booked with it and writes the chart",
        goals = {"treat"})
public static final class Vet {
    private final String vetName;

    public Vet(String vetName) {
        this.vetName = vetName;
    }

    @SpaceNotify(space = CLINIC, lease = "4h", resultLease = "4h")
    public VisitRecord see(Appointment appointment) {
        if (!appointment.vet().equals(vetName)) {
            return null; // not mine
        }
        String[] outcome = diagnose(appointment.petName());
        return new VisitRecord(appointment.requestId(), appointment.petName(), vetName,
                outcome[0], outcome[1]);
    }
}
✓ return null writes nothing

Step 5: the charts

The front desk polls its own replica for VisitRecord entries until all four have arrived, then prints them. The loop is the only place the clinic waits for anything, and it belongs to the demo: the agents never wait.

PetClinicFleet.java: reading the charts
for (int tick = 0; tick < 40; tick++) {
    records = frontDesk.clinic().readAll(Template.of(VisitRecord.class), 100);
    if (records.size() >= requests.size()) {
        break;
    }
    sleep(500);
}
✓ one readAll on the local replica every 500 ms, up to 40 times

The four pets, as the demo ran them

The acuity column is what the keyword rule in triageAcuity gives for each reason; the build computes it from the source and checks it against the recording. The vet and slot columns are from one recorded run (2026-11-04). The emergency and the urgent case always go to dr-song at once. The two routine pets split between the vets and take 09:00 and 09:30, but which pet gets which vet depends on the order the scheduler folds them, so it can change from run to run.

Request Pet Reason Acuity Booked
v-1Bella, a dog, owner Ada“overdue for annual checkup”ROUTINEdr-song at 09:00
v-2Milo, a cat, owner Ben“not eating, lethargic 2 days”URGENTdr-song at immediate
v-3Rocky, a dog, owner Cleo“hit by car”EMERGENCYdr-song at immediate
v-4Luna, a rabbit, owner Dov“routine vaccination booster”ROUTINEdr-ruiz at 09:30
mvn -q compile exec:java: the demo's output, 2026-11-04
petclinic-fleet: a clinic that runs itself by choreography

Nov 04, 2026 1:43:13 AM ai.badmonkey.agentspaces.agent.reduce.ReduceBinding start
INFO: slot-book: LEASED reduce of Triage into SlotBook on 'clinic', keyed by nothing (one accumulator), 0 key(s) pending
front desk logged 4 visit requests; the clinic takes it from here

== the day's charts ==
  Bella  dr-song   09:00     @ ROUTINE   [seen]
    dx: healthy on annual exam, slightly overweight
    rx: diet plan and dental cleaning, recheck in six months
  Milo   dr-song   immediate @ URGENT    [seen]
    dx: early gastrointestinal infection
    rx: subcutaneous fluids and antibiotics, recheck in 48h
  Rocky  dr-song   immediate @ EMERGENCY [seen]
    dx: stable after collision; no fractures on X-ray
    rx: overnight observation, pain management, recheck in 24h
  Luna   dr-ruiz   09:30     @ ROUTINE   [seen]
    dx: healthy; due vaccinations administered
    rx: booster given, no follow-up needed

Every pet was requested, triaged, scheduled, and seen with no
coordinator: the nurse watched for requests, the scheduler for
triage, the vets for their own appointments. The space carried
the work from one to the next.
✓ recorded verbatim from one run, with the log line the reduce binding prints; the diagnoses come from a canned table, and no model is involved
aspace://guide/petclinic-fleet/discipline · chapter 6

What the binder does for the author

The nurse's method is short because the binder carries the discipline that every choreography agent needs. A notify subscription delivers events at least once, on the fabric's thread, and a slow method on that thread would stall every other delivery. The binder gives the author three guarantees, and the method body states none of them.

  • Each entry reaches the method once. The binder keeps a set of entry ids per subscription, bounded at 4096 ids, and drops a delivery whose id it has seen. At-least-once delivery becomes once per bound agent.
  • The reaction runs off the delivery thread. Each delivery starts a virtual thread named after the class and method, so a slow method never holds up the fabric.
  • The binder writes the return value back. A non-null return becomes the next entry, which the binder writes to the result space (the watched space by default) under resultLease; null writes nothing.
THE FABRIC'S DELIVERY THREADA VIRTUAL THREAD OF ITS OWNspace.notify(template, listener, lease)an event: WRITTEN, a VisitRequest arrivedseen.add(entryId)one set per binding, bounded at 4096 idsan id already seen: the delivery is droppedinvoke(agent, method, entry)assess(request) runs heredispatch(result)the return value, written backnew idthe delivery thread is free again at onceWHAT dispatch(result) DOES WITH THE RETURN VALUEnullnothing is writtenan entrywritten with resultLeaseTaggedwritten with its tagsEntrieseach element in turnA renewal thread renews the subscription at half the lease while the agent stays bound: every two hours for the nurse's 4 h lease.
What the binder does for a @SpaceNotify method. The binder subscribes once, drops a delivery whose entry id it already handled, moves each reaction onto its own virtual thread so the fabric's delivery thread never waits for the method, and writes the return value back as the next entry. The method body contains none of it.
AgentBinder.java: the three guarantees
private Subscription subscribe(Object agent, Method method, SpaceNotify notify,
                               Class<?> entryType, Bound handle) {
    Space space = spaceFor(handle.identity, notify.space(), method);
    Space resultSpace = notify.resultSpace().isEmpty() ? space
            : spaceFor(handle.identity, notify.resultSpace(), method);
    Lease lease = Lease.of(Durations.parse(notify.lease()));
    Lease resultLease = Lease.of(Durations.parse(notify.resultLease()));
    // Delivery is at-least-once; the binder carries the choreography
    // discipline so the method body never has to: dedupe per entry id (watch),
    // then run the reaction on its own virtual thread so slow work never
    // holds the fabric's delivery thread, and write a non-null result back
    // as the next entry in the flow.
    String label = agent.getClass().getSimpleName() + "." + method.getName();
    Template<?> template = templateFor(entryType, notify.tags(), notify.where(), method);
    if (notify.on().length == 0) {
        throw new IllegalArgumentException("@SpaceNotify at " + method + " reacts to no event kind");
    }
    return watch(space, template, lease, handle, "space-notify", label, Set.of(notify.on()), spaceEvent ->
            Thread.ofVirtual().name("space-notify-" + label).start(() -> {
                try {
                    Object result = invoke(agent, method, spaceEvent.entry());
                    dispatch(result, null, resultSpace, resultLease, null, handle, method, label);
                } catch (RuntimeException e) {
                    LOG.log(System.Logger.Level.WARNING, label + ": notify failed", e);
                }
            }));
}
✓ from agentspaces-agent; the clinic's methods contain none of this

The same subscription, bound on two peers, runs twice: each peer has its own binder with its own set of seen ids. That is the right behavior for the vets, who both need to see each Appointment, and the wrong behavior for work that exactly one agent should do. A second nurse would write a second Triage for every request. Work that one agent must do goes through a take, which is why the scheduler uses @SpaceReduce and why the test can bind it twice.

@SpaceNotify: EVERY BOUND AGENT SEES THE ENTRY@SpaceReduce: ONE TAKER GETS THE ENTRYAppointmentdr-songaddressed to itVisitRecorddr-ruiznot addressednullTriageschedulerwins the claimbooks itscheduler-2loses the claimwaitsa guard in the method decides who actsthe claim race decides who acts
Who reacts: everyone, or one. A notify subscription reports each entry to every agent bound on every peer, so the two vets both see every Appointment and the field the scheduler wrote says whose it is. Work that exactly one agent should do goes through a take, which is why the schedulers use a reduce.

What to watch for

  • A subscription starts now. The binder registers it when the agent binds, and it sees entries that arrive afterward. An entry already in the agent's replica when the agent binds, such as a request written while the agent was down, never fires the method (chapter 9).
  • The set of seen ids lives in memory. A restarted agent starts with an empty set.
  • Reactions can overlap. Each delivery gets its own thread, so two requests that arrive together run concurrently and finish in either order. The clinic's methods are pure, so this costs nothing; an agent that shares state needs its own locking.
  • A method that throws loses that delivery. The binder logs a warning and writes nothing, and the id is already in the seen set, so it does not retry. A take handles failure differently: the lease lapses and the entry comes back.
Where the annotation is describedThe developer guide covers @SpaceNotify and the publish and subscribe table of the workflow guide maps the broker terms onto it. The javadoc is SpaceNotify.
aspace://guide/petclinic-fleet/book · chapter 7

The slot book: state in the space

The scheduler has the one job in the clinic that needs memory: whose turn it is for the next routine visit, and which half hour is next. The memory has to survive a restart, and in the test it has to be shared by two schedulers on two peers. So the book is not a field on the scheduler. It is a SlotBook entry in the clinic space, advanced once per triage by @SpaceReduce: a persistent accumulator whose state lives beside the entries it folds.

PetClinicFleet.java: the reduce annotation
@SpaceReduce(space = CLINIC, name = "slot-book", lease = "30s", accumulatorLease = "7d",
        produces = Appointment.class)
✓ step 3 of chapter 5 shows the whole method; book is null on the first step

The method takes the current book and one Triage, and returns an Entries fork of the new book and the Appointment. The binder treats the first element, the one of the accumulator type, as the new book and the rest as side outputs. It holds a ticket for the key while it folds. With no key on the annotation every Triage folds into one accumulator, which serializes all the clinic's bookings through one ticket.

SCHEDULER PEER: ReduceBinding.drainKey AND foldTHE CLINIC SPACE, AFTER THE STEP1take the key's ticketJoinTicket slot-book, take lease 30sticket (held), Triage, SlotBook a2take one Triageclaim, settle window, winticket (held), Triage (claimed), SlotBook a3read the current SlotBooknull on the very first stepunchanged4book(book, triage)returns Entries.of(next, Appointment)unchanged5complete the Triage with nextone atomic step; tags reduce, key, stepsSlotBook b, Triage gone6retire the previous SlotBookcancel it, or take and complete itSlotBook b only7write the Appointmentthe side output, lease 7dSlotBook b, Appointment8complete the ticketafter the drain folds every waiting Triageticket completed
One fold of the slot book. Per Triage the binder holds a ticket for the key, takes the element, runs the method with the current book, and completes the Triage with the new book in one step, so no Triage is folded twice. The binder writes the Appointment after the book, as the fork's side output. Both schedulers run the same steps; the ticket keeps them from folding at once.
ReduceBinding.java: taking the ticket and completing the step
if (!tickets.request(key)) {
    return;
}
Optional<TakenEntry<JoinTicket>> ticket = take(tickets.template(key));
if (ticket.isEmpty()) {
    return; // another reducer holds the key; its events or the sweep raise it again
}
✓ from agentspaces-agent; the element and the new book complete in one step

The step is atomic: completing the Triage with the new book is one operation, so one reducer never folds a Triage twice and the Triage is never completed without its new book. The binder writes the Appointment after that step, as the fork's side output.

THE SLOT BOOK: AN ENTRY IN THE SPACE, NOT A FIELD ON THE SCHEDULERstartno book yetfour pets2 urgent, 2 routineSlotBook(2, 2)scheduler restartsthe book stays in the spaceSlotBook(2, 2)Pip, a fifth petroutine: next slotSlotBook(3, 3)SlotBook(routineTurn, nextSlot): routineTurn picks the vet for the next routine visit; nextSlot counts the half hours takenslot labels09:0009:3010:0010:30next freeBella and Luna take 09:00 and 09:30 in either order; Pip takes 10:00
The slot book across a restart. Urgent and emergency visits go to the on-call vet at once and leave the book alone. Each routine visit takes the next half hour and moves the round-robin turn. Because the book is an entry, a restarted scheduler and a second scheduler on another peer book from the same book. The test asserts SlotBook(2, 2) after four pets, 10:00 for Pip, and SlotBook(3, 3) at the end.
PetClinicFleetTest.java: the book across a restart
// A scheduler restarts and a fifth routine visit lands: the book, not the
// scheduler's memory, says the next slot is 10:00.
firstScheduler.close();
subs.add(PetClinicFleet.runScheduler(scheduler));
frontDesk.clinic().write(new VisitRequest("v-5", "Pip", "Eve", "cat", "routine dental check"),
        Lease.of(Duration.ofHours(4)));
List<VisitRecord> five = awaitRecords(frontDesk, 5, Duration.ofSeconds(60));
assertThat(five).extracting(VisitRecord::petName).contains("Pip");
Appointment pip = frontDesk.clinic().readAll(Template.of(Appointment.class), 100).stream()
        .filter(a -> a.petName().equals("Pip")).findFirst().orElseThrow();
assertThat(pip.slot()).isEqualTo("10:00");
assertThat(Reductions.current(frontDesk.clinic(), SlotBook.class, "slot-book",
        Reductions.GLOBAL_KEY).orElseThrow().value()).isEqualTo(new SlotBook(3, 3));
✓ the test closes the first scheduler, binds a new one, and the next slot is 10:00
LEASED, the default modeIn the default LEASED mode a reduce takes its ticket through the space's claim race. Two reducers folding one key at once is therefore possible when a competing claim arrives late, which is the case chapter 8 explains. A fleet that needs exactly one reducer per key, fleet-wide, uses Mode.ORDERED, which sends the ticket and the takes through the ordered log. Pet Clinic stays on LEASED and a long settle window.
aspace://guide/petclinic-fleet/settle · chapter 8

The settle window

A LEASE_RACE take is a claim race. A taker writes a claim on the entry, publishes it to the group, and waits one settle window before it decides. After the window it keeps the entry only if its own claim is the lowest one it knows: the claim with the lowest (hlc, peerId) pair wins. The window exists so that a rival's claim has time to reach the taker before the taker decides.

A SHORT WINDOW, 150 MS: THE RIVAL CLAIM ARRIVES TOO LATE, TWO TAKERSscheduler Ascheduler BA claimsB claimsA waits 150 msB's claim, with the lower stamp, reaches AA's window closed first: A takes the entryB's claim is the lowest B knows: B takes it tooTHE CLINIC'S WINDOW, 500 MS: THE RIVAL CLAIM ARRIVES IN TIME, ONE TAKERscheduler Ascheduler BA claimsB claimsA waits 500 msB's claim, with the lower stamp, reaches AA sees the lower claim: A gives upB's claim is the lowest: B takes the entry oncepositions are schematic; the two window lengths are the values from the changelog and from the code
The settle window. A LEASE_RACE take writes a claim, waits one settle window, and then keeps the entry only if its own claim is the lowest it knows of. A rival claim that reaches the taker after the window leaves two takers who both believe they hold the entry. The window has to outlast the time a claim needs to cross the group.
ReplicatedSpace.java: the take
publishDelta(new SpaceWire.Delta(null, claimedId, sign(myClaim, actor)),
        "c:" + claimedId + ":" + myClaim.stamp().encoded());
sleep(settleWindow);
synchronized (lock) {
    TakeClaim winner = claimOf(claimedId);
    boolean won = winner != null && winner.holder().equals(holder)
            && winner.epoch() == myClaim.epoch() && !winner.expired(nowMillis());
    if (!won) {
        return Optional.empty(); // lost the race; retry elsewhere
    }
    takenEpochs.put(claimedId, myClaim.epoch());
}
✓ from agentspaces-space; sleep(settleWindow) is the whole price of the race

A rival claim that arrives after the window leaves two takers who both believe they hold the entry. The SPEC allows that (SPEC.md section 7.4: transient duplicate work remains possible), and it is what happened to this app's test. The changelog entry of 2026-11-02 records that PetClinicFleetTest was flaky at 0.5.0, passing one run in four. A diagnostic run showed one Triage folded by both schedulers, each writing an Appointment for it. The clinic space then waited 150 ms with six peers on one loaded machine. It now waits 500 ms, and eight runs in a row passed after the change.

PetClinicFleet.java: the clinic space
// The settle window is how long a take waits for a competing claim to arrive;
// it has to outlast the time a claim needs to reach the other peers. The
// library's default is 200 ms. Six peers on one loaded machine push a claim in
// well under 500 ms; at 150 ms the two schedulers sometimes both won the race
// for one triage and booked it twice.
ReplicatedSpace clinic = ReplicatedSpace.builder(runtime, CLINIC, identity, name)
        .settleWindow(Duration.ofMillis(500))
        .build();
✓ 500 ms in this app; the library's default is 200 ms

The library's own default is a fixed 200 ms. The builder and the Spring starter agree on it, and it does not follow the gossip period. The clinic overrides it: the code in the repository today waits 500 ms, and its comment says why. On 2026-11-04, three runs of the test passed against the build installed from the workspace, and three more against the 0.5.0 jars from Maven Central (chapter 10 has the output). The number is a trade. Every take waits the full window, so the scheduler, the only agent that takes, spends at least 500 ms per take; the nurse and the vets react without a claim and pay nothing. A longer window makes a late claim less likely, and it does not make one impossible.

What to watch for

  • Size the window for the slowest claim. The window has to outlast the time a claim needs to cross the group on a loaded machine. The test runs six peers in one JVM, which is why a window that suits a quiet fleet failed here.
  • The demo does not race. It binds one scheduler, so no rival claim exists. The test binds two to put the race under test.
  • Make the work under a take idempotent. The SPEC advises it for every LEASE_RACE workload, because the window narrows the duplicate case and cannot close it.
  • Use the ordered log when one is required. Mode.ORDERED on the reduce decides the ticket by log order, at the cost of a Raft quorum (chapter 7).
aspace://guide/petclinic-fleet/dies · chapter 9

When something stops

Three things can stop in the clinic, and the space handles each differently. The difference is the most useful thing to take from a choreography: work that a take holds comes back when its lease lapses, state that lives in an entry outlives the agent that wrote it, and a reaction that no agent was bound to receive is not repaired.

A SCHEDULER DIES, OR THE FOLD THROWS, MID-STEPTriage claimedtake lease 30sno completionthe Triage stayslease lapsesREAPPEAREDa scheduler takes itthe key is queued againby the design of ReduceBinding; this app's test does not kill a schedulerA SCHEDULER RESTARTSbinding closedfirstScheduler.close()SlotBook staysan entry, 7d leasenew bindingsweeps the spacePip books 10:00the book says 10:00asserted by PetClinicFleetTestTHE NURSE IS DOWN WHEN A REQUEST ARRIVESnurse not boundno subscriptionVisitRequest writtenlease 4 hnurse binds againits replica holds the requestno Triagenotify does not replaya nurse rebound on the same peer; @SpaceNotify delivers entries that arrive after the bind, and this app's test does not cover it
When something stops. Work that a take holds comes back when its lease lapses, and state that lives in an entry survives the agent that wrote it. A reaction that no one was bound to receive is the case the space does not repair on its own: a subscription delivers only the entries that arrive after it starts.

A scheduler dies or its fold throws

The reduce takes each Triage under a 30s lease. If the method throws, the binder logs it and stops that drain; if the peer dies, nothing completes the take. Either way the lease lapses, the Triage reappears, and a scheduler takes it again. The code is the same as for the happy path, because the crash path is the absence of a completion. This app's test does not kill a scheduler in the middle of a fold, so the behavior comes from the binder's design and its own tests.

ReduceBinding.java: a fold that throws
Object result;
try {
    result = step.apply(current.map(Space.Entry::value).orElse(null), element.entry());
} catch (RuntimeException | Error e) {
    LOG.log(System.Logger.Level.WARNING, config.name() + ": the fold threw for key '" + key
            + "'; the element's take lease will lapse", e);
    return false;
}
✓ the element's take lease lapses and the Triage returns

A scheduler restarts

The test closes the first scheduler's binding and binds a new one on the same peer. The slot book is an entry with a lease of 7 days, so it is still in the space. The new binding sweeps the space for waiting elements when it starts, reads the book, and books the fifth pet at 10:00. The test excerpt in chapter 7 shows it; its last assertion is the book itself, SlotBook(3, 3).

The nurse is down when a request arrives

This is the case the space does not repair. A @SpaceNotify subscription starts when the agent binds and delivers only the entries that arrive after it. A VisitRequest written while the nurse is down stays in the space for its 4 h lease. A nurse bound again on the same peer finds the request already in its replica, so no event fires and no Triage follows. A nurse that starts as a new process begins with an empty replica and sees the request fire only when a sync from another peer delivers it after the nurse has bound, a race the clinic does not rely on. A reduce differs: it sweeps the space when it starts, so a scheduler that binds late still folds a Triage that was already waiting. The workflow guide's publish and subscribe table says the same: the entry is the durable thing, and an agent that restarts reads the space.

If the clinic had to survive a nurse restartTwo changes would do it. The nurse could read the space for unanswered VisitRequest entries when it binds, or the request stage could be a @SpaceTake so that an unanswered request reappears for the next nurse. The first keeps the nurse a reaction; the second turns the stage into a worker.
aspace://guide/petclinic-fleet/running · chapter 10

Running and testing it

The app needs JDK 21 and Maven. It uses no model, no network service, and no API key: the diagnoses come from a canned table, and the peers talk over loopback TCP. The AgentSpaces 0.5.0 libraries resolve from Maven Central.

# in agentspaces-petclinic-fleet
mvn test           # the clinic as a flow test over real TCP
mvn -q exec:java   # the live demo: four pets, five peers, no orchestrator
./run-demo.sh      # the same demo, compiling first

The demo binds ports 7781 to 7785 on 127.0.0.1, so stop one run before you start another. The test asks the operating system for a free port per peer and has no such limit.

What the test asserts

PetClinicFleetTest is one test of 6 peers (front-desk, triage-nurse, scheduler, scheduler-2, dr-song, dr-ruiz) running 5 agents. It writes the four requests and a fifth after a scheduler restart, and it asserts the following, in order.

  • every pet reaches a chart with a diagnosis and a treatment, within 60 seconds;
  • the acuity on each appointment follows the reason: Rocky EMERGENCY, Milo URGENT, Bella and Luna ROUTINE;
  • no Triage is left in the space, so every one was taken and booked;
  • Rocky and Milo are booked with dr-song at immediate;
  • Bella and Luna are booked with the two different vets, at 09:00 and 09:30 in either order;
  • each chart names the vet its appointment named;
  • the slot book reads SlotBook(2, 2), awaited because the last fold reaches the front desk after the charts do;
  • after the first scheduler closes and a new one binds, a fifth pet, Pip, is booked at 10:00 and the book reads SlotBook(3, 3).
PetClinicFleetTest.java: the assertions
// The triage nurse assessed acuity from the reason for each visit; the
// appointment carries it, since the scheduler's reduce consumed the triage.
assertThat(appts.get("Rocky").acuity()).isEqualTo("EMERGENCY");
assertThat(appts.get("Milo").acuity()).isEqualTo("URGENT");
assertThat(appts.get("Bella").acuity()).isEqualTo("ROUTINE");
assertThat(appts.get("Luna").acuity()).isEqualTo("ROUTINE");
assertThat(frontDesk.clinic().readAll(Template.of(Triage.class), 100))
        .as("every triage was taken and booked").isEmpty();

// The emergency and the urgent case both went to the on-call vet, at once.
assertThat(appts.get("Rocky").vet()).isEqualTo(PetClinicFleet.ON_CALL);
assertThat(appts.get("Rocky").slot()).isEqualTo("immediate");
assertThat(appts.get("Milo").vet()).isEqualTo(PetClinicFleet.ON_CALL);
assertThat(appts.get("Milo").slot()).isEqualTo("immediate");
✓ 1 test, about 5 seconds
mvn test: recorded results, 2026-11-04
mvn test, build of 0.5.0 installed from the workspace (the default local repository):
  run 1: Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.840 s
  run 2: Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.340 s
  run 3: Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.312 s

mvn -Dmaven.repo.local=<empty directory> test, the 0.5.0 jars from Maven Central:
  run 1: Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.882 s
  run 2: Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 4.943 s
  run 3: Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.363 s
✓ the surefire summary line of each run, without the class name; three runs against each repository
If the test failsThe failure the changelog records at 0.5.0 was a duplicate booking from a late claim (chapter 8): two appointments for one pet. An IDE that compiles into target/ can also leave stale test classes; mvn clean test rebuilds them.
aspace://guide/petclinic-fleet/next

Where to go next

The codeThe app is agentspaces-petclinic-fleet in the example apps repository. The binder and the reduce this guide slices from are in agentspaces-agent, and the claim race is in agentspaces-space, both in the AgentSpaces repository.