Skip to content

About

A simple tuple space (shared memory) server used as the message board between collaborating agents

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

tuplespace

An in-memory tuple space, served over HTTP/JSON by one Rust binary.

Local processes need to hand work to each other, share small state, and block until something is ready. A tuple space makes all three the same pair of operations: put a typed tuple into a shared bag, claim one back out by pattern. A work queue, a mutex, a counter and a barrier are then all the same three calls with different tuples in them.

The primary client is bash and curl. That is a design constraint, not a concession: if a snippet here is awkward, the API is wrong.

  • In memory only. Nothing is written to disk. A restart is an empty space, deliberately.
  • No authentication. Anything that can reach the port is a full participant — it can claim, commit and delete any tuple. Bind it to 127.0.0.1.
  • Not a queue. No ordering, no fairness, no priority. Need order? Put it in the tuple.
  • Not a database. claim is the only read, and it takes. There is no way to browse.

Quick start

docker compose up --build     # or: cargo run --release

It takes no configuration, no volumes and no arguments; 9700 is the port.

TS=${TS:-http://localhost:9700}

# 1. Put a tuple. /put is not a lease op — no epoch, so no attach. A producer that
#    only ever puts never attaches at all.
curl -sS -X POST "$TS/put" -H 'X-Client-Id: producer' \
  -d '{"tuple":[10,"john smith",["my","name","is","what"]]}'
#=> {"tuple_id":1}

# 2. Attach as "worker-1". This mints the epoch that makes *this* process the live
#    instance of that client id, and hands back every lease it died holding.
EPOCH=$(curl -sS -X POST "$TS/attach" -d '{"client_id":"worker-1"}' | jq -r .epoch)

# 3. Claim a tuple matching (10, *, *): wait up to 5s for one, then hold it for 30s.
#    The tuple is out of the space now — nobody else can see it while we hold it.
claim=$(curl -sS -X POST "$TS/claim" \
  -H 'X-Client-Id: worker-1' -H "X-Client-Epoch: $EPOCH" \
  -d '{"pattern":[10,null,null],"wait_ms":5000,"hold_ms":30000}')
echo "$claim"
#=> {"lease_id":"L-1","tuple":[10,"john smith",["my","name","is","what"]],"expires_in_ms":30000}

# 4. Do the work, and commit last. The commit is what consumes the tuple: die before
#    it and the lease expires and somebody else does the job.
lease=$(jq -r .lease_id <<<"$claim")
curl -sS -X POST "$TS/commit" \
  -H 'X-Client-Id: worker-1' -H "X-Client-Epoch: $EPOCH" \
  -d "{\"lease_id\":\"$lease\"}"
#=> {}

That is the whole client. examples/worker.sh is the same five calls in a loop, and it is the file the acceptance tests run.


Four things script authors get wrong

1. 404 and 408 are not errors. They are what "nothing to do" looks like, and a polling worker sees far more of them than of 200. curl -f under set -e turns the first idle poll into an exit. Branch on the status instead:

res=$(curl -sS -X POST "$TS/claim" -H "X-Client-Id: $ME" -H "X-Client-Epoch: $EPOCH" \
      -w '\n%{http_code}' -d "$body")
code=$(tail -n1 <<<"$res"); body=$(sed '$d' <<<"$res")

2. 409 FENCED is terminal. It means another process has attached as your client id and is now the live instance of it. Retrying can only fence you again — one of you has to stop, and the one holding the stale epoch is you. Exit.

3. Waiting forever is wait_ms:null. It blocks until a tuple matches, the connection closes, or the server shuts down — there is no server-side ceiling on it. A waiter holds no tuple and no lease, so parking on one costs nothing.

The alternative is a finite wait_ms and a 408 loop, which is what you want when the worker has anything else to do between polls — a heartbeat, a metric, a check for a stop file:

while true; do ... case "$code" in 408|404) continue ;; esac; ... done

4. Commit last, after the work. The commit is the step that makes the work visible and the step that consumes the tuple. If the lease expired while you worked, the commit fails and the work is correctly discarded — see at-least-once below.


Tuples and patterns

A tuple is an ordered, fixed-length sequence of typed fields. A field is a scalar or a flat homogeneous list — never a nested tuple, never a list of lists.

Type JSON shorthand Long form
INT 10 — no ., e or E {"int":10}
FLOAT 3.5, 1e3, 10.0 {"float":10}
BOOL true, false {"bool":true}
STR "john smith" (UTF-8) {"str":"john smith"}
BYTES (none — always long form) {"bytes":"aGVsbG8="} (base64)
[]T ["my","name"] {"list":{"str":["my","name"]}}

