Skip to content

Introduce queue/v1: message queue over immutable edge tables - #437

Merged
em3s merged 21 commits into
mainfrom
feat/issue-428-queue-v1
Jul 21, 2026
Merged

em3s merged 21 commits into
mainfrom
feat/issue-428-queue-v1

Conversation

@em3s

@em3s em3s commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

queue/v1 is a message queue that also serves as a refresh / delay queue. It is an engine capability: the runtime (enqueue / poll) lives in engine (com.kakao.actionbase.engine.queue) over the immutable edge table, with a thin server/ HTTP layer and queue DDL (create / enable / disable / delete) over the v3 table API.

A queue is an ImmutableEdge table: source = partition, target = id (server-assigned ULID), a LONG seq property indexed ASC for per-partition order, and an opaque value (any JSON). Enqueue is a lock-free append; poll is a per-partition range scan over seq with a forward offset cursor and an optional until upper bound (refresh / delay).

Message = { key, seq, value }; endpoints under /queue/v1/namespaces/{ns}/queues. Full design — data model, and how every endpoint lowers to a v3 edge scan / table DDL — is in the design comment below.

Scoped to admin + enqueue + poll. Eviction / retention is a TBD follow-up — a background scan-and-delete sweep over the ImmutableEdge (which forbids in-place update, not deletion) — tracked separately.

Closes #428

Changes

  • engine (com.kakao.actionbase.engine.queue) — QueueService (enqueue / poll), PartitionHasher, QueueDescriptorCodec, QueueSchema, and the runtime payloads. Enqueue appends via MutationService.mutate INSERT with lock=false and assigns the ULID id; poll is a single-partition seq-index scan (seq:gt:offset for a log, seq:bt:offset+1,until for refresh). Wired as a bean in GraphConfiguration.
  • server (api/queue/v1) — MessageController (enqueue / poll) delegating to the engine; api/queue/v1/metadata/QueueController + QueueMetadataService build / inspect / toggle / delete the backing table over V3CompatService, with delete guarded (409 unless inactive).

No changes to the core immutable-edge binding — the queue reuses it as-is.

How to Test

  • ./gradlew :engine:test --tests "com.kakao.actionbase.engine.queue.*" — PartitionHasher, descriptor codec.
  • ./gradlew :server:test --tests "*queue.v1.*" — E2E (admin lifecycle incl. enable / disable / delete-guard, enqueue with ULID id, poll order / pagination / until).
  • ./gradlew :engine:spotlessCheck :server:spotlessCheck.

AI Assistance

  • This PR was written largely with AI assistance.
    • Tool / model: claude code (opus 4.8)

