Skip to content

feat(scope): add archive and reopen lifecycle with a write cutoff - #15

Closed
PsiACE wants to merge 12 commits into
scope-sharing/base-2611from
scope-sharing/2611-c-lifecycle
Closed

PsiACE wants to merge 12 commits into
scope-sharing/base-2611from
scope-sharing/2611-c-lifecycle

Conversation

@PsiACE

@PsiACE PsiACE commented Nov 16, 2026

Copy link
Copy Markdown
Owner

Summary

Implements the Scope archive/reopen slice of RFC oceanbase#2611 (Scope archive, deletion and cleanup). Archiving a named Scope stops its ordinary content writes at the boundary that owns them; structural children keep their own state.

Runtime base: ad0d02061eee0e9fee38c202b60f421216b06dd9.

Rationale

The RFC requires that archiving stop new Sources, Artifact content writes, ordinary local processing and Candidate commits in the named Scope, and that in-flight work cannot commit after the cutoff. It also requires the gate to live at the owning boundary rather than being repeated per transport.

Rather than adding a state machine, this reuses the existing versioned Scope row:

  • pc_scopes.lifecycle_state is authoritative next to the identity it names.
  • One gate (require_writable) reads that row under a lock inside the writer's own transaction, so a state change and an in-flight write cannot interleave: whichever transaction takes the row first commits first.
  • The gate is called from the three real owning boundaries, so every Family inherits it without per-transport duplication.

Ablation: remove the gate and a Candidate proposed before archive publishes afterwards (the new acceptance test fails). Remove the row lock and the state check becomes a race rather than a cutoff. Both are required; neither is a new concept.

Behavior

Archive (named Scope only)

  • Stops new Sources, Artifact content writes and Candidate persistence in that Scope.
  • Structural children keep their own state — no cascade.
  • Grants, Context References and read authority are untouched, so an external Scope with a valid grant still reads archived evidence, and grant management, reopen and cleanup remain available.
  • The state change advances the Scope version, so a stale reader cannot silently reapply it.

Reopen returns the same Scope ID to writable without re-authorizing work or resetting processing cursors.

Serialization. archive/reopen take the existing hierarchy boundary (lock_hierarchy) plus expected_version, which serializes against structural attach/move as well as against concurrent lifecycle requests.

API and contract

  • ScopeDescriptor.lifecycle_state (writable | archived | deleting | deleted, default writable).
  • ScopeApplication.archive(scope_id, expected_version), ScopeApplication.reopen(scope_id, expected_version).
  • ScopeNotWritableError(scope_id, state) and ScopeLifecycleConflictError(scope_id, requested, state); stale versions keep raising the existing ScopeVersionConflictError.
  • No _generated/ or openapi/ edits: the published Scope response keeps its current shape (the transport mapping excludes the new domain field) so G can expose it with the contract. Published in /tmp/powercontext-2611-coordination/C-interface.md.

Migration

New revision v1_5_0_006, registered on both frozen source chains with its SQLite fingerprint, MySQL state layout and MySQL wrapper:

  • Adds one NOT NULL column with a writable server default. It rewrites no row, retags no history and synthesizes no archival state; existing Scopes read back writable.
  • Adds no table, index, foreign key or check constraint; v1_5_0_005 keeps its recorded fingerprint.
  • Additive DDL only, so no domain step or backfill and repeated apply/verify stay no-op.
  • release/upgrade-support.json schema review updated with the new persistence digest and rationale; both locale migration docs and the release notes enumerate the new head.

Validation

uv run pytest tests/builtin tests/test_scope_api.py tests/test_access_control.py -q -p no:randomly
  -> 3553 passed, 146 skipped
uv run pytest tests/e2e/test_builtin_runtime.py tests/e2e/test_artifact_dreaming.py tests/e2e/test_access_control_http.py -q -p no:randomly
  -> 119 passed, 88 skipped