The long form is required in exactly three cases: BYTES, an empty list (nothing to infer the element type from), and an integral FLOAT from a language that cannot emit 10.0. Responses come back in shorthand wherever that round-trips, so BYTES and empty lists always come back long.

10 and 10.0 are different tuples and neither matches the other. There is no null value (which is what frees null to mean wildcard).

A pattern is a fixed-length array of matchers, and its length is part of the match:

Matcher JSON Matches
literal 10, "john", ["a","b"] that exact value, of that exact type
any null any value of any type
typed any {"any":"int"}, {"any":"[]str"} any value of that one type

Type names are int float bool str bytes []int []float []bool []str []bytes; anything else is BAD_PATTERN.

(10, *, *)       ✓ (10,"john smith",["a","b"])   ✓ (10,3.5,true)
                 ✗ (10,"x")            arity     ✗ (10.0,"x","y")   INT ≠ FLOAT
(10, *:STR, *)   ✓ (10,"john smith",["a","b"])   ✗ (10,3.5,true)

Which matching tuple you get is unspecified, and may differ between two identical calls. So is which of several blocked claims is woken. A matching tuple can be passed over indefinitely; if you need order, encode it — claim ("job",1), then ("job",2).


The API

Base http://<host>:9700. Everything is POST with a flat JSON body except /health and /stats; there are no path parameters, so a script never assembles a URL and gets everything it needs from one flat jq path.

Endpoint Body Answer
POST /attach {"client_id":"worker-1"} {"client_id":…,"epoch":7,"leases":[{"lease_id":…,"tuple":…,"expires_in_ms":…}]}
POST /put {"tuple":[10,"john smith"]} {"tuple_id":5512}
POST /claim {"pattern":[10,null],"wait_ms":5000,"hold_ms":30000} {"lease_id":"L-2291","tuple":…,"expires_in_ms":30000}
POST /commit {"lease_id":"L-2291"} or {"lease_id":…,"replacement":["counter",6]} {} or {"tuple_id":5513}
POST /abort {"lease_id":"L-2291"} {}
POST /renew {"lease_id":"L-2291","hold_ms":30000} {"expires_in_ms":30000}
GET /health — {"status":"ok"}
GET /stats — counts only, see Stuck?
Header Required on Meaning
X-Client-Id everything but /health and /stats your stable client id, 1–128 chars, opaque
X-Client-Epoch the lease ops: claim, commit, abort, renew the epoch from your latest /attach

Both are also accepted as query parameters (?client_id=…&epoch=…); the headers win.

Errors are {"error":"CODE","message":"…"}. The code is authoritative; the message may change, so never match on prose.

HTTP Code Meaning
400 BAD_TUPLE untypeable, heterogeneous or malformed tuple
400 BAD_PATTERN malformed pattern, or an unknown wildcard type name
400 BAD_REQUEST missing field, unparseable body, bad client id
404 NOT_FOUND wait_ms:0 and nothing matched, or the path does not exist — normal
405 METHOD_NOT_ALLOWED wrong HTTP method for this endpoint; the allow header names the right one
408 TIMEOUT the wait elapsed and nothing matched — normal
409 FENCED a newer /attach for this client id has superseded you — terminal
410 LEASE_EXPIRED the deadline passed; the original tuple was restored
410 UNKNOWN_LEASE no such lease, or it belongs to another client
413 TOO_LARGE a limit was exceeded; the message names which
428 NOT_ATTACHED the request carried no epoch — call /attach and send it
503 UNAVAILABLE the space is full, or the server is shutting down — retry, on a new connection

/commit is the only operation that consumes a tuple permanently, and its replacement needs no relationship to the tuple you claimed — any values, any types, any arity. A shape-changing state transition is therefore one atomic call:

curl -sS -X POST "$TS/commit" -H "X-Client-Id: $ME" -H "X-Client-Epoch: $EPOCH" \
  -d '{"lease_id":"L-2291","replacement":["job",7,"running","worker-3"]}'

A commit rejected for BAD_TUPLE or TOO_LARGE still ends the lease: the server restores the original tuple exactly as /abort would, and returns the error. There is nothing to retry.

Every error a lease op can return means the lease is gone.


Crash recovery: client ids, epochs and /attach

