; Extension — exactly-once append under retries.

(persist-test
  "seen? false before first append"
  (persist/seen? (persist/open) "orders" "cmd-1")
  false)
(persist-test
  "append-once appends on first use"
  (let
    ((b (persist/open)))
    (begin
      (persist/append-once b "orders" "cmd-1" "placed" 0 {})
      (persist/count b "orders")))
  1)
(persist-test
  "seen? true after first append"
  (let
    ((b (persist/open)))
    (begin
      (persist/append-once b "orders" "cmd-1" "placed" 0 {})
      (persist/seen? b "orders" "cmd-1")))
  true)
(persist-test
  "repeat with same key does not append again"
  (let
    ((b (persist/open)))
    (begin
      (persist/append-once b "orders" "cmd-1" "placed" 0 {})
      (persist/append-once b "orders" "cmd-1" "placed" 0 {})
      (persist/append-once b "orders" "cmd-1" "placed" 0 {})
      (persist/count b "orders")))
  1)
(persist-test
  "repeat returns the same event (same seq)"
  (let
    ((b (persist/open)))
    (let
      ((e1 (persist/append-once b "orders" "cmd-1" "placed" 0 {})))
      (persist/event-seq
        (persist/append-once b "orders" "cmd-1" "placed" 0 {}))))
  1)
(persist-test
  "different keys append separately"
  (let
    ((b (persist/open)))
    (begin
      (persist/append-once b "orders" "cmd-1" "placed" 0 {})
      (persist/append-once b "orders" "cmd-2" "placed" 0 {})
      (persist/count b "orders")))
  2)
(persist-test
  "idempotency is per-stream"
  (let
    ((b (persist/open)))
    (begin
      (persist/append-once b "a" "cmd-1" "x" 0 {})
      (persist/append-once b "b" "cmd-1" "x" 0 {})
      (list (persist/count b "a") (persist/count b "b"))))
  (list 1 1))
(persist-test
  "stored data is preserved on first append"
  (let
    ((b (persist/open)))
    (get
      (persist/event-data
        (persist/append-once b "s" "k" "x" 0 {:n 9}))
      :n))
  9)
(persist-test
  "idempotency survives restart on the durable backend"
  (let
    ((disk (persist/mem-backend)))
    (begin
      (persist/append-once
        (persist/mock-durable disk)
        "orders"
        "cmd-1"
        "placed"
        0
        {})
      (let
        ((db2 (persist/mock-durable disk)))
        (begin
          (persist/append-once
            db2
            "orders"
            "cmd-1"
            "placed"
            0
            {})
          (persist/count db2 "orders")))))
  1)
