{
  "ok": true,
  "tool": "api_why",
  "artifactClass": "why-run",
  "schemaVersion": "why-run-1.0",
  "sources": {
    "hash": "fdc86e3d8d5d6b6f214c8fc92a10727e6b460e1713166c236471e14f12cc6572",
    "files": [
      {
        "name": "forum",
        "sha256": "f4bf2fbf2fc30be48047a6f45900cf7537d0aae5999e488c49eaf39bd5740d0b",
        "content": "package Demo/Forum\n\n# A messaging forum on the Yichus service framework: profiles (owner\n# scoped), threads with a visibility rule, posts with an edit rule, a\n# moderator roster, and a per-thread reply cap. Written as the demo in\n# docs/forum-demo/. The profiles table is proven OwnerScoped; threads\n# and posts are proven Guarded: every write of them and every use of\n# their rows sits under a branch on `can_see` or `can_edit` applied to\n# the caller, and the access findings name which. The moderator roster\n# is proven Guarded by `is_moderator`: the first caller seats itself with\n# an insert, which never replaces a roster, and every later write sits\n# under `is_moderator` applied to the caller and the roster it changes.\n\nfrom Yichus/IO import IO, flat_map, pure\nfrom Yichus/Access import Principal, AccessRule, AccessSpec, OwnerScoped, Guarded, keep_visible\nfrom Yichus/Data import Db, Table, table, db_read, db_read_opt, db_write, db_query, db_next_id\nfrom Yichus/Json import (\n  Json, JsonBool, JsonNumber, JsonString, JsonArray, JsonObject, render_json, Rendered, RenderError\n)\nfrom Yichus/Service import (\n  Response, handler, route, service_def, ReadPerm, WritePerm, CreatePerm, QueryPerm\n)\nfrom Yichus/Transaction import TxTable, Txn, Outcome as TxOutcome, Committed, Aborted, RetryExhausted, CommitUnknown, stored_table, tx_pure, tx_bind, tx_abort, tx_read, tx_next_id, tx_insert, tx_write, transaction\nfrom Yichus/Systems import SystemSpec, SystemBinding, Postgres, Serializable\nfrom Yichus/Organize import FamilySpec, ReadingOrder, ReadingStep\n\nexport (\n  forum_api,\n  access_rules,\n  forum_systems,\n  forum_tables,\n  forum_shape,\n  forum_reading,\n  Profile(),\n  Visibility(),\n  Thread(),\n  Post(),\n  Posts(),\n  PutProfileRequest(),\n  OpenThreadRequest(),\n  ReadThreadRequest(),\n  ReplyRequest(),\n  EditPostRequest(),\n  GrantModeratorRequest(),\n  Issue(),\n  Outcome(),\n  can_see,\n  can_edit,\n  thread_request_issues,\n  posts_table,\n  put_profile,\n  get_profile,\n  grant_moderator,\n  open_thread,\n  list_threads,\n  read_thread,\n  post_reply,\n  edit_post,\n)\nexposes (Yichus/Access, Yichus/Data, Yichus/IO, Yichus/Organize, Yichus/Service, Yichus/Systems)\n\n# ---------------------------------------------------------------------------\n# Small total combinators shared by every layer below.\n# ---------------------------------------------------------------------------\n\ndef int_lt(a: Int, b: Int) -> Bool:\n  match cmp_Int(a, b):\n    case LT: True\n    case _: False\n\ndef int_gt(a: Int, b: Int) -> Bool:\n  match cmp_Int(a, b):\n    case GT: True\n    case _: False\n\ndef is_blank(s: String) -> Bool:\n  eq_String(s, \"\")\n\ndef member_String(items: List[String], target: String) -> Bool:\n  loop items:\n    case []: False\n    case [head, *tail]:\n      if eq_String(head, target): True\n      else: member_String(tail, target)\n\n# ---------------------------------------------------------------------------\n# JSON values: every response body is a Yichus/Json value, and\n# render_json writes it with each string escaped, so stored text may hold\n# any character JSON can carry.\n# ---------------------------------------------------------------------------\n\ndef jint(value: Int) -> Json:\n  JsonNumber(int_to_String(value))\n\ndef jstrings(items: List[String]) -> Json:\n  JsonArray(map_List(items, JsonString))\n\n# ---------------------------------------------------------------------------\n# Validation kit: issues, checks, the Outcome accumulator.\n# ---------------------------------------------------------------------------\n\nstruct Issue(field: String, code: String, hint: String)\n\nenum Outcome[a]:\n  Failure(issues: List[Issue])\n  Success(value: a)\n\ndef flag_if(cond: Bool, field: String, code: String, hint: String) -> List[Issue]:\n  if cond: [Issue(field, code, hint)]\n  else: []\n\ndef merge_issues(batches: List[List[Issue]]) -> List[Issue]:\n  flat_map_List(batches, batch -> batch)\n\ndef check_blank(field: String, value: String) -> List[Issue]:\n  flag_if(is_blank(value), field, \"required\", \"value must not be empty\")\n\ndef check_max_len(field: String, value: String, limit: Int) -> List[Issue]:\n  flag_if(int_gt(length_String(value), limit), field, \"too_long\",\n    concat_String([\"at most \", int_to_String(limit), \" characters\"]))\n\ndef check_text(field: String, value: String, limit: Int) -> List[Issue]:\n  merge_issues([\n    check_blank(field, value),\n    check_max_len(field, value, limit),\n  ])\n\ndef outcome_of[a](issues: List[Issue], value: a) -> Outcome[a]:\n  match issues:\n    case []: Success(value)\n    case _: Failure(issues)\n\n# ---------------------------------------------------------------------------\n# Response envelopes shared by every handler. `forbid` and `not_found`\n# are the runtime rules the access analyzer cannot prove: they carry no\n# row data, so a caller the rule turns away learns only that it was.\n# ---------------------------------------------------------------------------\n\ndef render_issue(issue: Issue) -> Json:\n  Issue(field, code, hint) = issue\n  JsonObject([(\"field\", JsonString(field)), (\"code\", JsonString(code)), (\"hint\", JsonString(hint))])\n\n# A response: one JSON object naming its view, then its fields.\n# render_json refuses only text JSON cannot carry (malformed Unicode) or\n# a value past its work bound; that answers 500, never a broken body.\ndef answer(status: Int, view: String, fields: List[(String, Json)]) -> Response:\n  match render_json(JsonObject([(\"view\", JsonString(view)), *fields])):\n    case Rendered(text): Response(status, text)\n    case RenderError(_):\n      Response(500, \"{\\\"view\\\":\\\"unrenderable\\\",\\\"message\\\":\\\"The answer held text JSON cannot carry.\\\"}\")\n\ndef respond(view: String, fields: List[(String, Json)]) -> Response:\n  answer(200, view, fields)\n\ndef reject(issues: List[Issue]) -> Response:\n  answer(422, \"rejected\", [\n    (\"issue_count\", jint(length_List(issues))),\n    (\"issues\", JsonArray(map_List(issues, render_issue))),\n  ])\n\ndef forbid(rule: String, message: String) -> Response:\n  answer(403, \"forbidden\", [(\"rule\", JsonString(rule)), (\"message\", JsonString(message))])\n\ndef not_found(what: String) -> Response:\n  answer(404, \"not_found\", [(\"what\", JsonString(what))])\n\n# ---------------------------------------------------------------------------\n# Domain records.\n# ---------------------------------------------------------------------------\n\nstruct Profile(user_id: String, display_name: String)\n\n# Who may read a thread: everyone, or its author, its members and the\n# moderators.\nenum Visibility:\n  Open\n  Members\n\nstruct Thread(\n  id: String,\n  title: String,\n  author: String,\n  visibility: Visibility,\n  members: List[String],\n  reply_cap: Int\n)\n\nstruct Post(id: String, thread_id: String, author: String, body: String, edited: Bool)\n\n# A thread's posts, with the version every save raises. An edit names the\n# version its caller read and is refused when the posts were saved since,\n# so of two edits made from one reading the second is refused, not lost.\nstruct Posts(version: Int, items: List[Post])\n\ndef render_visibility(v: Visibility) -> String:\n  match v:\n    case Open: \"open\"\n    case Members: \"members\"\n\ndef render_profile(profile: Profile) -> Json:\n  Profile(user_id, display_name) = profile\n  JsonObject([(\"user_id\", JsonString(user_id)), (\"display_name\", JsonString(display_name))])\n\ndef render_thread(thread: Thread) -> Json:\n  Thread(id, title, author, visibility, members, reply_cap) = thread\n  JsonObject([\n    (\"id\", JsonString(id)),\n    (\"title\", JsonString(title)),\n    (\"author\", JsonString(author)),\n    (\"visibility\", JsonString(render_visibility(visibility))),\n    (\"members\", jstrings(members)),\n    (\"reply_cap\", jint(reply_cap)),\n  ])\n\ndef render_post(post: Post) -> Json:\n  Post(id, thread_id, author, body, edited) = post\n  JsonObject([\n    (\"id\", JsonString(id)),\n    (\"thread_id\", JsonString(thread_id)),\n    (\"author\", JsonString(author)),\n    (\"body\", JsonString(body)),\n    (\"edited\", JsonBool(edited)),\n  ])\n\n# ---------------------------------------------------------------------------\n# The rules. Pure, so `why` can show them and a law can pin them.\n# ---------------------------------------------------------------------------\n\ndef is_moderator(roster: List[String], uid: String) -> Bool:\n  member_String(roster, uid)\n\n# The visibility rule: an Open thread is readable by every caller; a\n# Members thread by its author, its members and the moderators.\ndef can_see(uid: String, roster: List[String], thread: Thread) -> Bool:\n  Thread(_, _, author, visibility, members, _) = thread\n  match visibility:\n    case Open: True\n    case Members:\n      or(eq_String(author, uid), or(member_String(members, uid), is_moderator(roster, uid)))\n\n# The edit rule: a post is edited by its author or by a moderator.\ndef can_edit(uid: String, roster: List[String], post: Post) -> Bool:\n  Post(_, _, author, _, _) = post\n  or(eq_String(author, uid), is_moderator(roster, uid))\n\n# The reply cap: a thread admits a reply while its replies number fewer\n# than its cap.\ndef has_room(thread: Thread, replies: List[Post]) -> Bool:\n  Thread(_, _, _, _, _, reply_cap) = thread\n  int_lt(length_List(replies), reply_cap)\n\ndef post_id_is(post: Post, target: String) -> Bool:\n  Post(id, _, _, _, _) = post\n  eq_String(id, target)\n\ndef replace_post(posts: List[Post], edited: Post) -> List[Post]:\n  Post(target, _, _, _, _) = edited\n  map_List(posts, post -> (\n    if post_id_is(post, target): edited\n    else: post))\n\ndef find_post(posts: List[Post], target: String) -> Option[Post]:\n  loop posts:\n    case []: None\n    case [head, *tail]:\n      if post_id_is(head, target): Some(head)\n      else: find_post(tail, target)\n\n# ---------------------------------------------------------------------------\n# Storage layout. `profiles` is one record per caller keyed by\n# Principal.user_id (proven OwnerScoped). `threads` is one record per\n# thread id, `posts` the list of a thread's posts under the thread id;\n# both are Guarded: a write is a create (keyed by the table's own fresh\n# id) or sits under `can_see` / `can_edit` applied to the caller, and a\n# row read reaches nothing but such a branch, a guard, a match, or\n# `keep_visible`. The moderator roster is one row, Guarded by\n# `is_moderator`: it is created by an insert and changed only under that\n# guard. Record tables are read with `db_read_opt`, so a missing thread\n# is `None`, never a wrong-typed record.\n# ---------------------------------------------------------------------------\n\naccess_rules = AccessSpec([\n  AccessRule(\"profiles\", OwnerScoped),\n  AccessRule(\"threads\", Guarded([\"can_see\"])),\n  AccessRule(\"posts\", Guarded([\"can_see\", \"can_edit\"])),\n  AccessRule(\"moderators\", Guarded([\"is_moderator\"])),\n])\n\n# The eventual backing store, declared for the flow lens: a claim about\n# the deployment, not a connection (the engine's store is configured at\n# boot; see docs/forum-demo/).\nforum_systems = SystemSpec([\n  SystemBinding(\"threads\", Postgres(\"forum\", Serializable)),\n  SystemBinding(\"posts\", Postgres(\"forum\", Serializable)),\n  SystemBinding(\"profiles\", Postgres(\"forum\", Serializable)),\n  SystemBinding(\"moderators\", Postgres(\"forum\", Serializable)),\n])\n\n# The shape the forum declares about itself, checked by the organize\n# pages: the four tables are one family and the eight handlers are\n# written the same way (the conventions page names any member that\n# diverges and any inferred member the declaration omits), and a reader learns the blocks in this\n# order (the stack page names any step listed before a block it is\n# built from). Every caption is authored, never measured.\nforum_tables = FamilySpec(\"tables\", [\n  \"profiles_table\", \"threads_table\", \"posts_table\", \"moderators_table\",\n])\n\nforum_shape = FamilySpec(\"handlers\", [\n  \"get_profile\", \"put_profile\", \"grant_moderator\", \"open_thread\",\n  \"list_threads\", \"read_thread\", \"post_reply\", \"edit_post\",\n])\n\nforum_reading = ReadingOrder([\n  ReadingStep(\"jint\", \"an Int as a JSON number\"),\n  ReadingStep(\"jstrings\", \"a list of strings as a JSON array\"),\n  ReadingStep(\"answer\", \"a response: a JSON object naming its view, rendered with every string escaped\"),\n  ReadingStep(\"threads_table\", \"the threads table handle, one Thread per id\"),\n  ReadingStep(\"posts_table\", \"the posts table handle: per thread id, its posts and the version every save raises\"),\n  ReadingStep(\"moderators_table\", \"the moderator roster table, one list of user ids\"),\n  ReadingStep(\"profiles_table\", \"the profiles table handle, one Profile per user id\"),\n  ReadingStep(\"is_moderator\", \"whether a user id is on the roster\"),\n  ReadingStep(\"can_see\", \"the visibility rule: who may read a thread, by its visibility and members\"),\n  ReadingStep(\"can_edit\", \"the edit rule: the author or a moderator\"),\n  ReadingStep(\"respond\", \"a 200 response with a named view and its JSON fields\"),\n  ReadingStep(\"forbid\", \"a 403 response naming the rule that refused\"),\n  ReadingStep(\"not_found\", \"a 404 response naming what was missing\"),\n  ReadingStep(\"flag_if\", \"one validation issue when a condition holds\"),\n  ReadingStep(\"check_text\", \"the text validation every request body and title goes through\"),\n  ReadingStep(\"reject\", \"a 422 response carrying the validation issues\"),\n  ReadingStep(\"render_thread\", \"a thread as JSON\"),\n  ReadingStep(\"render_post\", \"a post as JSON\"),\n  ReadingStep(\"has_room\", \"whether a thread is under its reply cap\"),\n  ReadingStep(\"get_profile\", \"the caller reads their own profile\"),\n  ReadingStep(\"put_profile\", \"the caller writes their own profile after validation\"),\n  ReadingStep(\"grant_plan\", \"in one transaction: the first caller seats itself with an insert, then only a moderator adds a user\"),\n  ReadingStep(\"grant_outcome\", \"the grant plan run as one transaction\"),\n  ReadingStep(\"grant_moderator\", \"the grant's outcome as a response; a busy or unconfirmed grant asks to be sent again\"),\n  ReadingStep(\"list_threads\", \"the threads the caller may see\"),\n  ReadingStep(\"read_thread\", \"one thread and its posts, if the caller may see it\"),\n  ReadingStep(\"post_reply\", \"a reply under the visibility rule and the reply cap\"),\n  ReadingStep(\"edit_post\", \"an edit under the visibility rule and the edit rule\"),\n  ReadingStep(\"thread_request_issues\", \"the validation issues of an open-thread request\"),\n  ReadingStep(\"parse_thread\", \"a validated open-thread request as a Thread, or its issues\"),\n  ReadingStep(\"open_thread\", \"a new thread from a validated request\"),\n  ReadingStep(\"forum_api\", \"the service: eight routes, each a handler with its permissions\"),\n])\n\ndef profiles_table(db: Db) -> Table[Profile]:\n  table(db, \"profiles\")\n\ndef threads_table(db: Db) -> Table[Thread]:\n  table(db, \"threads\")\n\ndef posts_table(db: Db) -> Table[Posts]:\n  table(db, \"posts\")\n\nposts_rows: TxTable[s, Posts] = stored_table(\"posts\")\n\nthread_rows: TxTable[s, Thread] = stored_table(\"threads\")\n\ndef moderators_table(db: Db) -> Table[List[String]]:\n  table(db, \"moderators\")\n\nroster_rows: TxTable[s, List[String]] = stored_table(\"moderators\")\n\nroster_key = \"roster\"\n\n# ---------------------------------------------------------------------------\n# Requests.\n# ---------------------------------------------------------------------------\n\nstruct PutProfileRequest(display_name: String)\nstruct OpenThreadRequest(title: String, members_only: Bool, members: List[String], reply_cap: Int)\nstruct ReadThreadRequest(thread_id: String)\nstruct ReplyRequest(thread_id: String, body: String)\nstruct EditPostRequest(thread_id: String, post_id: String, body: String, version: Int)\nstruct GrantModeratorRequest(user_id: String)\n\ndef visibility_of(members_only: Bool) -> Visibility:\n  match members_only:\n    case True: Members\n    case False: Open\n\n# The validation of a thread request, on its own so a declared model\n# (forum.spec.bosatsu) can share it with the handler.\ndef thread_request_issues(req: OpenThreadRequest) -> List[Issue]:\n  OpenThreadRequest(title, _, members, reply_cap) = req\n  merge_issues([\n    check_text(\"title\", title, 80),\n    flag_if(int_lt(reply_cap, 0), \"reply_cap\", \"negative\", \"a cap is zero or more replies\"),\n    flat_map_List(members, member -> check_text(\"members\", member, 40)),\n  ])\n\ndef parse_thread(uid: String, fresh_id: String, req: OpenThreadRequest) -> Outcome[Thread]:\n  OpenThreadRequest(title, members_only, members, reply_cap) = req\n  outcome_of(thread_request_issues(req),\n    Thread(fresh_id, title, uid, visibility_of(members_only), members, reply_cap))\n\n# ---------------------------------------------------------------------------\n# Handlers: (Db, Principal, request) -> IO[Response]. The engine injects\n# Db and Principal; nothing here constructs a Principal.\n# ---------------------------------------------------------------------------\n\ndef put_profile(db: Db, p: Principal, req: PutProfileRequest) -> IO[Response]:\n  Principal(uid, _) = p\n  PutProfileRequest(display_name) = req\n  match check_text(\"display_name\", display_name, 40):\n    case []:\n      stored <- flat_map(db_write(profiles_table(db), uid, Profile(uid, display_name)))\n      pure(respond(\"profile\", [(\"profiles\", JsonArray([render_profile(stored)]))]))\n    case issues: pure(reject(issues))\n\ndef get_profile(db: Db, p: Principal) -> IO[Response]:\n  Principal(uid, _) = p\n  row <- flat_map(db_read_opt(profiles_table(db), uid))\n  profiles = match row:\n    case None: []\n    case Some(profile): [profile]\n  pure(respond(\"profile\", [(\"profiles\", JsonArray(map_List(profiles, render_profile)))]))\n\n# The first caller of an empty roster seats itself; after that only a\n# moderator grants. Seating is an insert, so two first callers cannot\n# both replace the roster: one transaction seats, the other retries and\n# finds a roster. A roster only grows, so a stored one is never empty.\ndef grant_plan[s](p: Principal, target: String) -> Txn[s, Response, List[String]]:\n  Principal(uid, _) = p\n  found <- tx_bind(tx_read(roster_rows, roster_key))\n  match found:\n    case None:\n      _ <- tx_bind(tx_insert(roster_rows, roster_key, [uid]))\n      tx_pure([uid])\n    case Some(roster):\n      if is_moderator(roster, uid):\n        grown = (\n          if member_String(roster, target): roster\n          else: [target, *roster])\n        _ <- tx_bind(tx_write(roster_rows, roster_key, grown))\n        tx_pure(grown)\n      else: tx_abort(forbid(\"only a moderator grants moderator\", \"Only a moderator can make someone a moderator.\"))\n\ndef grant_outcome(db: Db, p: Principal, target: String) -> IO[TxOutcome[Response, List[String]]]:\n  _ <- transaction(db)\n  grant_plan(p, target)\n\ndef grant_moderator(db: Db, p: Principal, req: GrantModeratorRequest) -> IO[Response]:\n  GrantModeratorRequest(target) = req\n  outcome <- flat_map(grant_outcome(db, p, target))\n  match outcome:\n    case Committed(roster): pure(respond(\"moderators\", [(\"roster\", jstrings(roster))]))\n    case Aborted(refusal): pure(refusal)\n    case RetryExhausted: pure(answer(503, \"try_again\", [(\"message\", JsonString(\"The roster was busy; send the request again.\"))]))\n    case CommitUnknown:\n      pure(answer(503, \"try_again\", [(\"message\", JsonString(\"The grant may not have been saved; send it again.\"))]))\n\ndef open_thread(db: Db, p: Principal, req: OpenThreadRequest) -> IO[Response]:\n  Principal(uid, _) = p\n  fresh_id <- flat_map(db_next_id(threads_table(db)))\n  match parse_thread(uid, fresh_id, req):\n    case Failure(issues): pure(reject(issues))\n    case Success(thread):\n      stored <- flat_map(db_write(threads_table(db), fresh_id, thread))\n      pure(respond(\"thread\", [(\"threads\", JsonArray([render_thread(stored)]))]))\n\ndef list_threads(db: Db, p: Principal) -> IO[Response]:\n  Principal(uid, _) = p\n  roster <- flat_map(db_read(moderators_table(db), roster_key))\n  rows <- flat_map(db_query(threads_table(db)))\n  visible = keep_visible(rows, thread -> can_see(uid, roster, thread))\n  pure(respond(\"threads\", [\n    (\"count\", jint(length_List(visible))),\n    (\"threads\", JsonArray(map_List(visible, render_thread))),\n  ]))\n\n# A thread and its posts, with the version an edit names.\ndef thread_view(thread: Thread, posts: Posts) -> Response:\n  Posts(version, items) = posts\n  respond(\"thread\", [\n    (\"thread\", render_thread(thread)),\n    (\"reply_count\", jint(length_List(items))),\n    (\"version\", jint(version)),\n    (\"posts\", JsonArray(map_List(items, render_post))),\n  ])\n\nfull_thread = reject([Issue(\"thread_id\", \"thread_full\", \"the thread has reached its reply cap\")])\n\nmembers_only = forbid(\"members only\", \"This thread is for its members only.\")\n\nedited_since = answer(409, \"edited_since\", [\n  (\"message\", JsonString(\"The posts were saved since you read them; read the thread again and send the edit with its version.\")),\n])\n\n# A save's outcome as a response; a busy or unconfirmed save asks to be\n# read and sent again.\ndef saved(outcome: TxOutcome[Response, (Thread, Posts)]) -> Response:\n  match outcome:\n    case Committed((thread, posts)): thread_view(thread, posts)\n    case Aborted(refusal): refusal\n    case RetryExhausted: answer(503, \"try_again\", [(\"message\", JsonString(\"The thread was busy; send the request again.\"))])\n    case CommitUnknown:\n      answer(503, \"try_again\", [(\"message\", JsonString(\"The save may not have been made; read the thread before sending it again.\"))])\n\ndef read_thread(db: Db, p: Principal, req: ReadThreadRequest) -> IO[Response]:\n  Principal(uid, _) = p\n  ReadThreadRequest(thread_id) = req\n  roster <- flat_map(db_read(moderators_table(db), roster_key))\n  row <- flat_map(db_read_opt(threads_table(db), thread_id))\n  match row:\n    case None: pure(not_found(\"thread\"))\n    case Some(thread):\n      if can_see(uid, roster, thread):\n        found <- flat_map(db_read_opt(posts_table(db), thread_id))\n        stored = match found:\n          case Some(posts): posts\n          case None: Posts(0, [])\n        pure(thread_view(thread, stored))\n      else: pure(forbid(\"members only\", \"This thread is for its members only.\"))\n\n# A reply, in one transaction with the reads of the thread and the posts it\n# joins: under the visibility rule and the reply cap, it raises the posts'\n# version.\ndef post_reply(db: Db, p: Principal, req: ReplyRequest) -> IO[Response]:\n  Principal(uid, _) = p\n  ReplyRequest(thread_id, body) = req\n  match check_text(\"body\", body, 500):\n    case [issue, *more]: pure(reject([issue, *more]))\n    case []:\n      outcome <- flat_map(transaction(db, _ -> (\n        seated <- tx_bind(tx_read(roster_rows, roster_key))\n        roster = match seated:\n          case Some(names): names\n          case None: []\n        row <- tx_bind(tx_read(thread_rows, thread_id))\n        match row:\n          case None: tx_abort(not_found(\"thread\"))\n          case Some(thread):\n            if can_see(uid, roster, thread):\n              found <- tx_bind(tx_read(posts_rows, thread_id))\n              match found:\n                case None:\n                  if has_room(thread, []):\n                    fresh_id <- tx_bind(tx_next_id(posts_rows))\n                    stored = Posts(1, [Post(fresh_id, thread_id, uid, body, False)])\n                    _ <- tx_bind(tx_write(posts_rows, thread_id, stored))\n                    tx_pure((thread, stored))\n                  else: tx_abort(full_thread)\n                case Some(Posts(version, items)):\n                  if has_room(thread, items):\n                    fresh_id <- tx_bind(tx_next_id(posts_rows))\n                    stored = Posts(version.add(1), [*items, Post(fresh_id, thread_id, uid, body, False)])\n                    _ <- tx_bind(tx_write(posts_rows, thread_id, stored))\n                    tx_pure((thread, stored))\n                  else: tx_abort(full_thread)\n            else: tx_abort(members_only)\n      )))\n      pure(saved(outcome))\n\n# An edit, in one transaction with the reads of the thread and the posts:\n# only where the posts are still at the version the caller read, under the\n# visibility rule and the edit rule; it raises the version.\ndef edit_post(db: Db, p: Principal, req: EditPostRequest) -> IO[Response]:\n  Principal(uid, _) = p\n  EditPostRequest(thread_id, post_id, body, seen) = req\n  match check_text(\"body\", body, 500):\n    case [issue, *more]: pure(reject([issue, *more]))\n    case []:\n      outcome <- flat_map(transaction(db, _ -> (\n        seated <- tx_bind(tx_read(roster_rows, roster_key))\n        roster = match seated:\n          case Some(names): names\n          case None: []\n        row <- tx_bind(tx_read(thread_rows, thread_id))\n        match row:\n          case None: tx_abort(not_found(\"thread\"))\n          case Some(thread):\n            if can_see(uid, roster, thread):\n              found <- tx_bind(tx_read(posts_rows, thread_id))\n              match found:\n                case None: tx_abort(not_found(\"post\"))\n                case Some(Posts(version, items)):\n                  match find_post(items, post_id):\n                    case None: tx_abort(not_found(\"post\"))\n                    case Some(post):\n                      if can_edit(uid, roster, post):\n                        if eq_Int(version, seen):\n                          Post(_, _, author, _, _) = post\n                          stored = Posts(seen.add(1), replace_post(items, Post(post_id, thread_id, author, body, True)))\n                          _ <- tx_bind(tx_write(posts_rows, thread_id, stored))\n                          tx_pure((thread, stored))\n                        else: tx_abort(edited_since)\n                      else: tx_abort(forbid(\"author or moderator\", \"Only the post's author or a moderator can edit it.\"))\n            else: tx_abort(members_only)\n      )))\n      pure(saved(outcome))\n\nforum_api = service_def(\n  \"forum\",\n  [\n    route(\"/profile\", handler(\"get_profile\", get_profile), [ReadPerm(\"profiles\")]),\n    route(\"/profile/put\", handler(\"put_profile\", put_profile), [WritePerm(\"profiles\")]),\n    route(\"/moderators/grant\", handler(\"grant_moderator\", grant_moderator),\n      [ReadPerm(\"moderators\"), CreatePerm(\"moderators\"), WritePerm(\"moderators\")]),\n    route(\"/threads/open\", handler(\"open_thread\", open_thread),\n      [CreatePerm(\"threads\"), WritePerm(\"threads\")]),\n    route(\"/threads\", handler(\"list_threads\", list_threads),\n      [ReadPerm(\"moderators\"), QueryPerm(\"threads\")]),\n    route(\"/threads/read\", handler(\"read_thread\", read_thread),\n      [ReadPerm(\"moderators\"), ReadPerm(\"threads\"), ReadPerm(\"posts\")]),\n    route(\"/posts/reply\", handler(\"post_reply\", post_reply),\n      [ReadPerm(\"moderators\"), ReadPerm(\"threads\"), ReadPerm(\"posts\"), CreatePerm(\"posts\"), WritePerm(\"posts\")]),\n    route(\"/posts/edit\", handler(\"edit_post\", edit_post),\n      [ReadPerm(\"moderators\"), ReadPerm(\"threads\"), ReadPerm(\"posts\"), WritePerm(\"posts\")]),\n  ]\n)\n"
      }
    ]
  },
  "request": {
    "binding": "Demo/Forum::read_thread",
    "inputs": {
      "p": {
        "user_id": "carol",
        "roles": []
      },
      "req": {
        "thread_id": "t1"
      }
    },
    "rows": {
      "threads": {
        "t1": {
          "id": "t1",
          "title": "private planning",
          "author": "alice",
          "visibility": {
            "Members": {}
          },
          "members": [
            "bob"
          ],
          "reply_cap": 2
        }
      },
      "posts": {
        "t1": {
          "version": 1,
          "items": [
            {
              "id": "p1",
              "thread_id": "t1",
              "author": "bob",
              "body": "first",
              "edited": false
            }
          ]
        }
      },
      "moderators": {
        "roster": [
          "mona"
        ]
      }
    },
    "seed": 7,
    "observe": true,
    "variations": 3
  },
  "binding": {
    "package": "Demo/Forum",
    "name": "read_thread",
    "id": "Demo/Forum::read_thread",
    "type": "(Yichus/Data::Db, Yichus/Access::Principal, Demo/Forum::ReadThreadRequest) -> Yichus/IO::IO[Yichus/Service::Response]",
    "isIO": true,
    "arity": 3
  },
  "seed": 7,
  "inputs": [
    {
      "param": "db",
      "type": "Yichus/Data::Db",
      "shape": {
        "kind": "enum",
        "name": "Db",
        "constructors": []
      },
      "origin": "world",
      "json": null,
      "rendered": null
    },
    {
      "param": "p",
      "type": "Yichus/Access::Principal",
      "shape": {
        "kind": "struct",
        "name": "Principal",
        "newtype": false,
        "fields": [
          {
            "name": "user_id",
            "shape": {
              "kind": "string"
            }
          },
          {
            "name": "roles",
            "shape": {
              "kind": "list",
              "elem": {
                "kind": "string"
              }
            }
          }
        ]
      },
      "origin": "provided",
      "json": {
        "user_id": "carol",
        "roles": []
      },
      "rendered": "Principal(user_id: \"carol\", roles: [])"
    },
    {
      "param": "req",
      "type": "Demo/Forum::ReadThreadRequest",
      "shape": {
        "kind": "struct",
        "name": "ReadThreadRequest",
        "newtype": true,
        "fields": [
          {
            "name": "thread_id",
            "shape": {
              "kind": "string"
            }
          }
        ]
      },
      "origin": "provided",
      "json": {
        "thread_id": "t1"
      },
      "rendered": "ReadThreadRequest(\"t1\")"
    }
  ],
  "output": {
    "type": "Yichus/Service::Response",
    "json": {
      "status": 403,
      "body": "{\"view\":\"forbidden\",\"rule\":\"members only\",\"message\":\"This thread is for its members only.\"}"
    },
    "jsonStatus": "encoded",
    "rendered": "Response(status: 403, body: \"{\"view\":\"forbidden\",\"rule\":\"members only\",\"message\":\"This thread is for its members only.\"}\")"
  },
  "steps": {
    "basis": "not evaluated: a handler's lets run inside its IO plan, so steps are shown for pure definitions only",
    "items": []
  },
  "soundFacts": {
    "basis": "sound-static (holds for every input)",
    "paramInfluence": [
      {
        "param": "db",
        "kind": "return-data",
        "sentence": "parameter 'db' may reach the returned data (static dataflow; holds for every input); no observation can rule its influence out"
      },
      {
        "param": "p",
        "kind": "return-data",
        "sentence": "parameter 'p' may reach the returned data (static dataflow; holds for every input); no observation can rule its influence out"
      },
      {
        "param": "req",
        "kind": "return-data",
        "sentence": "parameter 'req' may reach the returned data (static dataflow; holds for every input); no observation can rule its influence out"
      }
    ],
    "deadInputs": [],
    "structFields": []
  },
  "observed": {
    "basis": "bounded-observation (seed 7, one recorded handler run; 3 variations per aspect, each on a fresh world from the same seeded rows)",
    "variation": "a provided Int varies near its value first (+10%, -10%, doubled, halved, zero); every other value is drawn from the seed",
    "referenceBasis": "global-value-forcing",
    "touched": [
      "Demo/Forum::answer",
      "Demo/Forum::can_see",
      "Demo/Forum::forbid",
      "Demo/Forum::is_moderator",
      "Demo/Forum::member_String",
      "Demo/Forum::moderators_table",
      "Demo/Forum::roster_key",
      "Demo/Forum::threads_table"
    ],
    "differentials": [
      {
        "axis": "field 'user_id' of parameter 'p'",
        "outcome": "observed-constant",
        "sentence": "varying field 'user_id' of parameter 'p' across 4 distinct values with the rest fixed (seed 7), the rendered result never changed — a reaching path may need regions of the OTHER inputs these runs never visited; bounded observation, not proof",
        "param": "p",
        "field": "user_id"
      },
      {
        "axis": "field 'roles' of parameter 'p'",
        "outcome": "observed-constant",
        "sentence": "varying field 'roles' of parameter 'p' across 2 distinct values with the rest fixed (seed 7), the rendered result never changed — a reaching path may need regions of the OTHER inputs these runs never visited; bounded observation, not proof",
        "param": "p",
        "field": "roles"
      },
      {
        "axis": "parameter 'req'",
        "outcome": "varied",
        "sentence": "varying parameter 'req' changed the result from Response(status: 403, body: \"{\"view\":\"forbidden\",\"rule\":\"members only\",\"message\":\"This thread is for its members only.\"}\") to Response(status: 404, body: \"{\"view\":\"not_found\",\"what\":\"thread\"}\") (seed 7, variations base/0); fields that changed: status 403 to 404 (+1), body \"{\"view\":\"forbidden\",\"rule\":\"members only\",\"message\":\"This thread is for its members only.\"}\" to \"{\"view\":\"not_found\",\"what\":\"thread\"}\"; bounded observation, not proof",
        "witness": {
          "inputA": "ReadThreadRequest(\"t1\")",
          "outputA": "Response(status: 403, body: \"{\"view\":\"forbidden\",\"rule\":\"members only\",\"message\":\"This thread is for its members only.\"}\")",
          "inputB": "ReadThreadRequest(\"/profile/put94\")",
          "outputB": "Response(status: 404, body: \"{\"view\":\"not_found\",\"what\":\"thread\"}\")",
          "valueA": "ReadThreadRequest(\"t1\")",
          "valueB": "ReadThreadRequest(\"/profile/put94\")",
          "fields": [
            {
              "field": "status",
              "from": "403",
              "to": "404",
              "changed": true,
              "delta": "+1"
            },
            {
              "field": "body",
              "from": "\"{\"view\":\"forbidden\",\"rule\":\"members only\",\"message\":\"This thread is for its members only.\"}\"",
              "to": "\"{\"view\":\"not_found\",\"what\":\"thread\"}\"",
              "changed": true
            }
          ]
        },
        "param": "req",
        "outputFields": {
          "moved": [
            "status",
            "body"
          ],
          "steady": []
        }
      }
    ],
    "notReached": {
      "definitions": [
        "Demo/Forum::jint",
        "Demo/Forum::jstrings",
        "Demo/Forum::not_found",
        "Demo/Forum::posts_table",
        "Demo/Forum::render_post",
        "Demo/Forum::render_thread",
        "Demo/Forum::render_visibility",
        "Demo/Forum::respond",
        "Demo/Forum::thread_view"
      ],
      "sentence": "global values for 9 of 17 definitions reachable from Demo/Forum::read_thread statically were not forced on this input (seed 7): Demo/Forum::jint, Demo/Forum::jstrings, Demo/Forum::not_found, Demo/Forum::posts_table, Demo/Forum::render_post, Demo/Forum::render_thread, Demo/Forum::render_visibility, Demo/Forum::respond, Demo/Forum::thread_view — an absence on this input, not a fault; another input may force them; forcing a function value does not establish that its body ran; bounded observation, not proof"
    }
  },
  "world": {
    "shape": {
      "tables": {
        "moderators": {
          "rowType": "List[String]",
          "rowForm": "list: the row under an id is the whole list (a JSON array of records)",
          "rowIsList": true,
          "recordFields": {},
          "recordShape": {
            "kind": "string"
          }
        },
        "posts": {
          "rowType": "Posts",
          "rowForm": "record: the row under an id is one record (a JSON object)",
          "rowIsList": false,
          "recordFields": {
            "version": "Int",
            "items": "List[Post]"
          },
          "recordShape": {
            "kind": "struct",
            "name": "Posts",
            "newtype": false,
            "fields": [
              {
                "name": "version",
                "shape": {
                  "kind": "int"
                }
              },
              {
                "name": "items",
                "shape": {
                  "kind": "list",
                  "elem": {
                    "kind": "struct",
                    "name": "Post",
                    "newtype": false,
                    "fields": [
                      {
                        "name": "id",
                        "shape": {
                          "kind": "string"
                        }
                      },
                      {
                        "name": "thread_id",
                        "shape": {
                          "kind": "string"
                        }
                      },
                      {
                        "name": "author",
                        "shape": {
                          "kind": "string"
                        }
                      },
                      {
                        "name": "body",
                        "shape": {
                          "kind": "string"
                        }
                      },
                      {
                        "name": "edited",
                        "shape": {
                          "kind": "bool"
                        }
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        "profiles": {
          "rowType": "Profile",
          "rowForm": "record: the row under an id is one record (a JSON object)",
          "rowIsList": false,
          "recordFields": {
            "user_id": "String",
            "display_name": "String"
          },
          "recordShape": {
            "kind": "struct",
            "name": "Profile",
            "newtype": false,
            "fields": [
              {
                "name": "user_id",
                "shape": {
                  "kind": "string"
                }
              },
              {
                "name": "display_name",
                "shape": {
                  "kind": "string"
                }
              }
            ]
          }
        },
        "threads": {
          "rowType": "Thread",
          "rowForm": "record: the row under an id is one record (a JSON object)",
          "rowIsList": false,
          "recordFields": {
            "id": "String",
            "title": "String",
            "author": "String",
            "visibility": "Visibility",
            "members": "List[String]",
            "reply_cap": "Int"
          },
          "recordShape": {
            "kind": "struct",
            "name": "Thread",
            "newtype": false,
            "fields": [
              {
                "name": "id",
                "shape": {
                  "kind": "string"
                }
              },
              {
                "name": "title",
                "shape": {
                  "kind": "string"
                }
              },
              {
                "name": "author",
                "shape": {
                  "kind": "string"
                }
              },
              {
                "name": "visibility",
                "shape": {
                  "kind": "enum",
                  "name": "Visibility",
                  "constructors": [
                    {
                      "name": "Open",
                      "fields": []
                    },
                    {
                      "name": "Members",
                      "fields": []
                    }
                  ]
                }
              },
              {
                "name": "members",
                "shape": {
                  "kind": "list",
                  "elem": {
                    "kind": "string"
                  }
                }
              },
              {
                "name": "reply_cap",
                "shape": {
                  "kind": "int"
                }
              }
            ]
          }
        }
      },
      "rowKey": "rows are {table: {id: row}} (or {table: [row, ...]} numbering rows \"1\"..\"n\"); a handler that reads by the principal's user_id needs a row under that id",
      "principalForm": {
        "user_id": "<id>",
        "roles": [
          "<role>"
        ]
      },
      "enumForm": "an enum value is written {\"Ctor\": {fields}} -- {\"Backlog\": {}} for a nullary constructor, which is also the form this tool prints; the bare object of a constructor's fields is read too, and a bare {} is the first nullary constructor"
    },
    "misses": [],
    "seededRows": {
      "moderators": [
        "[\"mona\"]"
      ],
      "posts": [
        "Posts(version: 1, items: [Post(id: \"p1\", thread_id: \"t1\", author: \"bob\", body: \"first\", edited: False)])"
      ],
      "threads": [
        "Thread(id: \"t1\", title: \"private planning\", author: \"alice\", visibility: Members, members: [\"bob\"], reply_cap: 2)"
      ]
    },
    "rowsAfter": {
      "moderators": [
        "[\"mona\"]"
      ],
      "posts": [
        "Posts(version: 1, items: [Post(id: \"p1\", thread_id: \"t1\", author: \"bob\", body: \"first\", edited: False)])"
      ],
      "threads": [
        "Thread(id: \"t1\", title: \"private planning\", author: \"alice\", visibility: Members, members: [\"bob\"], reply_cap: 2)"
      ]
    }
  },
  "skipped": [],
  "proposals": [
    {
      "name": "p = a principal who owns no row",
      "rationale": "the recorded run's principal is 'carol'; untried: the principal 'someone-else' with no roles, who appears in no seeded row, which tests whether the result depends on who asks",
      "request": {
        "binding": "Demo/Forum::read_thread",
        "inputs": {
          "p": {
            "user_id": "someone-else",
            "roles": []
          },
          "req": {
            "thread_id": "t1"
          }
        },
        "rows": {
          "threads": {
            "t1": {
              "id": "t1",
              "title": "private planning",
              "author": "alice",
              "visibility": {
                "Members": {}
              },
              "members": [
                "bob"
              ],
              "reply_cap": 2
            }
          },
          "posts": {
            "t1": {
              "version": 1,
              "items": [
                {
                  "id": "p1",
                  "thread_id": "t1",
                  "author": "bob",
                  "body": "first",
                  "edited": false
                }
              ]
            }
          },
          "moderators": {
            "roster": [
              "mona"
            ]
          }
        },
        "seed": 7,
        "observe": true,
        "variations": 3
      }
    },
    {
      "name": "every table empty",
      "rationale": "the recorded run was seeded with rows in threads, posts, moderators; untried: an empty world, where every read misses",
      "request": {
        "binding": "Demo/Forum::read_thread",
        "inputs": {
          "p": {
            "user_id": "carol",
            "roles": []
          },
          "req": {
            "thread_id": "t1"
          }
        },
        "rows": {},
        "seed": 7,
        "observe": true,
        "variations": 3
      }
    },
    {
      "name": "table 'threads' empty",
      "rationale": "the recorded run was seeded with rows in threads; untried: the same world with 'threads' empty, so a read of it misses while the other tables stand",
      "request": {
        "binding": "Demo/Forum::read_thread",
        "inputs": {
          "p": {
            "user_id": "carol",
            "roles": []
          },
          "req": {
            "thread_id": "t1"
          }
        },
        "rows": {
          "posts": {
            "t1": {
              "version": 1,
              "items": [
                {
                  "id": "p1",
                  "thread_id": "t1",
                  "author": "bob",
                  "body": "first",
                  "edited": false
                }
              ]
            }
          },
          "moderators": {
            "roster": [
              "mona"
            ]
          }
        },
        "seed": 7,
        "observe": true,
        "variations": 3
      }
    },
    {
      "name": "table 'posts' empty",
      "rationale": "the recorded run was seeded with rows in posts; untried: the same world with 'posts' empty, so a read of it misses while the other tables stand",
      "request": {
        "binding": "Demo/Forum::read_thread",
        "inputs": {
          "p": {
            "user_id": "carol",
            "roles": []
          },
          "req": {
            "thread_id": "t1"
          }
        },
        "rows": {
          "threads": {
            "t1": {
              "id": "t1",
              "title": "private planning",
              "author": "alice",
              "visibility": {
                "Members": {}
              },
              "members": [
                "bob"
              ],
              "reply_cap": 2
            }
          },
          "moderators": {
            "roster": [
              "mona"
            ]
          }
        },
        "seed": 7,
        "observe": true,
        "variations": 3
      }
    },
    {
      "name": "table 'moderators' empty",
      "rationale": "the recorded run was seeded with rows in moderators; untried: the same world with 'moderators' empty, so a read of it misses while the other tables stand",
      "request": {
        "binding": "Demo/Forum::read_thread",
        "inputs": {
          "p": {
            "user_id": "carol",
            "roles": []
          },
          "req": {
            "thread_id": "t1"
          }
        },
        "rows": {
          "threads": {
            "t1": {
              "id": "t1",
              "title": "private planning",
              "author": "alice",
              "visibility": {
                "Members": {}
              },
              "members": [
                "bob"
              ],
              "reply_cap": 2
            }
          },
          "posts": {
            "t1": {
              "version": 1,
              "items": [
                {
                  "id": "p1",
                  "thread_id": "t1",
                  "author": "bob",
                  "body": "first",
                  "edited": false
                }
              ]
            }
          }
        },
        "seed": 7,
        "observe": true,
        "variations": 3
      }
    }
  ],
  "epistemics": "soundFacts hold for every input (static dataflow). observed entries are bounded observations from seeded runs. Decision rule: output dependence is ruled OUT only by a sound unused fact. A guard-only fact rules out data flow, but control flow can still change the result. A concrete differing-output witness establishes dependence. A return-data (may-reach) fact combined with observed-constant runs stays UNRESOLVED — the reaching path may need input regions these runs never visited, so vary the OTHER parameters' regions to hunt a witness before concluding anything.",
  "narrative": "This run evaluated the handler 'read_thread' (package Demo/Forum) with 'db' (the world's database), 'p' = Principal(user_id: \"carol\", roles: []) (provided) and 'req' = ReadThreadRequest(\"t1\") (provided). It returned Response(status: 403, body: \"{\"view\":\"forbidden\",\"rule\":\"members only\",\"message\":\"This thread is for its members only.\"}\").\n\nProven for every input, by static dataflow (no run needed): 'db' may reach the result, so no run can rule its influence out; 'p' may reach the result, so no run can rule its influence out; 'req' may reach the result, so no run can rule its influence out.\n\nObserved on this run, not proven (bounded-observation (seed 7, one recorded handler run; 3 variations per aspect, each on a fresh world from the same seeded rows)): changing field 'user_id' of parameter 'p' across the seeded values never changed the result, which does not show independence; changing field 'roles' of parameter 'p' across the seeded values never changed the result, which does not show independence; changing parameter 'req' from ReadThreadRequest(\"t1\") to ReadThreadRequest(\"/profile/put94\") moved status from 403 to 404 (+1) and body from \"{\"view\":\"forbidden\",\"rule\":\"members only\",\"message\":\"This thread is for its members only.\"}\" to \"{\"view\":\"not_found\",\"what\":\"thread\"}\". Seeded and varied values are drawn from the seed, not from the domain: an integer may be negative or far outside any expected range. The run forced global values for 8 definitions: answer, can_see, forbid, is_moderator, member_String, moderators_table, roster_key, threads_table. Loading a function value does not establish that its body ran. Global values for 9 definitions this one can reach were not forced on this input: jint, jstrings, not_found, posts_table, render_post, render_thread, render_visibility, respond, thread_view (an absence on this input, not a fault; another input may force them).\n\nThe world was seeded with 1 row in 'moderators', 1 row in 'posts' and 1 row in 'threads'. Seeded rows, as rendered: 'moderators': [\"mona\"]; 'posts': Posts(version: 1, items: [Post(id: \"p1\", thread_id: \"t1\", author: \"bob\", body: \"first\", edited: False)]); 'threads': Thread(id: \"t1\", title: \"private planning\", author: \"alice\", visibility: Members, members: [\"bob\"], reply_cap: 2). Every read found its row. No table changed.\n\n5 experiments are proposed from this run's facts, none of them run: p = a principal who owns no row; every table empty; table 'threads' empty; table 'posts' empty; table 'moderators' empty."
}