Empty commit to open the PR for queue/v1 over immutable edge tables (#428).
Scope: enqueue + poll only; eviction is a separate follow-up.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. enhancement New feature or request labels Jul 20, 2026
em3s and others added 5 commits July 20, 2026 23:18
Sharding, partition hashing, and forward-only poll cursor for queue/v1
over immutable edge tables (#428).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Store queue metadata (partitionCount, orderBy) in the backing immutable
edge table comment behind a `queue/v1` marker (#428).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
QueueAdminService builds an ImmutableEdge table via V3CompatService with a
LONG partition source, STRING message-id target, and an indexed LONG orderBy.
Validates orderBy/property names against v2 reserved fields. Delete deactivates
then removes. Lifecycle E2E included (#428).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
QueueService.enqueue appends messages as INSERTs with lock=false (an append
has no read-modify-write conflict), routing each message to a partition via
PartitionHasher and reporting per-message status. E2E included (#428).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
QueueService.poll fans out a per-partition index scan across a shard's
partitions, merges by orderBy, and returns a forward-only cursor. limit is
per-partition; ordering is guaranteed within a partition. E2E covers order,
cursor pagination, and shard split (#428).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XS This PR changes 0-9 lines, ignoring generated files. labels Jul 20, 2026
em3s and others added 6 commits July 20, 2026 23:37
The cursor now records the last-consumed orderBy per partition and resumes
each scan with `orderBy:gt:position`, instead of opaque per-page scan offsets.
Previously a drained partition dropped out of the cursor and was re-read from
the start on the next poll. Carry every prior position forward so drained
partitions yield nothing until higher-ordered messages arrive. Requires
orderBy to be unique per partition (a monotonic sequence). (#428)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…l limit

Add /queue/v1 to ReadOnlyRequestFilter's guarded prefixes so queue writes
(create/enqueue/delete) are rejected in read-only mode like graph writes, and
classify the queue endpoints in ReadOnlyRequestFilterTest's exhaustiveness
registry (the full build's endpoint scan required this). Also bound poll
`limit` to 1..1000 to cap per-partition fan-out work. (#428)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Instead of injecting a separate LONG orderBy field, orderBy now names one of
the caller-declared properties (validated: present, LONG, non-nullable) and is
indexed for order. Enqueue carries the order value inside the message payload,
and poll returns the full declared properties intact (orderBy is also surfaced
as a convenience projection). This drops the "magic field" and mirrors how
ImmutableEdge's index + range predicate actually work. (#428)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add QueueExpireTableE2ETest modeling the top-k _expire table: partition =
hash(table|topk|entity) % 2310, id = table|topk|entity|expiredAt, and expiredAt
as the orderBy so entries poll in due order (oldest expiry first). Drives the
QueueAdminService/QueueService beans directly (no HTTP) to show another
controller's workflow can control a queue programmatically. (#428, #386)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
30 = 2·3·5 (divisors 1,2,3,5,6,10,15,30) keeps shard=k/N splits balanced while
keeping single-shard poll fan-out cheap; 480 was needlessly high for the poll
scan-per-partition cost. (#428)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ify partitionCount to 30

Rewrite QueueExpireTableE2ETest to exercise create -> enqueue -> poll over HTTP
(expiredAt as orderBy, due-first poll), and add a second angle where a workflow
enqueues through the QueueService bean and the entries are polled back over HTTP
(proving another controller's workflow can drive the queue). Unify sample
partition counts to 30 to match the new default. (#428, #386)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@em3s

em3s commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor Author

queue/v1 — finalized design

A queue is an ImmutableEdge table. The runtime (enqueue / poll) is an engine package (com.kakao.actionbase.engine.queue) that reuses the immutable-edge binding unchanged; the server/ side is a thin HTTP layer plus queue DDL over the v3 table API. Runtime calls lower to the edge scan / mutation, admin calls to the table DDL. Message = { key, seq, value }; id is a server-assigned ULID.

Data model — queue ↔ immutable edge table

queue immutable edge table
namespace database
queue table (ImmutableEdge)
partition = floorMod(xxHash32(key), partitions) source (LONG)
message id (ULID) target (STRING) — unique per partition
seq (order / refresh due time) property seq (LONG) + single ASC index
value (any JSON) property value (STRING, JSON blob)
partitions (config) table comment — queue/v1 {"partitions":N} marker

Immutable specifics: no State row (a write persists index records only — the ASC seq index is the log); read() → initial, so enqueue is a lock-free append; point get is unsupported, so the only read path is a scan.

API — every endpoint lowers to a v3 call

queue endpoint lowers to (v3)
POST .../queues POST /graph/v3/databases/{ns}/tables (TableCreateRequest)
GET .../queues/{queue} GET /graph/v3/…/tables/{queue}
PUT .../queues/{queue}/enable · /disable PUT /graph/v3/…/tables/{queue} — { "active": true / false }
DELETE .../queues/{queue} GET (active guard, 409 if active) + DELETE /graph/v3/…/tables/{queue}
POST .../queues/{queue}/messages edge INSERT via MutationService.mutate (append, no lock)
GET .../queues/{queue}/partitions/{partition}/poll GET /graph/v3/…/tables/{queue}/edges/scan/seq

Enqueue — { key, seq, value } → edge INSERT

enqueue field edge
key floorMod(xxHash32(key), partitions) = source; not stored
(server) ULID.random() target (id)
seq property seq (= edge version)
value (any JSON) property value (JSON string)

Response: { accepted, results: [{ partition, id, status }] }, where id is the assigned ULID.

Poll — request → edge scan

GET .../partitions/7/poll?limit=100&offset=1730000000000&until=1730000009999
# lowers to
GET /graph/v3/databases/mydb/tables/events/edges/scan/seq?start=7&direction=OUT&limit=100&ranges=seq:bt:1730000000001,1730000009999
# without `until` -> ranges=seq:gt:1730000000000
poll param edge scan note
partition start source
(fixed) direction=OUT
limit limit
offset ranges=seq:gt:offset (or bt lower offset+1) exclusive lower bound — a range predicate, not the scan's own offset
until ranges=seq:bt:…,until inclusive upper; refresh passes now, so not-yet-due rows are never returned
index seq .../scan/seq the ASC index
— offset (opaque token) unused — the queue resumes by seq value

Poll — response ← edge scan

edge scan (DataFrameEdgePayload) poll transform
edges[].source messages[].partition Long → Int
edges[].target messages[].id ULID
edges[].properties.seq messages[].seq as-is
edges[].properties.value messages[].value JSON → parsed (any)
offset (opaque String) offset (LONG) replaced with max(seq)
hasNext hasNext pass-through
version / count / total / context (dropped) total unsupported on immutable

offset is the same field in and out (like the edge scan) and is retained when a partition drains, so later appends / newly-due rows are picked up on the next poll. Consumers shard by owning a subset of 0 .. partitions-1; the server does no cross-partition fan-out or merge.

Create — body → TableCreateRequest

queue create TableCreateRequest
queue table
storage storage
partitions comment — queue/v1 {"partitions":N}
(fixed) schema — ImmutableEdge (seq LONG + ASC index, value STRING)
(fixed) mode — SYNC

Get — TableDescriptor → queue metadata

TableDescriptor queue metadata
database namespace
table queue
comment marker partitions (decoded)
storage storage
active / schema / indexes (hidden)

Invariants

invariant why
id = ULID (80-bit entropy) per-partition target uniqueness → no collision loss
seq is a monotonic client-supplied ordering key (timestamp / LSN / sequence) the LSM-backed seq index scans in order, so per-partition delivery is sorted — the queue's contract; strict uniqueness is not required
seq index is ASC oldest → newest replay (WAL/CDC and refresh order)

Follow-up

rename databases → namespaces, partitionCount → partitions; drop orderBy config and user properties; enqueue { key, seq, value } + ULID id; poll per-partition offset / until → gt / bt; lifecycle PUT /enable · /disable + delete active-guard; remove Shard and QueueCursor.

Out of scope / TBD follow-up: eviction / retention via a background scan-and-delete sweep over the ImmutableEdge (append-only writes, but deletion is allowed — only in-place update is not).

A queue is an engine capability over the immutable edge table, so the
runtime (enqueue/poll) moves into com.kakao.actionbase.engine.queue
(QueueService, PartitionHasher, QueueDescriptorCodec, QueueSchema,
payloads), wired as a bean in GraphConfiguration. The server keeps a
thin HTTP layer (MessageController) and queue DDL under
api/queue/v1/metadata (QueueController + QueueMetadataService).

Finalize the API:
- paths use namespaces/{ns} and partitions (was databases/partitionCount)
- message = {key, seq, value}; id is a server-assigned ULID; value is an
  opaque any-JSON blob (seq and value are fixed system fields)
- poll is per-partition with offset (seq:gt) plus optional until (seq:bt)
  for refresh/delay queues; response carries offset + hasNext
- lifecycle: PUT enable/disable, delete guarded (409 unless inactive)
- remove Shard and QueueCursor

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 21, 2026
em3s and others added 2 commits July 21, 2026 11:17
Rename QueueAdminE2ETest to QueueLifecycleE2ETest and scrub the
remaining "admin" strings (namespace, storage, QueueSchema doc) now that
the DDL surface lives in api/queue/v1/metadata.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
… add partitions endpoint

Runtime partition-count reads (enqueue routing, poll range check) now use
Graph's in-memory label registry via getLabel — refreshed by the periodic
metastore reload — instead of a fresh metastore read per request. No extra
caching layer. A queue not yet picked up by a reload is simply not visible
yet (E2E warms the registry with Graph.updateLabels after create).

Add GET /queue/v1/namespaces/{ns}/queues/{queue}/partitions returning the
partition count from the same in-memory source, for consumers that fan a
poll loop across 0..partitions-1.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 21, 2026
em3s and others added 2 commits July 21, 2026 11:43
Cache the decoded partition count keyed by (namespace, queue) so enqueue
routing and the poll range check neither read the metastore nor re-parse
the comment marker on every request. Expire-after-write (1 min), not
-access, bounds staleness so a re-partitioned queue (the size can change)
is picked up within ~1 minute; a cache miss reads Graph's in-memory
registry and decodes the marker.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Cut verbose KDoc down to one-line docs where they earn their place, and
collapse QueueSchema.SEQ_FIELD/SEQ_INDEX into a single SEQ (the index is
named after the field it indexes); VALUE_FIELD -> VALUE.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 21, 2026
Add Bean Validation to QueueCreateRequest — @notblank + name/storage
@pattern (Constants.Name) and @min(1) on partitions — wired via @validated
+ @Valid on the DDL controller, which also runs path names through
V3NameValidator (mirroring TableController). Drop the now-redundant
partitions require in the service.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jul 21, 2026
@em3s

em3s commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Scope & fit

queue/v1 is a durable, partitioned, append-only log over the immutable edge table, with a due-time filter for refresh / delay use. It is a log primitive, not a full message broker — so it fits some use cases cleanly and not others.

What works end-to-end

  • create / get / enable / disable / delete a queue; discover the partition count
  • enqueue a batch (append, server-assigned ULID id); per-partition poll in seq order with a forward offset cursor
  • replay from any offset, or from the beginning (today nothing is trimmed; once the eviction follow-up lands, replay is bounded by the retention window — see below)
  • until filter → poll only messages due by a given time (refresh / delay)
  • consumers shard by owning a subset of partitions (client-side)

Fit by use case

Use case Verdict Main blockers
Refresh / delay scheduler 🟢 works (ops follow-up) can't cancel/modify a scheduled entry; fired entries accumulate (no eviction)
WAL/CDC / Kafka log 🟡 partial no retention/compaction (unbounded growth); no consumer-group offset commit; no streaming / long-poll
General work queue (ack-based) 🔴 no no ack / visibility-timeout / redelivery / dead-letter

Key gaps

  • Eviction / retention — "append-only" here means the write path only ever appends (enqueue never updates or randomly inserts); it does not mean entries are permanent. ImmutableEdge forbids in-place update, not deletion, so old entries can be trimmed by a background scan-and-delete sweep — a TBD follow-up, out of scope for this PR. Until it lands there is no retention, so the log grows unbounded (Actionbase has no table-level TTL today; only the storage backend's applies).
  • Server-side offset / ack — consumers hold their own offset; there is no consumer group, and no ack / redelivery.
  • Also: per-partition ordering only (no cross-partition order), no dedup, no partition-count change after creation, and a create-to-visible delay (~1 min, until the metastore reload).

Refresh / delay is the best current fit. WAL/CDC becomes practical once retention (the eviction follow-up) lands; it is not a drop-in Kafka replacement. It is not an ack-based work queue.

…at once

createQueue now forces graph.updateLabels() after the DDL create, so the
runtime (which reads partition metadata from Graph's in-memory registry via
getLabel) sees the new queue immediately — instead of failing until the next
metastore reload, which may be long or disabled (e.g. a plain local
ServerApplication run). Drops the manual updateLabels warm-up the E2E tests
needed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@em3s

em3s commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor Author

queue/v1 interactive end-to-end demo.

# go run queue_v1_demo.go
queue_v1_demo.go
//	BASE=http://localhost:8080 NS=demo_ns Q=events go run queue_v1_demo.go
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"regexp"
	"strings"
	"time"
)

const (
	b, d, r                      = "\033[1m", "\033[2m", "\033[0m"
	red, grn, yel, blu, mag, cyn = "\033[31m", "\033[32m", "\033[33m", "\033[34m", "\033[35m", "\033[36m"
)

var (
	base  = env("BASE", "http://localhost:8080")
	ns    = env("NS", "demo_ns")
	q     = env("Q", "events")
	stdin = bufio.NewReader(os.Stdin)
	keyRe = regexp.MustCompile(`"([^"\\]+)":`)
	step  = 0
)

func env(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}

func pause() {
	fmt.Printf("\n%s   ↵ Enter to send (Ctrl-C to quit)%s", d, r)
	stdin.ReadString('\n')
}

func hr() { fmt.Printf("%s%s%s\n", d, strings.Repeat("─", 62), r) }

// colorJSON indents and tints object keys.
func colorJSON(raw []byte) string {
	var buf bytes.Buffer
	if json.Indent(&buf, raw, "", "  ") != nil {
		return string(raw)
	}
	return keyRe.ReplaceAllString(buf.String(), yel+`"$1"`+r+":")
}

func doReq(method, path, body string) (int, []byte) {
	var rdr io.Reader
	if body != "" {
		rdr = strings.NewReader(body)
	}
	req, _ := http.NewRequest(method, base+path, rdr)
	if body != "" {
		req.Header.Set("Content-Type", "application/json")
	}
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		fmt.Printf("\n%srequest failed: %v%s\n", red, err, r)
		os.Exit(1)
	}
	defer resp.Body.Close()
	data, _ := io.ReadAll(resp.Body)
	return resp.StatusCode, data
}

// stripTrace drops the (huge) stack trace Spring adds to error bodies.
func stripTrace(body []byte) []byte {
	var m map[string]any
	if json.Unmarshal(body, &m) != nil {
		return body
	}
	if _, ok := m["trace"]; !ok {
		return body
	}
	m["trace"] = "(stack trace omitted)"
	if out, err := json.Marshal(m); err == nil {
		return out
	}
	return body
}

func showRes(code int, body []byte) {
	sc := grn
	if code >= 400 {
		sc = red
	}
	fmt.Printf("%s← HTTP %s%d%s\n", b, sc, code, r)
	body = stripTrace(body)
	if len(bytes.TrimSpace(body)) > 0 {
		fmt.Println(colorJSON(body))
	}
}

// call = header + request + pause + send + response; returns the parsed body.
func call(title, desc, method, path, body string) map[string]any {
	step++
	fmt.Println()
	hr()
	fmt.Printf("%s%s[%d] %s%s\n%s%s%s\n", b, mag, step, title, r, d, desc, r)
	fmt.Printf("\n%s%s%s %s%s%s\n", b+cyn, method, r, blu, base+path, r)
	if body != "" {
		fmt.Printf("%srequest:%s\n%s\n", d, r, colorJSON([]byte(body)))
	}
	pause()
	code, data := doReq(method, path, body)
	showRes(code, data)
	var m map[string]any
	json.Unmarshal(data, &m)
	return m
}

func partitionOf(m map[string]any) int {
	if res, ok := m["results"].([]any); ok && len(res) > 0 {
		if first, ok := res[0].(map[string]any); ok {
			if p, ok := first["partition"].(float64); ok {
				return int(p)
			}
		}
	}
	return 0
}

func offsetOf(m map[string]any) string {
	if v, ok := m["offset"].(float64); ok {
		return fmt.Sprintf("%.0f", v)
	}
	return ""
}

func main() {
	fmt.Printf("%s%squeue/v1 — interactive end-to-end demo%s\n", b, mag, r)
	fmt.Printf("%sbase=%s  namespace=%s  queue=%s%s\n", d, base, ns, q, r)
	fmt.Printf("%sEach step prints the request; press Enter to send it and see the response.%s\n", d, r)

	qpath := "/queue/v1/namespaces/" + ns + "/queues/" + q
	storage := fmt.Sprintf("datastore://%s/%s", ns, q)

	call("Create the namespace", "A queue namespace is a v3 database.",
		"POST", "/graph/v3/databases",
		fmt.Sprintf(`{"database":%q,"comment":"queue demo"}`, ns))

	call("Create the queue", "No schema to declare — seq (order), value (opaque body) and the ULID id are system fields.",
		"POST", "/queue/v1/namespaces/"+ns+"/queues",
		fmt.Sprintf(`{"queue":%q,"storage":%q,"partitions":8}`, q, storage))

	call("Inspect the queue", "Create forces a metadata sync, so the queue is usable immediately.",
		"GET", qpath, "")

	call("Get the partition count", "Consumers use this to fan a poll loop across 0..partitions-1.",
		"GET", qpath+"/partitions", "")

	now := time.Now().UnixMilli()
	enq := fmt.Sprintf(`{"messages":[
  {"key":"user-1","seq":%d,"value":{"body":"a"}},
  {"key":"user-1","seq":%d,"value":"just-a-string"},
  {"key":"user-1","seq":%d,"value":[1,2,3]}
]}`, now-3000, now-2000, now-1000)
	er := call("Enqueue a batch", "key routes to a partition (hash), seq orders it, value is any JSON; the server assigns each ULID id. Same key → same partition.",
		"POST", qpath+"/messages", enq)
	part := partitionOf(er)
	poll := fmt.Sprintf("%s/partitions/%d/poll", qpath, part)
	fmt.Printf("\n%s→ landed in partition %s%d%s%s; polling it next.%s\n", d, b, part, r, d, r)

	pr := call("Poll the partition", "One partition, seq ascending. 'offset' comes back as the forward cursor.",
		"GET", poll+"?limit=10", "")
	off := offsetOf(pr)

	call("Poll again from the cursor", "offset="+off+" resumes strictly after it — the partition is now drained (empty page).",
		"GET", poll+"?limit=10&offset="+off, "")

	now = time.Now().UnixMilli()
	enq2 := fmt.Sprintf(`{"messages":[
  {"key":"user-1","seq":%d,"value":{"note":"due now"}},
  {"key":"user-1","seq":%d,"value":{"note":"due in 1h"}}
]}`, now-500, now+3600000)
	call("Enqueue a 'due now' and a 'due later' message", "seq doubles as a due-time (epoch ms): one just passed, one is an hour out.",
		"POST", qpath+"/messages", enq2)

	call("Poll only what's due (refresh queue)", fmt.Sprintf("until=%d bounds the poll — the future message is withheld, so a scheduler never fires early.", now),
		"GET", fmt.Sprintf("%s?limit=10&offset=%s&until=%d", poll, off, now), "")

	call("Try to delete while active (guarded)", "Delete is refused with 409 until the queue is disabled.",
		"DELETE", qpath, "")
	call("Disable the queue", "PUT .../disable flips the active flag (idempotent).",
		"PUT", qpath+"/disable", "")
	call("Delete the queue", "Now that it is inactive, delete succeeds (204).",
		"DELETE", qpath, "")

	fmt.Println()
	hr()
	fmt.Printf("%s%sdone.%s\n", b, grn, r)
}
output
queue/v1 — interactive end-to-end demo
base=http://localhost:8080  namespace=demo_ns  queue=events
Each step prints the request; press Enter to send it and see the response.

──────────────────────────────────────────────────────────────
[1] Create the namespace
A queue namespace is a v3 database.

POST http://localhost:8080/graph/v3/databases
request:
{
  "database": "demo_ns",
  "comment": "queue demo"
}

   ↵ Enter to send (Ctrl-C to quit)

← HTTP 200
{
  "tenant": "local",
  "database": "demo_ns",
  "active": true,
  "comment": "queue demo",
  "revision": -1,
  "createdAt": -1,
  "createdBy": "",
  "updatedAt": -1,
  "updatedBy": ""
}

──────────────────────────────────────────────────────────────
[2] Create the queue
No schema to declare — seq (order), value (opaque body) and the ULID id are system fields.

POST http://localhost:8080/queue/v1/namespaces/demo_ns/queues
request:
{
  "queue": "events",
  "storage": "datastore://demo_ns/events",
  "partitions": 8
}

   ↵ Enter to send (Ctrl-C to quit)← HTTP 200
{
  "namespace": "demo_ns",
  "queue": "events",
  "partitions": 8,
  "storage": "datastore://demo_ns/events"
}

──────────────────────────────────────────────────────────────
[3] Inspect the queue
Create forces a metadata sync, so the queue is usable immediately.

GET http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 200
{
  "namespace": "demo_ns",
  "queue": "events",
  "partitions": 8,
  "storage": "datastore://demo_ns/events"
}

──────────────────────────────────────────────────────────────
[4] Get the partition count
Consumers use this to fan a poll loop across 0..partitions-1.

GET http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events/partitions

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 200
{
  "namespace": "demo_ns",
  "queue": "events",
  "partitions": 8
}

──────────────────────────────────────────────────────────────
[5] Enqueue a batch
key routes to a partition (hash), seq orders it, value is any JSON; the server assigns each ULID id. Same key → same partition.

POST http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events/messages
request:
{
  "messages": [
    {
      "key": "user-1",
      "seq": 1784610977019,
      "value": {
        "body": "a"
      }
    },
    {
      "key": "user-1",
      "seq": 1784610978019,
      "value": "just-a-string"
    },
    {
      "key": "user-1",
      "seq": 1784610979019,
      "value": [
        1,
        2,
        3
      ]
    }
  ]
}

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 200
{
  "accepted": 3,
  "results": [
    {
      "partition": 5,
      "id": "01KY1HN09QJ2A8TS55A3A7Q7FJ",
      "status": "CREATED"
    },
    {
      "partition": 5,
      "id": "01KY1HN09QG0N8827C7GK61AVD",
      "status": "CREATED"
    },
    {
      "partition": 5,
      "id": "01KY1HN09QN0Y6HE8JKFM12PE3",
      "status": "CREATED"
    }
  ]
}

→ landed in partition 5; polling it next.

──────────────────────────────────────────────────────────────
[6] Poll the partition
One partition, seq ascending. 'offset' comes back as the forward cursor.

GET http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events/partitions/5/poll?limit=10

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 200
{
  "messages": [
    {
      "partition": 5,
      "id": "01KY1HN09QJ2A8TS55A3A7Q7FJ",
      "seq": 1784610977019,
      "value": {
        "body": "a"
      }
    },
    {
      "partition": 5,
      "id": "01KY1HN09QG0N8827C7GK61AVD",
      "seq": 1784610978019,
      "value": "just-a-string"
    },
    {
      "partition": 5,
      "id": "01KY1HN09QN0Y6HE8JKFM12PE3",
      "seq": 1784610979019,
      "value": [
        1,
        2,
        3
      ]
    }
  ],
  "offset": 1784610979019,
  "hasNext": false
}

──────────────────────────────────────────────────────────────
[7] Poll again from the cursor
offset=1784610979019 resumes strictly after it — the partition is now drained (empty page).

GET http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events/partitions/5/poll?limit=10&offset=1784610979019

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 200
{
  "messages": [],
  "offset": 1784610979019,
  "hasNext": false
}

──────────────────────────────────────────────────────────────
[8] Enqueue a 'due now' and a 'due later' message
seq doubles as a due-time (epoch ms): one just passed, one is an hour out.

POST http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events/messages
request:
{
  "messages": [
    {
      "key": "user-1",
      "seq": 1784610979934,
      "value": {
        "note": "due now"
      }
    },
    {
      "key": "user-1",
      "seq": 1784614580434,
      "value": {
        "note": "due in 1h"
      }
    }
  ]
}

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 200
{
  "accepted": 2,
  "results": [
    {
      "partition": 5,
      "id": "01KY1HN0PZV805GMZ2SRTQ4PMQ",
      "status": "CREATED"
    },
    {
      "partition": 5,
      "id": "01KY1HN0PZMYWJ40F47N8C6CCA",
      "status": "CREATED"
    }
  ]
}

──────────────────────────────────────────────────────────────
[9] Poll only what's due (refresh queue)
until=1784610980434 bounds the poll — the future message is withheld, so a scheduler never fires early.

GET http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events/partitions/5/poll?limit=10&offset=1784610979019&until=1784610980434

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 200
{
  "messages": [
    {
      "partition": 5,
      "id": "01KY1HN0PZMYWJ40F47N8C6CCA",
      "seq": 1784610979934,
      "value": {
        "note": "due now"
      }
    }
  ],
  "offset": 1784610979934,
  "hasNext": false
}

──────────────────────────────────────────────────────────────
[10] Try to delete while active (guarded)
Delete is refused with 409 until the queue is disabled.

DELETE http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 409
{
  "error": "Conflict",
  "message": "queue `demo_ns.events` must be disabled before deletion",
  "path": "/queue/v1/namespaces/demo_ns/queues/events",
  "requestId": "dce3d24c-10",
  "status": 409,
  "timestamp": "2026-07-21T05:16:20.864+00:00",
  "trace": "(stack trace omitted)"
}

──────────────────────────────────────────────────────────────
[11] Disable the queue
PUT .../disable flips the active flag (idempotent).

PUT http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events/disable

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 200
{
  "namespace": "demo_ns",
  "queue": "events",
  "partitions": 8,
  "storage": "datastore://demo_ns/events"
}

──────────────────────────────────────────────────────────────
[12] Delete the queue
Now that it is inactive, delete succeeds (204).

DELETE http://localhost:8080/queue/v1/namespaces/demo_ns/queues/events

   ↵ Enter to send (Ctrl-C to quit)
← HTTP 204

──────────────────────────────────────────────────────────────
done.

- Consistent naming: internal code uses `numPartitions` (Spark-style) while
  the HTTP/DTO surface keeps `partitions`. Completes the rename across the
  poll lambda, the cache (numPartitionsCache / NUM_PARTITIONS_CACHE_SIZE),
  PartitionHasher, and tests.
- Harden the poll seq read: `as? Number ?: error(...)` instead of a hard
  `as Number` cast, so a malformed/non-queue edge fails with a clear message
  rather than an NPE/ClassCastException.
- Trim a WHAT-style comment.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@em3s

em3s commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor Author

Demoed offline w/ @zipdoki and @eazyhozy and looks good. Optimistic merge.

The queue-config concept was named three ways (QueueMeta, QueueDescriptorCodec,
QueueMetadataService). Standardize on "Metadata" for the config/DDL concept and
reserve "Descriptor" for the API response DTO (matching core TableDescriptor):

- QueueMeta -> QueueMetadata
- QueueDescriptorCodec -> QueueMetadataCodec (name now matches the type it codecs)
- files/tests renamed accordingly
- QueueDescriptorResponse, QueueMetadataService, and the metadata package unchanged

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@em3s em3s changed the title Introduce queue/v1 (enqueue + poll): Kafka-style log over immutable edge tables Introduce queue/v1: Kafka-style log over immutable edge tables Jul 21, 2026
@em3s em3s changed the title Introduce queue/v1: Kafka-style log over immutable edge tables Introduce queue/v1 (enqueue + poll): message queue over immutable edge tables Jul 21, 2026
@em3s em3s changed the title Introduce queue/v1 (enqueue + poll): message queue over immutable edge tables Introduce queue/v1: message queue over immutable edge tables Jul 21, 2026
@em3s
em3s merged commit ece9852 into main Jul 21, 2026
2 checks passed
@em3s
em3s deleted the feat/issue-428-queue-v1 branch July 21, 2026 08:25
@em3s em3s self-assigned this Jul 21, 2026
@em3s em3s mentioned this pull request Jul 21, 2026
1 task done
@em3s em3s mentioned this pull request Aug 6, 2026
1 task done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Introduce queue/v1: message queue over immutable edge tables

1 participant