uv run pytest tests/e2e -q -p no:randomly            # full run, 88% reached before the shell timeout
  -> 0 failures observed
uv run pytest tests/test_release_version.py -q        -> 12 passed
uv run python scripts/upgrade_release_gate.py         -> exit 0
uv run ruff check src/ tests/...                      -> All checks passed
uv run ty check src/                                  -> All checks passed

New tests: tests/builtin/persistence/test_scope_lifecycle.py (cutoff, child independence, stale-version and repeat-request serialization) and tests/builtin/review/test_service.py::test_archived_scope_refuses_a_candidate_that_was_queued_before_the_cutoff (composed-runtime acceptance: a queued Candidate cannot publish after archive).

Gaps / not in this PR

  • Deletion is not implemented. Single-Scope delete-with-children conflict, subtree preview with an explicit authorized set, changed-membership detection, the structural-only delete, access cutoff for reads, persisted operation identity/progress and the idempotent ScopeResourceHandler boundary are still pending. deleting/deleted exist as states and vocabulary only.
  • Cross-store cleanup is not implemented, and physical erasure is not claimed or supported.
  • Read-path cutoff for deletion (ordinary reads, search, Prepare, plugin reads) is not implemented; archive deliberately does not restrict reads.
  • Processing start-time checks are covered indirectly: a queued task's final write is refused by the gate, which is the observable guarantee. No new enqueue-time check was added.
  • The published Scope response does not yet expose lifecycle_state or the archive/reopen endpoints; that is G's contract work.
  • Migration revision v1_5_0_006 is the head of this branch only; H reconciles the final chain.

Deployment

No deployment, merge, credential or HOME-level configuration changes.

AI usage

Implemented with an AI agent (bub / magpie), which read the pinned RFC and repository guidelines, wrote the code and tests, and ran the commands above. All reported results were executed locally in this branch; a human should review the lifecycle semantics and the migration registration.

C lifecycle and others added 12 commits November 16, 2026 20:21
Implements the Scope archive half of RFC oceanbase#2611's archive, deletion and cleanup
section. Archiving a named Scope stops its ordinary content writes at the
boundary that owns them, and leaves its structural children untouched.

- `pc_scopes.lifecycle_state` is a NOT NULL column with a `writable` server
  default, so every existing Scope reads back writable: the revision rewrites
  no row, retags no history and synthesizes no archival state. Registered as
  `v1_5_0_006` on both frozen source chains with the SQLite fingerprint, MySQL
  state layout and MySQL wrapper the chain requires.