A client id is an identity, not a label. Two processes sharing one id are the same client as far as the server is concerned, which is why /attach exists:

  • It returns every lease that id was holding, tuple and all. A worker SIGKILLed mid-task and restarted under the same id is handed its own unfinished work back. It can finish it if the work is resumable, or abort it and let the claim loop pick it up again — the server has no opinion.
  • It increments the epoch, and every lease op carries the epoch in X-Client-Epoch. An op arriving with an older epoch is FENCED before it has taken, committed or counted anything. So the restarted instance wins and the zombie loses.

One thing to know about the edge of this. The server keeps an epoch for an id only while that client holds a lease or has a request in flight — it runs no client directory. An epoch presented for an id it has forgotten is adopted rather than refused, which is what stops an idle worker's poll loop from having to re-attach on every pass. 428 NOT_ATTACHED therefore means your request carried no epoch, not that the server had none. Commit, abort and renew all name a lease, and a live lease keeps the state alive, so those stay fenced whenever fencing is what you need.

The consequence worth internalising: attaching fences your other instance. Do not attach "just in case", and do not let a library do it for you.

A client id that is stable across restarts is what makes recovery work. A per-process id (worker-$$) is right for a throwaway script and wrong for a named worker, whose whole reason for coming back is to reclaim what it was doing.


Choosing hold_ms

hold_ms is the hardest parameter in the API, and it is deliberately the client's: only the client knows how long its work takes. It must cover the worst case duration of the work, not the typical one.

Too short Too long
the lease expires mid-task; the tuple goes back to the space and someone else starts the same job; your commit is rejected a client that dies holding the tuple wedges it for the whole remaining hold — a 30s hold means up to 30s in which nobody can have that tuple

Neither failure is silent — a short hold shows up as a rising expiries in /stats, and a long one as work that visibly stalls after a crash — but the first costs duplicated work and the second costs latency, so the two errors are not symmetric. Prefer the side your workload can afford.

If the work cannot be bounded, take a short hold and POST /renew while it runs. Renewing sets a new deadline hold_ms from now, in both directions: it can shorten a lease as well as extend one. Nothing renews automatically, in any client here, on purpose — an auto-renewed lease held by a hung process is held forever, which is precisely the failure leases exist to end.


At-least-once delivery

A tuple can be delivered more than once. That is not a bug to be fixed in a later version, it is the only honest thing a lease can promise: when a worker goes silent, the server cannot tell a crash from slow work, and it has to choose between handing the tuple to somebody else and losing it forever.

The idiom that makes this safe is one line:

Do the work, and let COMMIT be the step that makes it visible.

Work whose only effect is a replacement tuple is safe automatically — if the lease expired while you worked, the commit is rejected, and the effect never happens. The harmful case is effects outside the space: sending an email, charging a card, appending to a file. Those can happen twice, because nothing about them is under the lease.

When you have such an effect, either make it idempotent (key it on something in the tuple), or put its outcome in the replacement tuple and have the next step be what acts on it — which turns an outside effect into an in-space one and moves it back under the lease.


Idioms

Want Do
work queue producers put ("job",…); workers claim ("job",null) → commit()
shared counter claim ("counter",{"any":"int"}) → commit ("counter",n+1)
barrier / signal wait: claim ("ready",null); signal: put ("ready",1)
mutex claim ("lock") to take, commit ("lock") to release
ordered processing encode the order — claim ("job",1), then ("job",2); the server has none

The counter is worth reading twice, because it is where the shape earns its keep. There is no increment operation and there does not need to be one: a claim removes the tuple, so between one client's claim and its commit no other client can see a counter tuple at all — theirs finds nothing and blocks. The read-modify-write is atomic for free, and the mutex, the queue and the state machine are all the same three calls.


Clients

Bash. No library ships, because a bash library wrapping four curl calls hides more than it saves. These files ship instead, each standalone and copy-pasteable, each run live by the test suite:

File What
examples/worker.sh the whole worker loop: attach, drain, claim, work, commit
examples/put.sh one tuple in, one curl
examples/claim-once.sh take one matching tuple and consume it
examples/counter.sh the atomic increment

The three snippets publish one exit-status contract, so a caller under set -e can tell an empty space from a broken server without parsing anything: 0 it did it, 1 there was nothing to do, 2 it failed (message on stderr).

Python. clients/python/tuplespace.py is one file, standard library only. There is no install step — copy it into your project.

from tuplespace import Client, ANY, NoTuple, Fenced

ts = Client("http://localhost:9700", client_id="worker-1")

for lease in ts.attach():          # anything we were holding when we died
    lease.abort()

