Revert "feat(relay): support community-scoped NIP-AR artifacts" (#9689)

Reverts #9650 (squash commit `eebf62b6`), except for migration `0097`
and the channel artifact sync fences it added.

Community scope adds a relay access gate based on community admission
rather than channel membership, a new relay-admin command kind (`9034`)
and an operator-run key transition. Its design and NIP-AR text need
relay maintainer review before they ship. Two integration gaps also
remain:

- Media download authorization looks up references only in `events`, so
an attachment referenced only by a community artifact is unreadable when
media-read enforcement is on.
- User erasure retires a community head in the database without
signaling live syncs, so members who are already syncing keep the erased
copy.

The feature can return as a new PR once those are resolved.

## Kept from #9650

- **Migration `0097`, byte for byte.** Published images already include
it, and databases that auto-migrated have recorded it. Dropping it would
stop those relays from starting. It only adds columns and indexes that
the channel code ignores. The declared schema matches that expanded
shape and keeps the `(community_id, artifact_id)` primary key, so the
operator key transition no longer exists.
- **Channel artifact sync fences.** Snapshot and live sends check for a
pending resync and for connection cancellation under the queue lock. A
reader who loses access, or whose content is redacted, while a frame is
in flight therefore receives no further payload. Handler-backed tests
cover a resync recorded while a snapshot payload waits for queue room
and one recorded after a live head read.

## Compatibility

This revert supports databases that applied only migration `0097`, which
is all that auto-migration runs. A database that ran #9650's operator
contract script, or was bootstrapped from #9650's declared schema, has
no `(community_id, artifact_id)` key, so channel artifact writes fail
there. Before deploying to such a database, check that
`artifact_heads_pkey` is on `(community_id, artifact_id)` and that
`artifact_heads` has no rows with `scope = 'community'`; if either check
fails, it needs a separate recovery step.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Co-authored-by: Paul <4a1bfa0013bc6d14a8d600d8bf6392efefbd2a26ac3c96c9b2a106b0d12297ca@buzz.block.builderlab.xyz>
This commit is contained in:
Will Pfleger
2026-11-18 21:38:17 -05:00
committed by GitHub
parent db40da87b4
commit a406191694
57 changed files with 389 additions and 4901 deletions

View File

@@ -1,111 +0,0 @@
# Community artifact activation
Community artifacts implement [NIP-AR](nips/NIP-AR.md). The operator switch
`BUZZ_COMMUNITY_ARTIFACTS_ENABLED` defaults to `false`. Enabling it requires a
restart and a verified contracted schema; setting it on the expand schema
serves channel artifacts but neither accepts nor advertises community scope.
## Expand and deploy
For an existing database, apply migration 0097. Deployments that manage
schema out of band can run the same reviewed SQL in a single transaction.
Defer any desired-state plan that changes `artifact_heads` until the guarded
contract below succeeds. The declarative schema specifies the final scoped
primary key, which old channel writers cannot use.
Migration 0097 adds constant-default scope columns, nullable channel IDs,
community revision JSON, redaction state and a bounded policy map on
`communities`. It retains the `(community_id, artifact_id)` primary key
and adds a scoped unique index.
There is no data backfill. Existing rows default to channel scope. Old channel
writers retain their conflict target and the bridge retains their advisory
lock `artifact:{tenant}:{d}`. All indexes have lock and statement budgets. If
an inline index build exceeds them, leave auto-migration disabled. Apply only
the additive column statements at the top of migration 0097 in a transaction
with the same lock and statement budgets, and commit. Then build the three
indexes with `CREATE [UNIQUE] INDEX CONCURRENTLY` outside a transaction, using
the exact names and column order in 0097. Rerun 0097 to validate their shapes
and record the migration. The additive statements are idempotent for this
procedure; a mismatched column or index still fails closed.
Deploy this audience-enforcing relay, compatible deletion executors and
operator tools to **every** backend serving the tenant, with the switch off.
Ordinary query, history, ID, search, count, moderation preview and fan-out
fences apply even while the switch is off. Community payloads are stored only
in the existing revision ledger, outside `events` and its generated search
index. They do not enter chat counters, push or hooks. The community purge deletes both scoped ledgers and clears the policy map
before retaining the community tombstone. Compatible deletion executors are
required after contract, alongside serving backends.
An old binary can continue channel operations on the expanded schema. If
rolling back before contract, disable auto-migration on the old binary: sqlx
otherwise refuses migration versions newer than the binary knows.
## Separate operator contract
This step is intentionally absent from automatic migration history. Do not run
it in a migration boot hook. An upgrade skipping the bridge deployment must
stop after expand. After verifying all backends enforce community audiences
and use scoped column inference for upserts, run in one operator session:
```sh
psql "$DATABASE_URL" -v ON_ERROR_STOP=1 \
-c "SET buzz.community_artifact_contract_ready = 'all-backends-enforce-community-audience'" \
-f scripts/maintenance/community-artifact-contract.sql
```
The attestation is a human fleet check, not something a database catalog can
prove. The script verifies the expanded unique index and atomically attaches
it as the scoped primary key while removing the legacy primary key, within
5-second lock and 30-second statement budgets. The script is safe to rerun.
After it succeeds, resume desired-state reconciliation for `artifact_heads`.
The declarative schema now matches the scoped primary key. Fresh databases
bootstrapped from `schema/schema.sql` start with that key and require compatible
relay binaries, deletion executors and operator tools from the start.
Restart compatible backends with `BUZZ_COMMUNITY_ARTIFACTS_ENABLED=true` only
after the fleet check. Each process verifies the scoped primary key, absence
of the old unique key and the expanded columns before accepting writes or
advertising `artifacts.community_scope`. NIP-11 resolves the canonical tenant
UUID and advertises `max_policies: 256`. Verify signed reads and writes in both
scopes, including simultaneous identical `d` values, before allowing clients.
## Rollback floor
After contract, this audience-enforcing bridge is the minimum relay version,
even if community writes have not started. Old binaries cannot use their
legacy conflict target. Keep the contracted schema and all privacy fences.
Turning the switch off stops explicit community operations and advertisement;
it does not remove stored payloads or make them ordinary events. Do not restore
the old unique key once both scopes can contain the same `d`. Returning to an
older binary requires a separate reviewed recovery plan and is outside this
activation procedure. No live deployment is part of implementing this feature.
## Admission and exact-copy lifecycle
Community admission keeps the authenticated key and its verified owner as
restriction identities. Direct roster membership is sufficient. Owner roster
membership is a fallback only for a verified FI agent assertion or when the
current OA policy permits the verified proof. A timeout blocks new content and
redaction but permits reads and exact accepted-content retries; bans block both.
| State | Entry and exit fence |
|---|---|
| Subscribe | Claim the subscription generation under the existing lifecycle lock, retain the tenant artifact topic, and confirm Redis interest on one unbroken loss epoch before reading. |
| DB snapshot | Check admission and read current heads in one writer-backed repeatable-read transaction, keyset-paged by identity and indexed by tenant, scope and immutable type. Hold at most 256 heads per page and the advertised set bound overall. |
| Enqueue | Reserve output first. The socket credential gate, subscription generation and pending invalidation are checked before enqueue. |
| Live | A bounded typed Redis signal carries only identity, immutable type and change cause. Check admission and reload the authorized current head on the writer. A denied admission ends the sync with resync. The signal carries no payload. Current-head redaction resyncs that type; historical redaction does not retire its successor. |
| Invalidation | Existing principal/owner disconnect fan-out handles revocation. If an invalidation is missed, an idle sync can retain its set until the next relevant signal or socket revocation. The socket-level revalidator still handles archive, deletion and required-FI upgrades. Decode loss, reconnect or receiver lag resync exact copies. |
| Close | CLOSE, replacement REQ, disconnect and refusal retire the generation, cancel the task and release exactly the topic retained by its scope through the existing teardown. |
The relay writer pool defaults to 50 connections (`BUZZ_DB_POOL_SIZE`) with a
3 second acquisition timeout.
Community snapshots additionally cap themselves at `min(pool_size - 1, 8)`,
wait at most 1 second for that permit, and refuse one-connection pools. This
leaves a writer slot available when snapshots are paused on output. A
community snapshot or live head read takes one writer checkout with a 2 second
acquisition deadline and a 2 second statement timeout. The existing 30 second
snapshot budget includes paging, enqueue waits and authorization. Other writer
traffic may still saturate the pool; bounded refusal/resync preserves access
control in that case. Ordinary channel sync and ordinary event wire shapes
retain their existing paths.

View File

@@ -1,18 +1,18 @@
NIP-AR
======
Channel and Community Artifacts
-------------------------------
Channel Artifacts
-----------------
`draft` `optional` `relay`
Defines `kind:45010` for editable records called **artifacts**. A channel artifact has one home channel and may be attached to a thread. Its home determines who can read it. The optional [community scope](#community-scoped-artifacts-proposed-extension) has its own audience and no channel home. Any number of artifacts, including of the same type, may share a channel or thread.
Defines `kind:45010` for editable records called **artifacts**. Each artifact has one home channel and may be attached to a thread. Its home determines who can read it. Any number of artifacts, including of the same type, may share a channel or thread.
The relay manages identity, access, and revisions. Clients define the content types, such as `buzz.task` or `buzz.project`.
## Event format
Each event contains a complete snapshot. This section defines the channel envelope. This task is created in a channel, with the standard signing fields omitted.
Each event contains a complete snapshot. For example, a task created directly in a channel (standard signing fields omitted):
```json
{
@@ -52,7 +52,7 @@ Clients place fields needed for filtering in client-defined tags. The relay matc
## Identity and edits
A channel artifact is identified by `(community, d)` within the channel identity space, independently of its author or home. `d` and `type` are immutable. Kind 45010 is a regular stored event, not a NIP-01 addressable event. It falls in Buzz's forum and social kind range (45000–45999) but is not a forum post and follows none of the forum rules.
An artifact is identified by `(community, d)`, independently of its author or home. `d` and `type` are immutable. Kind 45010 is a regular stored event, not a NIP-01 addressable event. It falls in Buzz's forum and social kind range (45000–45999) but is not a forum post and follows none of the forum rules.
Creation requires an unused `d`, `op=create`, and no `prev`. Every later revision MUST name the current accepted event in `prev`. The relay checks authorization and advances the current revision atomically: two competing edits cannot both succeed. Timestamps do not choose the winner.
@@ -62,11 +62,9 @@ A `create` whose `d` is already in use fails. When the sender cannot read the ex
On creation or when changed from the previous accepted revision, `root` MUST identify an existing, undeleted conversation anchor in `h`. Later loss of that anchor does not prevent edits. Replies belong to that conversation, not to an artifact revision.
## Channel access
## Access
This section applies to channel artifacts. Community artifacts follow [Admission and authorization](#admission-and-authorization) instead.
Channel read permission governs every channel artifact read, including lookups, history, search, previews, counts, and live updates. Threads inherit their channel's audience. Membership and visibility changes take effect on subsequent reads and deliveries.
Channel read permission governs every artifact read, including lookups, history, search, previews, counts, and live updates. Threads inherit their channel's audience. Membership and visibility changes take effect on subsequent reads and deliveries.
Write permission means permission to post a kind-9 message in the channel, including authentication, token restrictions, moderation, and archive checks. Relays apply these checks the same way, and at the same point, as for a kind-9 message. This includes agents and, where channel policy permits, nonmembers of open channels. Artifact writes use `messages:write`, the scope that admits kind-9 posting.
@@ -134,7 +132,7 @@ sequenceDiagram
["REQ", "s1", {"artifact": "current", "#h": ["<channel>"], "#type": ["buzz.task"]}]
```
A channel sync filter MUST include `#h` with 1 or more channels. It accepts the same `#name` predicates and limits as a NIP-AR current-state query, with the same AND/OR rules, and also `kinds: [45010]`. It accepts no `limit` or `offset`. A relay rejects a channel sync filter without `#h`, or any filter with an unknown key, with `CLOSED`. A community sync adds the `scope` key and forbids `#h` instead; see [Reading and syncing](#reading-and-syncing).
The filter MUST include `#h` with 1 or more channels. It accepts the same `#name` predicates and limits as a NIP-AR current-state query, with the same AND/OR rules, and also `kinds: [45010]`. It accepts no `limit` or `offset`. A relay rejects a filter without `#h`, or with an unknown key, with `CLOSED`.
**Scope.** The sync's scope is the set of artifacts that a NIP-AR current-state query with the same filter returns to this reader at that time. The rules below use this one definition for access, matching and system channels.
@@ -239,69 +237,6 @@ Clients validate content before interpreting it as a known type. Unknown types o
Artifact text is untrusted. A type name, relationship tag, or payload cannot authorize a privileged action. Moving, deleting, or revoking access cannot erase copies already downloaded.
## Community-scoped artifacts (proposed extension)
### Envelope and identity
A relay advertising `artifacts.community_scope.version = 1` accepts a second form of kind 45010. A community artifact uses `["ar","1"]`, `["community","<community UUID>"]` and the usual `d`, `type`, `title`, `op` and `prev` tags. It MUST omit `h` and `root`. A channel artifact retains its existing envelope and MUST omit the new `community` tag. Reject a missing, mixed or repeated scope. The signed community UUID MUST equal the tenant resolved by the connection or HTTP request, including on retries. Clients obtain this stable UUID from the serving relay's `artifacts.community_scope.community_id` in NIP-11. Two hostnames that serve the same community advertise the same ID. The NIP-11 `artifacts` object advertises the scope:
```json
"community_scope": {"version": 1, "community_id": "<community UUID>", "max_policies": 256}
```
`max_policies` is the bound on stored type policies; this version uses 256. Scope UUIDs on input and output MUST be canonical lowercase, hyphenated, non-nil UUIDs.
Both scopes reuse the existing head and revision ledger. The identity in a community is `(community, scope class, d)`. Every channel remains in the same channel identity space, so moving a channel artifact preserves its identity. An artifact cannot move between scope classes. Reject `op=move` for a community artifact. In both scopes, `type` is immutable, and a revision naming an identity in the wrong scope answers like an unavailable head.
For one record per canonical key in a community type, clients MAY derive:
```
d = UUIDv8(first 16 bytes of SHA-256(
"nip-ar-community-artifact\0" + community_uuid + "\0" + type + "\0" + key))
```
The inputs are UTF-8. The UUID is lowercase and hyphenated. The type's client contract defines the canonical key, including case and Unicode normalization. Apply the version and variant bits as in the channel derivation. The distinct prefix separates the two derivations. Channel authors can choose arbitrary UUIDs, so the relay MUST also separate the two identity spaces in storage. The same UUID may exist in each scope and cannot reserve a record in the other. Within a scope, the first accepted create reserves the identity. The relay does not interpret names or content, and does not require the key or verify its derivation.
### Admission and authorization
| Operation | Required permission |
| --- | --- |
| Read, policy lookup, history, head, or sync | Current effective community admission and `messages:read`. |
| Create, update, delete, or restore | Current effective community admission, `messages:write` and the current write policy for the type. A community timeout blocks the write. |
| Set a type's write policy | A direct community owner or admin acting under `admin:users`. Apply the relay's administrative ban and timeout rules. |
Apply the same authenticated transport, event signer, expiry, size, quota and moderation rules on HTTP and WebSocket. A channel-restricted credential cannot use community scope, even if it covers every channel. Unauthenticated reads and generic channel permissions confer no community access. Treat lookup failure as denial or an error, with no artifact data. On an open relay, any authenticated principal admitted by current relay rules qualifies under `everyone`, even with no roster row. On a roster relay, the principal needs current effective membership, direct or through verified delegation admitted by the relay. Delegation does not transfer an owner's or admin's role. Apply the principal's and applicable owner's community restrictions. A ban blocks reads and writes, including replay. A timeout leaves reads available. Channel membership, archive, posting restrictions and channel admin roles do not grant or restrict these operations.
### Type write policy
The policy is tenant-scoped and keyed by the exact canonical artifact `type`. Missing means `everyone` with no prior policy revision. `admins` admits only an author who personally holds the community owner or admin role. The default on a rosterless open community is still `everyone`. Setting policy requires a configured community owner or admin.
Use the signed relay-admin command `SET_ARTIFACT_TYPE_POLICY` (proposed kind 9034, pending allocation). Require `community`, `type`, `policy` (`everyone` or `admins`), and `prev` (the current policy command ID or `0` for no prior command). Omit `h` and use empty content. The signed `community` MUST equal the tenant resolved by the request. After verifying the signature, refuse a command signed for another community before consulting any accepted-command record, including on retry, so an admin of several communities cannot apply it to the wrong one. Apply the relay-admin freshness and signer checks. Return a conflict for stale `prev`; an exact retry of the current accepted command is a no-op if the requester is still authorized. A superseded policy command may conflict on retry. Read current policy before retrying a conflicted command. The relay records the accepted admin action in its audit trail. The command is neither a kind 45010 revision nor an event in an ordinary subscription. A client with artifact-signing access alone cannot sign this command through that capability.
A signed HTTP `/query` policy lookup takes one exact type. For example, `{"artifact":"policy","scope":"community","#type":["example.settings"]}`. It returns `{"policy":"everyone","revision":null}` for an unset type, or the current policy and accepted command ID. The relay advertises and enforces a bound on stored policy entries. At the bound, it rejects a command for a type with no entry, whatever its `policy`, and still accepts changes to existing entries. Switching a configured type back to `everyone` retains its revision, and the entry still counts toward the bound. Retaining the revision prevents an older command from resetting the compare-and-set history.
A committed policy change governs new revisions, including updates, deletes and restores of existing records. It neither rewrites records nor changes their audience. A write and a policy change MUST be serialized so their admission and commit order agree. Serialize policy updates against write admission before acquiring the artifact's identity lock, including if the type has never had a policy. Recheck the write policy in the transaction. An older pending write that still qualifies must still satisfy the head compare-and-set. An exact previously accepted artifact replay by the same signer, with current community read admission and an unrestricted `messages:write` credential, returns only acknowledgement. It does not re-evaluate the edit policy, timeout or freshness, and it does not write or publish again. This acknowledgement grants no authority to create a new revision. A ban still refuses the replay. Check current community admission and the signed community before consulting receipts.
### Reading and syncing
Select the community scope explicitly with `"scope":"community"` on the signed HTTP views `current`, `head` and `history`. For WebSocket sync, use:
```json
["REQ", "s1", {"artifact":"current","scope":"community","#type":["example.settings"]}]
```
This sync selects one exact type and can use the existing exact tag predicates. `#h` is forbidden, and `head` still requires `#d`. Apply admission and scope before any filtering or paging. Reject community-scoped count requests in this version with an explicit error, never a zero or empty count. A legacy filter still sees only channel artifacts. Generic event reads, search, counts, direct ID fetches and ordinary live fan-out MUST exclude community artifact payloads. Route authorized reads through the explicit artifact views. HTTP incremental tokens and deltas remain channel-only in this version. Reject attempts to apply them to community scope.
Use the same snapshot, buffer bounds, `EOSE` and head sequencing as channel sync. Confirm live interest in the authenticated tenant before opening the snapshot. Only pass change signals to sync, and re-read authorized heads before delivery. A tag or deletion transition follows the existing before-and-after match rule. There is no kind 45011 move removal for community scope. Check current community admission, including any required FI credential, within the initial snapshot and each live head read. When an invalidation or a denied live read reveals loss of access, close the sync with `CLOSED "resync: ..."` or disconnect the session. An idle sync may retain an older set until the next relevant signal or socket revocation. A failed initial read cannot send `EOSE`. After loss of access, the client discards the active set for that community; after re-admission it starts with a fresh complete snapshot. Follow existing sync rules for loss of pub/sub, output and redaction signals. Changing an edit policy alone changes no content or read access.
### Delete and moderation
A community soft delete reserves its `d` under the same rules as a channel soft delete. The authorized way to recreate a canonical key is to read its deletion head and send `restore` with that ID in `prev`. A rename to a different key is a create and delete with separate commits. Existing references still address the old identity. A kind-5 deletion cannot target a community artifact revision.
For community moderation, use a community-bound kind 9005 command with a single target revision `e` and no `h`. Verify that the target is a community-scoped kind 45010 revision in this tenant. Require the existing moderation write scope and direct owner or admin authority, independent of who can edit its type. Redact through the existing moderation path and retain the accepted revision ID. Redaction of a current head ends any affected sync with resync. A kind 9005 with one valid `h` and no `community` uses the existing channel path. Reject repeated, missing or mixed scopes. This command does not emit a channel removal or update chat counters. Deleting the community itself purges both scopes, their acceptance ledgers and the type policies.
A relay MUST enable community writes and advertise the capability only after all backends that can serve the community enforce the community audience on queries, lookups, moderation and delivery.
## Incremental reads
Incremental reads maintain an eventually consistent local store. They do not prove a complete set at one database snapshot. Absence from a page never proves deletion or loss of access.