- One gate, `require_writable`, reads that row under a lock inside the writer's
  own transaction. It is called from the three real owning boundaries:
  `SourceRepository.add_many_with_status` (Source capture),
  `ArtifactRepository._insert_revisions` (every Artifact revision, which covers
  Create, revise, merge, publication copy and a reviewed Candidate's commit)
  and `CandidateRepository.create_many` (Candidate persistence). No transport
  carries a redundant copy of the check.
- `ScopeApplication.archive`/`reopen` take the existing hierarchy boundary plus
  the current `expected_version`, and advance the version on success, so a state
  change serializes against attach/move and against a stale reader.
- Archive keeps grants, context references and read authority, so an external
  Scope with a valid grant still reads archived evidence; reopen retains the
  Scope ID.

Tests cover the user-visible cutoff: a queued Candidate proposed before archive
cannot publish afterwards, and children stay writable.
…tryable cleanup

Implements the deletion half of RFC oceanbase#2611's Scope archive, deletion and cleanup
section on top of the archive slice.

Three explicit steps, because a deletion that acts on a set the requester never
saw is not explicit:

- `preview(selection)` resolves the exact structural set from parent edges only
  and returns it with a digest over `(scope_id, parent_scope_id, version)`.
- `confirm(selection, digest, single_scope=...)` re-resolves inside the existing
  hierarchy boundary and refuses a set that changed by attachment, move or
  metadata update; `single_scope` conflicts while children exist. It then refuses
  unresolved deployment defaults and persistent bindings, cuts access, and
  records the operation, confirmed set and per-resource progress.
- `cleanup(operation_id)` runs each unfinished handler; a failure records a stable
  code and stays retryable, and the members remain non-writable so an incomplete
  cleanup never restores reads.

Access cutoff is the existing `pc_scopes.lifecycle_state`, read at one serving
boundary (`_scope_operation`) for every scoped read and write, so ordinary reads,
historical readback, search, Prepare and plugin reads stop at the same point as
writes. Archive still keeps reads available.

Cleanup is a minimal boundary, not a workflow system: one idempotent
`purge(connection, scope_id)` over the owned tables, derived from the schema
rather than restated, and never following Context References or lineage into
another Scope. An unsupported cleanup mode is refused before acceptance, so no
partial delete is presented as success and no erasure is claimed.

Tests cover the observable path end to end: a confirmed subtree delete, a
single-Scope conflict with children, attach and move invalidating a confirmation,
binding repair required first, a failed cleanup staying unavailable and
retryable, an unsupported mode refused before the cutoff, the runtime refusing
ordinary reads and writes after deletion, and a surviving Scope keeping its own
revision intact.
Three archive defects were reproduced through public runtime operations at
11dcf84 and are fixed at their owning boundaries rather than per transport.

- A tag Candidate is proposed into a Scope and committed by writing tags.
  `CatalogCandidateRepository._version` and
  `RelationalTagService.replace_in_transaction` now share the one lifecycle
  gate, so a tag Candidate can be neither proposed nor approved after the
  cutoff, and a direct tag replacement is refused too.
- `CandidateRepository._insert_version` is the single path for every stored
  Candidate version, so a revision of an already queued Candidate is refused
  after the cutoff instead of advancing its head.
- Portable export/restore carries `pc_scopes.lifecycle_state` in a new scope
  record schema version 2, so restoring an archived Scope no longer silently
  reopens it. Bundles from the previous schema stay supported through an
  explicit `earlier_defaults` declaration: before the field existed every Scope
  was writable, and that historic meaning is stated rather than guessed. A
  bundle that carries an archived state can never lose it, and the state is
  inside the record digest so an archived and a writable Scope with equal
  metadata no longer collide.

Deletion boundaries reported at the same head are fixed too:

- Creating a child under a `deleting` Scope, binding or defaulting to it, and
  moving another Scope into it are refused on the existing hierarchy
  transaction, so a confirmed set cannot gain members or bindings after its
  cutoff. Nothing that arrived late is deleted to force completion.
- Finalization no longer raises a raw IntegrityError out of `cleanup`: a
  remaining reference is recorded against the operation so it stays incomplete,
  visible and retryable, and inbound references are cleared once more at
  finalization so a surviving Scope keeps no dangling reference.

Archive still keeps authorized reads and child independence.
Add ScopeApplication.resolve_range with explicit node and depth budgets.
Structural descendants come from parent edges, so a narrow range no longer
reads every Scope descriptor, and Context References or lineage never expand
membership. Budget exhaustion raises instead of returning a partial set, and
the result carries per-member versions plus a membership digest for later
confirmation.
Adopts A's accepted bounded resolver (8ece2d0) as a real dependency instead
of keeping a parallel range helper.

- `preview` and the locked `confirm` link now resolve through
  `ScopeApplication.resolve_range`, so structural membership comes from parent
  edges, a narrow range no longer reads every Scope descriptor, and the
  confirmation digest is A's single `membership_digest` over
  `(scope_id, parent_scope_id, version)`. The duplicate digest helper this
  branch carried is removed.
- The node and depth budgets are an explicit contract on
  `ScopeDeletionApplication`: exceeding either raises
  `ScopeRangeLimitError` before any cutoff, so a deletion never acts on a
  truncated set. `mode="all"` is refused by the resolver rather than by an
  ad-hoc check here.

Two focused regressions cover the merge: deletion preview still refuses an
over-budget range without changing any member's state, and A's scope range
suite passes unchanged alongside the deletion suite.
… access

A full-repository `ty check` (not src-only) reported five diagnostics at
66d0730, all in tests that reach an optional runtime capability without
narrowing it, plus one real annotation gap this exposes:

- `BuiltinRuntime.scope_deletions` was inferred as `None | Any` because the
  class came through the package's lazy `__getattr__`. It is now annotated with
  the concrete `ScopeDeletionApplication` imported from its owning module. The
  lazy export stays, because `scope.deletion` reaches
  `persistence.scope_lifecycle`, which imports `scope.errors`; an eager package
  import would create a cycle, and the runtime behaviour is unchanged.
- The two test sites narrow with the pattern this repository already uses
  (`assert runtime.scopes is not None`) and then use the typed reference, so the
  two pre-existing `# type: ignore[union-attr]` comments are removed rather than
  joined by more. No cast, no `assert False`, no production change to hide an
  error, and every assertion still checks the same observable behaviour.

`uv run ty check` over the whole repository now passes.
Three of the four blocking findings from the 2f5b71b review are fixed at the
boundary that owns each one. The fourth now has a concrete dependency contract
instead of a workaround.

- Removal order comes from parent edges, not from the confirmed order or lexical
  ids. An `exact` selection returns members sorted by `scope_id`, so a child whose
  id sorted first was removed after its parent and `pc_scopes.parent_scope_id`
  (RESTRICT) blocked finalization forever — 24 of 60 rounds with shipped ids.
  `removal_order` walks the set's own parent edges deepest-first, so both id
  orders converge while the confirmed membership, digest and ids stay untouched.
- `single_scope=True` now enforces its size contract: a confirmed set of anything
  but one member is refused before the cutoff, including a parent together with
  its own child. Previously three unrelated roots were removed, or the parent and
  child pair executed and stuck.
- `complete` now means this Scope's own content is gone. The atomic-memory index,
  the approved-head lexical index and the retained evidence modules keep tables in
  their own schemas outside `BUILTIN_TABLES`, so they were never removed and the
  operation reported success over live content. Each owner gained a scoped
  `purge_scope` and a composing handler asks the owners, rather than the Scope
  service guessing at their columns and deleting by match. A store that cannot
  answer records a normal failure and stays visible and retryable. The deletion
  operation and progress rows are body-free evidence and are deliberately kept.
- Read cutoff covers the two ordinary reads that bypassed it: publishing reads a
  source Artifact, and portable export copies Scope content wholesale. Both now
  consult lifecycle at the owning boundary. An `archived` source stays publishable
  and exportable, because archive stops writes and explicitly keeps reads; only a
  `deleting`/`deleted` Scope is unavailable. Publication into a non-writable target
  is refused in the same check.

Deletion now composes the handler set the runtime actually owns, so a Runtime
without an index never claims to have cleaned tables it does not know about.

Publication-origin purge stays open: a survivor's `pc_artifact_publications` row
names the origin Artifact through a RESTRICT FK, and deleting that survivor row to
force a purge would destroy immutable provenance. The required outcome needs a
content-free origin address at that boundary, which is a schema and
owner-contract decision owned by H with F. The concrete contract and the current
retryable, non-complete behaviour are documented rather than waived.
…vely

Two defects inside the previous repair, both reachable through public
constructors with shipped defaults.

- `ScopeDeletionApplication(db, scopes)` still built `default_handlers()` without
  the projection owners, so it accepted a deletion and reported `complete` while
  the Scope's Atomic Memory text remained stored and the Scope row was already
  gone — the exact false-completion shape, narrowed to the class default. The
  required handler names are now declared and `confirm` refuses before the access
  cutoff with `MissingScopeResourceHandlerError` naming what is missing, so the
  Scope stays writable and no content is orphaned behind a success. The composed
  runtime is unaffected and still supplies real owners; the constructor keeps its
  signature rather than hiding the gap.
- `removal_order` walked recursively once per member depth, so a budget-legal
  `exact` set of 1000 members raised `RecursionError` *after* the cutoff.
  `confirm` returned no receipt and every retry re-crashed, leaving all 1000
  Scopes `deleting` forever. The ordering is now an iterative post-order walk
  bounded by the confirmed set size, with no raised recursion limit, no reduced
  node budget and no new depth cap on exact membership. It reads only the
  confirmed parent edges, so a parent outside the set is never deleted.

The new tests exercise the branches that were not covered: the default
constructor without any handler argument (not an explicit complete set), and a
1000-node exact chain in both lexical orders converging to `complete` with an
idempotent retry. Both fail on the previous head — `ImportError` for the absent
contract and `RecursionError` for the walk — and pass here.
…letion

`confirm` refused a handler set that could not cover the required owners, but
`cleanup(operation_id)` trusted whatever progress rows the operation had recorded
at confirm time. An operation persisted by an earlier build with a shorter set
therefore finalized `complete` under a complete handler set: the Scope row was
deleted and its Atomic Memory text, FTS shadow and description remained stored
and unreachable. Reproduced publicly — a pending short-recorded operation,
resumed by a service holding the full set, returned `complete` with
`pc_atomic_memory_current` still holding the plaintext.

Coverage of the *recorded* work is now checked before any member metadata is
destroyed, per confirmed member so one member's rows cannot mask another's:

- `recorded_coverage` reports each (member, required handler) the operation never
  recorded. A gap keeps the operation `cleanup_pending` with the members still
  unavailable and the Scope metadata intact, so the residue stays reachable and
  no false `complete` is issued. No progress row is rewritten and no missing task
  is stamped done.
- `repair_coverage` is the explicit, bounded repair: it adds one **pending** row
  per missing required handler, keeps every existing row's identity, state and
  attempts, and clears the recorded blocker. `cleanup` then has to actually run
  the initialized owner for that row to become `done`, and only a real purge
  completes the operation. The operation id, confirmed members and historical
  evidence are preserved, and a genuinely completed operation stays idempotent
  rather than being reopened.

Default-refusal and iterative ordering are unchanged, and a full recorded set
still recovers through the ordinary retry.
Three bounded correctness corrections in the recorded-coverage guard added last
commit. The legacy short-set refusal, the explicit pending repair and every
ordinary path are unchanged.

- `recorded_coverage` grouped nothing: its inner comprehension iterated the whole
  operation's progress for every member, so any member holding one row received
  the union and could not report a missing owner. The docstring and handoff
  claimed per-member checking, which was therefore false. Rows are now grouped
  once by the member they belong to and each confirmed member is compared against
  its own rows, including a member with no rows at all. Grouping once also makes
  the check linear in the row count instead of rebuilding the set per member.
  An asymmetric record — one member with the full set, another missing an owner —
  now refuses before finalization and keeps both members' live residue and Scope
  rows.
- Repair cleared `last_error_code` on every row of the operation, erasing a row's
  own failure reason before its work ever succeeded. It now clears only the
  coverage blocker it replaces, and marking no longer overwrites an existing
  failure code, so a real `IntegrityError` survives with its state and attempts
  until the work actually succeeds.
- Two concurrent repairs of one operation raised a raw duplicate-key
  `IntegrityError`. Repair is a supported recovery step, so a lost race now rolls
  back and rereads: if the concurrent attempt recorded the same work the receipts
  converge on one pending row, and any other integrity failure still surfaces.

Tests cover the union masking against real Atomic Memory content in both members
through actual cleanup and finalization, the preserved diagnostic across a repeat
repair, and one bounded concurrency case. All three fail on the previous head.
A deletion operation carried no requester, so once its members were physically
removed there was no live Scope left to authorize against. That pushed the wire
layer into substituting `server.observe`, which made observation destructive and
left the real member manager unable to read or retry their own operation.

The operation now records who confirmed it, and every action re-checks current
authority rather than trusting the record:

- `confirm` takes the authenticated principal and an authorizer supplied by the
  transport, and requires `scope.admin` on **every** confirmed member, AND-ed.
  Observation is not among the checks, so an observer cannot confirm, read or
  resume, and a manager holding authority on only one member is refused. The
  check runs before the access cutoff, and the digest is re-verified inside the
  write transaction so a set that changed in between is still refused.
- `cleanup`, `repair_coverage` and `operation` apply the same gate before acting,
  so revocation takes effect before any further destructive step and status is
  never admitted by observation alone.
- The attestation (principal plus the exact checked members) is stored in the
  existing canonical `confirmed_scopes` document, so no schema change is needed
  and no migration revision is claimed from H. A record written before this
  change stays a bare member list and decodes as unattested.
- Terminal readback after the members are gone is limited to exactly the
  attested requester. That is a bounded choice, not a global role: it grants no
  content access, cannot resurrect a Scope, and cannot authorize a new deletion.
- A legacy record with no attestation is refused for every principal and keeps
  its members unavailable; no owner is back-filled, because that would fabricate
  authority.

`trusted_local` mirrors the Runtime's existing contract for an in-process caller
whose owner already made the access decision; it defaults to false and does not
record a fake requester, so its operations stay unattested at terminal readback.
…eration

Three corrections to the deletion authority gate. The accepted foundation and
`5539dfad5` are unchanged; this is a separate delta on top of it.

- Half a check is never a check. `requester is None or authorize is None` let a
  presented principal with a forgotten authorizer fall through to local trust and
  record a fabricated `service:local`, which any transport principal could then
  claim. Exactly one argument is now refused outright, on trusted and untrusted
  services alike, and no synthetic identity or empty check list is ever created.
  A trusted embedding records **no** attestation at all, so it is genuinely
  unattested rather than impersonating a service principal.
- The trusted path is an explicit declaration, not a bare flag. `trusted_local`
  is replaced by `TrustedEmbedding(owner)`, passed once at construction by the
  owning composition; a single call cannot elect to trust itself. With none
  declared, every action requires a real requester and authorizer.
- No identity means no operation. The terminal branch used to return the stored
  attestation without comparing any caller to it, so an unauthenticated
  in-process call could read a completed operation — including its members,
  requester and digest — and run `cleanup`. An attestation is evidence, not
  authentication; a caller must present a principal that matches the record.
- Terminal authority comes from the exact operation the caller loaded, never from
  membership. `deletion_covering` resolved the operation by `root_scope_id IN
  members` and returned `rows[0]`, so one operation's requester could read
  another's. That helper is deleted; each call site passes its own record's
  attestation.

Revocation semantics are now documented for what they are: authority is admitted
per invocation, so a revocation stops the next call but does not interrupt work
already admitted inside a running one. Cleanup is resumable and non-atomic, and
the membership digest is a set-equality check, not an authorization snapshot. No
atomic mid-call cutoff is claimed.

Tests cover both-absent, each half-absent on a trusted service, no fabricated
identity, strict terminal refusal without a subject, and two operations over one
member set keeping their own requesters with real canonical bindings. Ablation of
the old OR-gate reproduces the fabricated `service:local` and fails both new
tests behaviourally, not by import error.
@PsiACE

PsiACE commented Nov 17, 2026

Copy link
Copy Markdown
Owner Author

Closing this component/prototype PR under the RFC oceanbase#2611 scope cleanup. It is not a merge target in the retained integration stack. The branch and all commits are retained as source material; any required behavior must be extracted once into the minimal, master-based architecture rather than merged as an additional parallel implementation. This closure does not discard the ongoing bounded correctness work, approve the current architecture, or authorize reopening/expanding the stack.

@PsiACE PsiACE closed this Nov 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant