beads/journalops/journal.go
Julian Knutsen f624530287
fix(events): journal delete and cascade dep_remove rows carry the request actor; notice when reading a disabled journal (#5985) (#6061)
* fix(events): thread the request actor through the issueops delete door

`bd delete --actor A` journaled its `delete` row and every cascade
`dep_remove` row with actor='' — the #5985 finding. The actor was in hand
at the role body (DeleteInTx already passes req.Actor to the reference
rewrite) and dropped one call below it.

Widen the delete workers with an explicit `actor string` parameter, the
house style PR #5908 used for the rest of the journal (never ambient
context): DeleteResolvedSetInTx, DeleteIssue(s)InTx, deleteIssueRowInTx,
and the RecordDependencyRemovals* family. DeleteInTx passes req.Actor and
SweepInTx passes SweepRequest.Actor, so sweep deletions become attributable
for free.

The genuinely actorless system surfaces — storage.DeleteIssue(s),
Tx.DeleteIssue, the dolt wisp deletes, the source-repo wipe behind
`bd repo remove` — pass "" explicitly, which the 0066 contract reads as
system/unknown. Their comments now say why rather than claiming the
plumbing cannot carry an actor.

No storage.Storage interface change and no migration: 0066 already added
`actor VARCHAR(255) NOT NULL DEFAULT ''`.

The domain/db repository call sites keep their existing "" for now; the
next commit threads the UOW door's actor to them.

Refs #5985

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(events): thread the request actor through the domain repository delete seam

The UOW door (proxied-server `bd delete`, HTTP API deleteIssues, `bd sweep`
over a unit of work) had the actor as far down as domain.deleteMany and lost
it at the repository interface, so its `delete` and cascade `dep_remove` rows
landed with actor=''.

Widen the seam the way PR #5908 widened IssueRepository.MovePersistence, for
the same reason: an explicit trailing `actor string` on
IssueSQLRepository.Delete / DeleteByIDs and DependencySQLRepository.
DeleteAllForIDs. deleteMany passes the actor its use case was already given,
so DeleteIssue / DeleteWisp / DeleteIssues / DeleteWisps keep their surfaces
unchanged and both doors now agree.

No variadic and no default: a new caller has to say whose delete this is, or
say "" and mean it.

Refs #5985

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(events): say when the journal being read is disabled; correct the actor docs

Zero rows is indistinguishable from caught-up. A consumer polling a workspace
whose writers never enabled the journal gets a successful, empty read forever
and concludes it is up to date — the "nothing to read and no way to tell why"
trap behind the field report's "0 rows" claim, which was default-off
activation and not a write-path gap.

`bd events export` and `bd events tail` now print a one-line stderr notice when
the target workspace resolves to disabled, and still serve whatever rows exist:
exporting the ledger a now-disabled workspace recorded while it WAS enabled is
legitimate, so this is a notice and not a refusal. It is the CLI mirror of the
HTTP API's EventsJournalDisabled 409, which can refuse because it has no
historical-export case. stderr, not the JSONL stream, and the exit code is
unchanged.

The default stays off. Flipping it changes write amplification and retention
for every workspace, which is not release-branch material.

Also fixes two now-false statements about attribution — the `bd events tail`
record contract and the docs page both said deletes never carry an actor — and
documents the requirement that every WRITER workspace enable the journal, not
just the one a consumer reads.

The golden gains the delete/dep_remove attribution, regenerated deliberately.
It keeps an actorless delete alongside the attributed one: the fixture used to
be the only evidence a consumer had, and reading it as "deletes are never
attributed" would mis-resolve every delete conflict.

Refs #5985

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(events): pin delete/cascade attribution at the DB on every plumbing

Four levels, because the drop happened at a seam no single one of them can
see:

- internal/storage/dolt: a ROLE-path delete (store.Deleter(), Force, an
  explicit actor) reads back `deleter-1` on both the delete row and the
  cascade dep_remove row. The store.DeleteIssue stanza in
  TestEventsJournal_ActorAttribution keeps asserting '' and its comment now
  says WHY — that surface is the actorless system interface, so the pin is
  meaningful instead of aspirational.
- internal/storage/domain/db: the repository seam itself — Delete,
  DeleteByIDs and DeleteAllForIDs each journal under the actor they are
  handed — plus the cascade through the use case. journalRow gains Actor, so
  the existing suite can see the column at all.
- internal/storage/uow: the same promise through the unit-of-work Deleter,
  the door #5908's review caught drifting once already.
- internal/storage/embeddeddolt: a per-op matrix over the DEFAULT LOCAL
  WORKSPACE. One mutation of every journaled kind, asserted at the DB, both
  directions — every attributed op names its actor, and the only rows that
  may carry none are the derived is_blocked updates.
- cmd/bd: #5985's repro verbatim through the real binary, and the
  disabled-journal notice (present on export and tail, on stderr, absent
  when enabled).

Also corrects the two remaining "actorless delete plumbing" claims in the
journalops.Row and issueops.RecordEventInTx contract comments.

Closes #5985

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(events): fix the CLI repro's flag and read stdout where stderr now speaks

`bd delete` has no --yes; --force is what makes it a real delete rather than
a preview.

TestRoutedCreateJournalsIntoTheTargetWorkspace asserted "the launching
workspace journaled nothing" against COMBINED output, which the new
disabled-journal notice now legitimately writes to. Its subject is journal
ROWS, so it reads stdout.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-29 04:14:23 -07:00

121 lines
6.2 KiB
Go

package journalops
import "context"
// Row is one raw record of the durable mutation journal.
//
// IssueJSON is empty when the op is a delete (no surviving row to snapshot);
// DepJSON is empty for non-dependency ops; CommentJSON is empty for non-comment
// ops. TS is the insert-time timestamp, stamped inside the committing
// transaction and normalized to a string.
//
// TS IS NOT MONOTONE IN SEQ, and a consumer that sorts by it is wrong. It is
// client-stamped, so two writers against one SQL server — or one writer whose
// clock steps back — can commit seq N with a later TS than seq N+1. Seq is the
// order; TS is a label. The retention floors resolve the same way, to a seq
// bound rather than a per-row age test, for exactly this reason.
//
// Actor is the acting identity that performed the mutation, as resolved for
// the audit-events table. A delete, and the dep_remove rows a cascading delete
// produces, carry the identity that REQUESTED the delete. It is empty only
// when the path genuinely has no actor: derived maintenance, system cleanup
// with no request behind it, and rows written before the column existed.
type Row struct {
Seq int64
TS string
Op string
IssueID string
Actor string
IssueJSON string
DepJSON string
CommentJSON string
}
// Page is one journal read that also reports how far behind the caller is: the
// rows it asked for, and the head of the journal's history at the moment they
// were read.
//
// The two travel together because they are only meaningful together. Rows alone
// cannot answer "poll again now, or wait?" — a full page might be the end of the
// journal or the first thousand of a hundred thousand — and a head read
// separately could be taken from a different instant and land BELOW the last row
// served, which a consumer reads as "past the end" and stalls on.
//
// Head is the highest seq the counter has ever assigned. It never decreases
// under a prune, so it is the journal's HISTORY rather than its CONTENTS: a
// fully pruned journal reports its rows gone and its head unchanged. Deriving
// it from the rows in hand would make it a fact about the page instead, which
// reads as "caught up" at the end of every bounded read.
type Page struct {
Rows []Row
Head int64
}
// Journal is the workspace's durable mutation journal, read as pages from a
// caller-held checkpoint — see the package doc for what that plane is and why
// its retention and activation are not on this role.
//
// IT IS ONE ROLE WITH ONE METHOD, and being born with one is the point rather
// than an accident of what shipped first. The plane's other verbs are operator
// decisions the read holder is deliberately not entitled to, so there is no
// second shape of this question waiting to be appended: `bd events prune` and
// the per-instance activation switch answer to storage.EventsJournalAccessor
// and storage.EventsJournalConfigurer, which the workspace holds and a
// publishing surface does not.
//
// The read/write entitlement test the role rule applies (can one caller be
// entitled to the read and not the write?) comes back YES here, loudly, which
// is why the split exists at all: `bd serve` publishes GET /v0/beads/events and
// documents that it never retains, so handing it a delete would make that
// documentation the only thing standing between a consumer's checkpoint and a
// prune.
//
// Result values are unspecified when error is non-nil — in particular a
// truncation carries its window in the ERROR and not in a partial Page, so a
// caller that ignores the error and reads Rows gets nothing rather than a
// plausible-looking suffix. Implementations never mutate caller-owned values,
// having none to mutate.
type Journal interface {
// ReadEventsJournalPage returns the journal records after the caller's
// checkpoint, with the head of the journal's history.
//
// SINCE IS EXCLUSIVE. The answer is the records whose seq is strictly
// greater than since, so a consumer stores the seq it last processed and
// hands back exactly that, with no arithmetic and no risk of an off-by-one
// replay. A since of 0 therefore means "from the beginning of history",
// because seq starts at 1.
//
// ROWS ARE SEQ-ASCENDING, and gapless within one answer. Seq is drawn from
// a counter inside the mutation's own transaction rather than assigned at
// insert, so the order rows are served in is the order they COMMITTED in —
// which is the order a replay has to apply them in, and is not what an
// AUTO_INCREMENT would have given.
//
// LIMIT CAPS THE ROWS AND NOT THE HEAD. A limit of 0 means uncapped: this
// role imposes no ceiling of its own, because the caller that pages a
// hundred thousand records out to a file is as legitimate as the one
// polling for ten. A FRONT DOOR may impose one — the HTTP handler behind
// GET /v0/beads/events caps its page, and that cap is the HANDLER's promise
// to its clients, stated on the operation — and a bounded page still
// reports the journal's head, which is how the caller learns there is more.
//
// HEAD COMES FROM THE SAME TRANSACTION AS THE ROWS, and is read after them.
// Reading it first would let a mutation commit in between and yield a head
// BELOW the last row served; taking it from a separate transaction would
// allow the same thing. This order can only report a head equal to or ahead
// of the last row returned, which a poller acts on correctly either way.
// Head never decreases across calls, prune included.
//
// A CHECKPOINT AT OR ABOVE HEAD IS CAUGHT UP: no rows, the head, and a nil
// error. That is the answer a poller gets on a quiet workspace and the
// answer it gets at the end of a fully pruned journal, and it is
// deliberately the same answer, because both mean "there is nothing after
// your checkpoint".
//
// A CHECKPOINT BELOW THE RETAINED WINDOW IS A TYPED FAILURE: the returned
// error matches errors.As against *TruncatedError, carrying the window the
// implementation can still serve. Resuming from that window's Floor-1
// succeeds and yields the retained records; the caller decides between that
// gap and a rebuild, and no implementation decides for it. See TruncatedError.
ReadEventsJournalPage(ctx context.Context, since int64, limit int) (Page, error)
}