ts.put(10, "john smith", ["my", "name", "is", "what"])   # types inferred

while True:
    try:
        with ts.claim(("job", ANY), wait=30_000, hold=60_000) as c:
            _, arg = c.tuple
            do_work(arg)
            c.commit()             # the tuple is gone only now
    except NoTuple:                # Timeout or NotFound — nothing to do, ask again
        continue
    except Fenced:                 # another instance owns this client id: stop
        raise

It never retries, never renews, never attaches on your behalf, and never commits for you — leaving the with block without calling commit aborts, and an exception aborts and then propagates untouched. Timeout and NotFound do not inherit TupleSpaceError, so the idle poll every worker runs all day cannot swallow a real failure.


Configuration

Environment variables only. No config file, no flags beyond --version and --help, and every setting defaulted — it runs with none of them set.

Variable Default Meaning
TUPLESPACE_ADDR 0.0.0.0:9700 listen address
TUPLESPACE_MAX_HOLD_MS 300000 cap on hold_ms; over → TOO_LARGE
TUPLESPACE_MAX_TUPLES 100000 capacity, checked on /put only; over → UNAVAILABLE
TUPLESPACE_MAX_TUPLE_BYTES 65536 encoded size of one tuple
TUPLESPACE_MAX_FIELDS 32 fields per tuple
TUPLESPACE_MAX_LIST_LEN 4096 elements in one list field
TUPLESPACE_LOG info tracing filter directive
TUPLESPACE_LOG_FORMAT text text or json

An invalid value fails at startup, naming the variable. There is no silent fallback to a default, because that is discovered much later and much more expensively.

The cap on a raw request body is derived from TUPLESPACE_MAX_TUPLE_BYTES — four times it plus 4 KiB — rather than set separately. A request carries at most one tuple or pattern, so the only thing worth saying about its size is that it is comfortably above the largest tuple this server takes; the multiplier is room for a client that pretty-prints, since the tuple limit is measured on the compact form. A body past the cap is 413 TOO_LARGE naming it, like any other limit. Raise TUPLESPACE_MAX_TUPLE_BYTES and this moves with it: that is the point of deriving it, since a fixed cap would refuse tuples you had explicitly allowed.

Shutting down

SIGTERM and SIGINT (so docker stop, and Ctrl-C) shut the server down in under two seconds. Every blocked /claim is answered 503 UNAVAILABLE first, so a worker parked on a long wait_ms — or on wait_ms:null, which has no end of its own — learns immediately rather than hanging against a socket that will never answer — treat UNAVAILABLE from /claim as "reconnect and claim again", not as an error.

Outstanding leases are not waited for: a lease may legitimately be held for minutes, and a shutdown that waits for one is a shutdown that hangs. Nothing is flushed anywhere, because there is nowhere to flush it to — the tuples in the space and the tuples out on leases go with the process. One line on the way out says how many of each that was:

shutting down: released 2 blocked claim(s); discarding 41 tuple(s) and 3 lease(s) — storage is
in memory and nothing here survives the exit

Work lost that way is work a client can redo, provided the client kept it: a producer that has not seen a /commit should be prepared to /put again. That is the same at-least-once rule that applies to an expired lease, and the same reason handlers must be idempotent.

The shipped docker-compose.yml publishes to 127.0.0.1 deliberately. There is no authentication: anything that can reach the port can claim, commit and delete any tuple in the space. Publish it more widely only on a network you would grant that to.


Stuck?

GET /stats answers "is anything stuck", and it is counts only — the client API cannot browse the space, and an operator endpoint that leaked one tuple would become a client feature by accident.

{"tuples":41,"leases":3,"waiters":2,"clients":5,"uptime_s":8123,
 "puts":9912,"claims":9871,"commits":9840,"aborts":12,"expiries":19}
Field Counts
tuples tuples in the space now. A tuple out on a lease is in nobody's space and is not counted here
leases leases whose deadline has not passed
waiters /claim requests blocked right now, waiting for a match
clients clients the server is holding state for: one with a live lease, or one blocked in /claim. Not connected clients — see below
uptime_s seconds since this process started serving
puts claims commits aborts expiries lifetime totals since startup, of the operations that succeeded. A /put refused at capacity is not a put; a /claim that timed out is not a claim

clients is the field to read carefully. There is no such thing as a connected client here: nothing is held open between requests, and the server keeps state for a client only while it has a live lease or a blocked claim. So a fleet of twenty workers polling an idle space reads clients: 0 between polls, and that is healthy. Read it as "how many workers are mid-something", never as "how many are up" — and if you need the second number, your process supervisor has it and this server never will.

Symptom Means
waiters > 0, tuples == 0 everyone is waiting and nobody is producing — normal when idle
leases climbing, never falling workers are claiming and not committing; check holds against how long the work really takes
expiries rising holds are too short — raise hold_ms, or use /renew
clients == 0 while workers are running normal: they are between polls, holding no lease and no blocked claim
repeated fenced in the log two processes are sharing one client id; give them distinct ids
a claim returns nothing but you can see the tuple check the arity and the types: (10,null) does not match (10,"x","y"), and 10 does not match 10.0

/stats is also the one handler that does not sweep expired leases first, so leases and expiries are an honest observation of whether the reaper is running rather than of your read.

What the log says

One line per state-changing op, on stdout. The operation is the first word and everything after it is name=value, so grep is enough to follow one tuple or one worker through:

 INFO tuplespaced::http: put: tuple accepted client="worker-1" tuple=5512 arity=3
 INFO tuplespaced::http: claim: tuple leased client="worker-2" lease=L-2291 tuple=5512 hold_ms=30000
 INFO tuplespaced::http: commit: tuple consumed client="worker-2" lease=L-2291 tuple=5512 replaced=5513
 WARN tuplespaced::http: expire: hold elapsed, tuple restored client="worker-2" epoch=3 lease=L-2291 tuple=5512 held_ms=30004
 WARN tuplespaced::http: fenced: a later instance holds this client id client="worker-1" epoch=6 current=7 op=commit

expire and fenced are the only two WARNs, and both mean something went wrong on a client rather than in the server: a worker that stopped without releasing its tuple, and a worker that has been superseded by a later /attach of its own id.

TUPLESPACE_LOG=debug adds the pattern each /claim scanned for — which is how "this worker gets nothing" becomes "this worker is asking for something nobody puts". Tuple contents are logged at TRACE and nowhere above it, because the space carries your data and logs end up in issue reports. TUPLESPACE_LOG_FORMAT=json writes the same fields as one JSON object per line.


Development

cargo build
cargo test        # unit, HTTP end-to-end, the bash examples, and the Python client

The test suite runs the shipped scripts and the shipped Python client as files, against a real server — a broken example is a broken product. Nothing beyond cargo test is required, and the tests that want more skip when they cannot run, printing a SKIPPED line past the test harness's output capture so an ordinary cargo test shows it. What each missing tool costs:

Tool Without it
bash, curl, jq the shipped examples and the README quick start are not run
shellcheck the shipped examples are not linted
python3 the Python client's own suite is not run
docker, git the image is not built from a clean checkout, and the cold start is not tested
ldd the server binary's runtime dependencies are not read off it

A run that has all of them says so, and a skip becomes a failure:

TUPLESPACE_TEST_REQUIRE_ALL=1 cargo test          # every tool above is expected
TUPLESPACE_TEST_REQUIRE_DOCKER=1 cargo test       # only the daemon is

That is what stops a CI image quietly losing a package and going green having tested nothing. tests/prerequisites.rs keeps both halves honest: it fails if a harness starts running a program this table does not list, and it runs a skipping test as a child process to check the skip is still visible and still fatal under TUPLESPACE_TEST_REQUIRE_ALL.

Where What
src/ the server: value and pattern are pure, space is the store, http is the surface
tests/api.rs the HTTP surface end to end
tests/scripts.rs examples/*.sh, run live, plus shellcheck
tests/python.rs the Python client's own suite, run against a live server
tests/readme.rs the quick start above, run live
tests/docker.rs the shipped image, built from a clean checkout and started with nothing supplied
tests/packaging.rs the Dockerfile and compose rules that can be checked without a daemon
tests/stress.rs 10 producers and 10 consumers over 10,000 tuples, each consumed exactly once
tests/prerequisites.rs the suite's own setup: what it shells out to, and that a skip is loud
PRDs/ what is being built and why; PRDs/index.md first
docs/00-api-interface.md the settled design the PRDs implement
IMPLEMENTATION_PLAN.md what is done, what is next, and every open question

Licence

MIT — see LICENSE. Copyright (c) 2026 Helix Venture Studio Pty Ltd Trading as Helix Collective.

The Python client and the shipped examples/*.sh are covered by it too, which is what makes "copy it into your project" an instruction anyone can actually follow.

About

A simple tuple space (shared memory) server used as the message board between collaborating agents

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages