fix(memory): preserve presence for empty values (#5964)

* fix(memory): preserve presence for empty values (#5963)

Recall and Forget now distinguish an existing empty memory row from an absent key across direct, embedded, and UOW storage paths.

Agent-Signature: codex-unknown-model-unknown-reasoning on behalf of sjarmak

* fix(memory): make bd recall report presence from row existence

printRecallResult (and the recallCmd caller) derived "found" from
value != "", so a memory stored as the empty string still printed
"No memory with key" and exited 1 even though the role's
RecallResult.Found was true and bd forget would delete the row.
Thread result.Found through instead: an empty-valued memory now
recalls cleanly (exit 0, empty value; JSON reports found: true), and
only an absent key is a miss.

Addresses maintainer review on #5964 (fixes #5963).

* test(httpapi): pin GET /v0/beads/memories/{key} as 200 for an empty value

TestGetMemoryAnswersAMissWithA404 pinned a RecallResult{Value: ""}
case (Found defaulting to its zero value, false) as a 404, a shape no
backend can produce since Found now comes from row existence rather
than value truthiness. Move that case into its own
TestGetMemoryAnswersAnEmptyValueWith200, which recalls Found: true
and asserts a 200 with an empty value. Also updates the handler's
doc comment, which still described the retired 404-on-empty
behavior.

Addresses maintainer review on #5964 (fixes #5963).

* docs(httpapi): fix openapi spec to say memory presence is row existence

The published spec still said an empty-valued memory is a 404 on
GET /v0/beads/memories/{key} and DELETE /v0/beads/memories/{key},
contradicting the role's RecallResult.Found (row existence). Rewrite
the operation descriptions, both 404 response bodies, Memory.value
and RememberedMemory.replaced to say presence is row existence
everywhere: an empty-string memory is a 200 (or is removed by
forget) with an empty value, matching what GET /v0/beads/memories
already enumerated. Regenerate types.gen.go via `make api-gen` so
the generated doc comments match.

Addresses maintainer review on #5964 (fixes #5963).

* docs(changelog): note the empty-valued memory presence fix

Add an Unreleased/Fixed entry for #5964 (fixes #5963): bd recall,
bd forget and GET /v0/beads/memories/{key} now treat an empty-valued
memory as present everywhere, instead of only on GET
/v0/beads/memories.

* fix(memory): make bd remember <bare-key> recall an empty-valued memory

rememberBareKeyPath decided presence from existing != "", so a bare slug
naming a memory stored as the empty string was refused as "no memory
named" instead of recalled. It now takes the role's Found, matching
printRecallResult, bd forget and the HTTP door.

* test(memory): pin empty-value presence through the real commands

TestPrintRecallResult and TestRememberBareKeyPath call the helpers directly,
so a RunE that went back to deciding presence from value != "" would leave
them green. TestEmbeddedMemory/empty_valued_memory_is_present empties a
memory row beneath bd and runs bd recall, bd remember <bare-key> and
bd forget against it, checking first that bd no longer sees the placeholder.

Two comments in problem.go and one in memories_test.go still said an
empty-valued memory is a 404. The CHANGELOG line now says a key with no row
is a miss, since a forgotten key was once stored.

* build(bazel): add the memoryops dep to the bd_test go_test (make bazel-sync)

memory_embedded_test.go now imports internal/storage/memoryops directly
(storagememoryops.StorageKey, to overwrite a memory row out of band), so
gazelle emits //internal/storage/memoryops on bd_test. cmd/bd/BUILD.bazel
landed on main after this PR branched, so the PR could not carry the dep;
without it, bazel.yml's "BUILD files in sync" step fails in the required
bazel-test lane. Generated by `make bazel-sync`.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(memory): maintainer fixup — adoption review nits

Maintainer fixup for the adopt-pr iteration-1 review of #5964. Both review
lanes approved and the quality scorecard approved at 981; these are its four
non-gating nits, each confined to lines this PR already adds.

- internal/httpapi: TestForgetMemoryOfAnEmptyValuedKeyIs200 pins the DELETE
  door's empty-value 200 the way TestGetMemoryAnswersAnEmptyValueWith200
  pins the read. Guarding the handler's 404 on Value == "" reddens exactly
  this test and nothing else.
- CHANGELOG: the bullet names DELETE /v0/beads/memories/{key} beside GET,
  whose answer changed the same way (404 with the row left standing -> 200
  with the row removed).
- uow: the two new GetAllConfig presence probes in Recall and Forget say why
  they read the whole table, by pointing at Remember's rationale.
- conformance: RunMemoriesEmptyRowIsPresentUntilForgotten runs its
  no-history-on-retry leg last and SKIPs it with a reason when a fixture has
  no CountHistory, as the MemoriesFixture doc promises, instead of passing
  quietly. All three in-tree fixtures wire the hook, so every in-tree run
  is unchanged (19/19 on dolt, embeddeddolt and uow, 0 SKIP).

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(httpclient): report an empty-valued memory as present (base-refresh repair)

Maintainer repair from refreshing #5964 onto main b630f96f5b. Main's #7247
added the HTTP client store (internal/httpclient) after this PR branched,
and its memory role and served conformance leg still treated a memory
stored as the empty string as absent:

- Recall set Found from Value != "".
- The RecallMemory doc said an empty-valued row was a 404.
- TestServedMemoriesRecallConflatesStoredEmptyWithAbsent called
  conformance.RunMemoriesRecallConflatesStoredEmptyWithAbsent, which this
  PR deletes.

The rebase applied cleanly, but the merged tree did not compile.

- internal/httpclient/memories.go: Recall reports Found true on any 200.
  With this PR the wire returns a 404 only for a key with no row; an
  empty-valued row comes back as a 200 with an empty value. Setting Found
  from Value would hide that row again on the HTTP backend. Forget already
  reported Found true on a 200.
- internal/httpclient/wire/writes.go: the RecallMemory doc now says the
  same.
- internal/httpclient/served_memories_deps_test.go: the hm10 served case
  now runs RunMemoriesEmptyRowIsPresentUntilForgotten, the contract case
  this PR adds in place of the one it deletes.

With BEADS_TEST_EMBEDDED_DOLT=1 the served memory tests pass with 0 SKIP.
Reverting the Recall line makes hm10 fail with
`Recall("hm10-stored-empty") = value "" found false, want value "" found
true`.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: sjarmak <t@t.co>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Stephanie Jarmak 2026-10-12 19:28:54 +00:00 • committed by GitHub
commit 559b5de1e2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
24 changed files with 476 additions and 196 deletions

View file

@ -795,6 +795,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
route; the direct and embedded routes are unchanged
([#5861](https://github.com/gastownhall/beads/issues/5861) item 1).
- **`bd recall`, `bd forget`, `bd remember <bare-key>`,
`GET /v0/beads/memories/{key}` and `DELETE /v0/beads/memories/{key}` now
treat an empty-valued memory as present**
([#5964](https://github.com/gastownhall/beads/pull/5964), fixes
[#5963](https://github.com/gastownhall/beads/issues/5963)). Presence used to
be derived from the stored value's truthiness, so a memory written out of
band with an empty string was invisible even though its row existed. `bd
recall` printed "No memory with key" and exited 1, `bd forget` refused to
delete it, `bd remember <bare-key>` refused to recall it, and both HTTP
doors answered 404 (the DELETE leaving the row in place), while
`GET /v0/beads/memories` already enumerated the same row. Presence now comes from row existence on direct Dolt, embedded Dolt and
the proxied backend. An empty-valued memory is found, recalls as an empty
string, and is deleted on the first forget. Only a key with no row is a
miss.
- **`bd doctor` no longer flags a `.local_version` that starts with `v`.** The
canonical spelling of a Go module version — and the string a build stamped
from a Go pseudo-version reports and writes into `.local_version` itself —

View file

@ -233,14 +233,11 @@ func RunMemoriesRememberWithExplicitKeyStoresVerbatim(t *testing.T, ctx context.
}
// RunMemoriesRememberReplacesAndReportsIt pins
// memoryops.RememberResult.Replaced, including the leg that makes it different
// from RecallResult.Found.
// memoryops.RememberResult.Replaced against row presence.
//
// Three legs: a first write reports false, a second reports true and REPLACES
// rather than appends, and a write over an out-of-band EMPTY row reports true
// even though a Recall of that key would have reported Found false. The third
// is the divergence the leaf doc states — Replaced is about the ROW — and it is
// the one a body computing `previous != ""` gets wrong.
// rather than appends, and a write over an out-of-band EMPTY row reports true.
// The third is the one a body computing `previous != ""` gets wrong.
func RunMemoriesRememberReplacesAndReportsIt(t *testing.T, ctx context.Context, fixture MemoriesFixture) {
t.Helper()
neighbors := seedMemoriesAllFourClasses(t, ctx, fixture)
@ -262,7 +259,7 @@ func RunMemoriesRememberReplacesAndReportsIt(t *testing.T, ctx context.Context,
if err := fixture.SetConfig(ctx, "kv.memory."+emptied, ""); err != nil {
t.Fatalf("seed an empty memory row out of band: %v", err)
}
assertMemoriesRecall(t, ctx, fixture, emptied, "", false)
assertMemoriesRecall(t, ctx, fixture, emptied, "", true)
overEmpty := rememberMemory(t, ctx, fixture, memoryops.RememberRequest{Key: emptied, Content: "now it has content"})
if !overEmpty.Replaced {
t.Fatalf("Remember over a row stored EMPTY reported Replaced false: Replaced is about the row, " +
@ -374,8 +371,8 @@ func RunMemoriesRecallAnswersTheStoredValue(t *testing.T, ctx context.Context, f
}
// RunMemoriesRecallReportsAMissAsNotFoundNotAnError pins the decision recorded
// in memoryops/errors.go: there is no ErrNotFound on this role, because the
// seam beneath it cannot see the difference the error would claim.
// in memoryops/errors.go: absence is a result callers inspect, not an
// operational error they must classify.
func RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t *testing.T, ctx context.Context, fixture MemoriesFixture) {
t.Helper()
seedMemoriesAllFourClasses(t, ctx, fixture)
@ -401,33 +398,70 @@ func RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t *testing.T, ctx context
}
}
// RunMemoriesRecallConflatesStoredEmptyWithAbsent pins
// memoryops.RecallResult.Found's central claim, and the one asymmetry that lets
// a caller see past it: List enumerates the key, because the ROW exists.
// RunMemoriesEmptyRowIsPresentUntilForgotten pins presence to the ROW rather
// than to whether its value is non-empty. No front door creates an empty
// memory, but out-of-band config writes and older workspaces can contain one,
// and it must remain addressable through Recall and Forget.
//
// That is the same same-answer-different-row shape the settings contract pins
// for `bd config get`, and stating it is what keeps a backend from "fixing" it
// on one leg and making the answer depend on the route.
func RunMemoriesRecallConflatesStoredEmptyWithAbsent(t *testing.T, ctx context.Context, fixture MemoriesFixture) {
// The second Forget is the retry leg: after the first call deletes the row, it
// reports a genuine miss and records no further history.
func RunMemoriesEmptyRowIsPresentUntilForgotten(t *testing.T, ctx context.Context, fixture MemoriesFixture) {
t.Helper()
seedMemoriesAllFourClasses(t, ctx, fixture)
neighbors := seedMemoriesAllFourClasses(t, ctx, fixture)
emptied := fixture.IssuePrefix + "-stored-empty"
never := fixture.IssuePrefix + "-never-stored"
if err := fixture.SetConfig(ctx, "kv.memory."+emptied, ""); err != nil {
t.Fatalf("seed an empty memory row out of band: %v", err)
}
assertMemoriesRecall(t, ctx, fixture, emptied, "", false)
assertMemoriesRecall(t, ctx, fixture, emptied, "", true)
assertMemoriesRecall(t, ctx, fixture, never, "", false)
plane := listMemories(t, ctx, fixture, "")
if value, ok := plane[emptied]; !ok || value != "" {
t.Fatalf("List[%q] = %q (present=%v), want an empty value that IS enumerated: "+
"the row exists even though Recall denies it", emptied, value, ok)
t.Fatalf("List[%q] = %q (present=%v), want an enumerated empty value", emptied, value, ok)
}
if _, ok := plane[never]; ok {
t.Fatalf("List carries %q, which nothing stored", never)
}
first := forgetMemory(t, ctx, fixture, emptied)
if !first.Found || first.Value != "" {
t.Fatalf("first Forget(%q) = %+v, want Found true with the empty stored value", emptied, first)
}
assertMemoriesRawAbsent(t, ctx, fixture, "kv.memory."+emptied)
assertMemoriesNeighborsSurvived(t, ctx, fixture, neighbors)
var afterFirst int
if fixture.CountHistory != nil {
var err error
afterFirst, err = fixture.CountHistory(ctx)
if err != nil {
t.Fatalf("CountHistory after first Forget: %v", err)
}
}
second := forgetMemory(t, ctx, fixture, emptied)
if second.Found || second.Value != "" {
t.Fatalf("second Forget(%q) = %+v, want Found false with no value", emptied, second)
}
assertMemoriesRawAbsent(t, ctx, fixture, "kv.memory."+emptied)
assertMemoriesNeighborsSurvived(t, ctx, fixture, neighbors)
// The no-write half of the retry is the only leg that needs history, which
// is why it comes last: a backend that cannot observe history has run every
// other leg by here, and SKIPS this one with that reason, as the
// MemoriesFixture.CountHistory doc promises, rather than passing quietly.
if fixture.CountHistory == nil {
t.Skip("this backend cannot observe history, so the no-write half of the retry is unobservable here")
}
afterSecond, err := fixture.CountHistory(ctx)
if err != nil {
t.Fatalf("CountHistory after second Forget: %v", err)
}
if afterSecond != afterFirst {
t.Fatalf("history entries went %d -> %d across the second Forget, want no write", afterFirst, afterSecond)
}
}
// RunMemoriesForgetRemovesExactlyTheNamedRow IS THE QUADRANT CASE, and the
@ -528,13 +562,7 @@ func RunMemoriesForgetReportsTheForgottenValue(t *testing.T, ctx context.Context
// RunMemoriesForgetOfAnAbsentKeyIsNotFoundAndDeletesNothing pins that a miss is
// a RESULT and not an error, that it changes no row anywhere in the table, that
// the second call — the one a retrying caller actually makes — answers the same
// way, and that the SECOND kind of miss behaves like the first: a memory stored
// as the empty string is Found false, and its row is left standing.
//
// That last leg is memoryops.ForgetResult.Found's parenthesis, and it keeps
// Forget's answer and Recall's answer the same statement. A body that deleted
// on "the row is there" rather than on "Recall would find it" would report
// nothing removed while removing something.
// way.
//
// The whole-table row count is the assertion that matters: "the key is still
// absent" would pass on a delete that swept a neighboring plane.
@ -542,10 +570,6 @@ func RunMemoriesForgetOfAnAbsentKeyIsNotFoundAndDeletesNothing(t *testing.T, ctx
t.Helper()
neighbors := seedMemoriesAllFourClasses(t, ctx, fixture)
key := fixture.IssuePrefix + "-never-stored-forget"
emptied := fixture.IssuePrefix + "-empty-forget"
if err := fixture.SetConfig(ctx, "kv.memory."+emptied, ""); err != nil {
t.Fatalf("seed an empty memory row out of band: %v", err)
}
var before int
if err := fixture.QueryScalar(ctx, "SELECT COUNT(*) FROM config", nil, &before); err != nil {
@ -553,14 +577,12 @@ func RunMemoriesForgetOfAnAbsentKeyIsNotFoundAndDeletesNothing(t *testing.T, ctx
}
for attempt := 1; attempt <= 2; attempt++ {
for _, miss := range []string{key, emptied} {
result, err := fixture.Memories.Forget(ctx, memoryops.ForgetRequest{Key: miss})
if err != nil {
t.Fatalf("Forget(%q) attempt %d = %v, want success with Found false", miss, attempt, err)
}
if result.Found || result.Value != "" {
t.Fatalf("Forget(%q) attempt %d = %+v, want Found false and no value", miss, attempt, result)
}
result, err := fixture.Memories.Forget(ctx, memoryops.ForgetRequest{Key: key})
if err != nil {
t.Fatalf("Forget(%q) attempt %d = %v, want success with Found false", key, attempt, err)
}
if result.Found || result.Value != "" {
t.Fatalf("Forget(%q) attempt %d = %+v, want Found false and no value", key, attempt, result)
}
}
@ -569,11 +591,8 @@ func RunMemoriesForgetOfAnAbsentKeyIsNotFoundAndDeletesNothing(t *testing.T, ctx
t.Fatalf("count config rows after: %v", err)
}
if after != before {
t.Fatalf("config rows went %d -> %d across four forgets that found nothing, want no change", before, after)
t.Fatalf("config rows went %d -> %d across two forgets that found nothing, want no change", before, after)
}
// The stored-empty row is specifically still there: Found false said nothing
// was removed, and that has to be true of the row as well as of the answer.
assertMemoriesRawValue(t, ctx, fixture, "kv.memory."+emptied, "")
assertMemoriesNeighborsSurvived(t, ctx, fixture, neighbors)
// The empty key is a refusal, not a miss.

View file

@ -505,7 +505,7 @@ var roleContractCases = []roleContract{
RunMemoriesRememberRefusesAnUnderivableKey,
RunMemoriesRecallAnswersTheStoredValue,
RunMemoriesRecallReportsAMissAsNotFoundNotAnError,
RunMemoriesRecallConflatesStoredEmptyWithAbsent,
RunMemoriesEmptyRowIsPresentUntilForgotten,
RunMemoriesForgetRemovesExactlyTheNamedRow,
RunMemoriesForgetNeverTouchesTheSettingsPlane,
RunMemoriesForgetReportsTheForgottenValue,

View file

@ -1350,6 +1350,7 @@ go_test(
"//internal/storage/issueops",
"//internal/storage/journalscan",
"//internal/storage/kvkeys",
"//internal/storage/memoryops",
"//internal/storage/schema",
"//internal/storage/uow",
"//internal/storage/versioncontrolops",

View file

@ -217,9 +217,11 @@ func rememberBudgetVerdict(existing map[string]string, key, content string, budg
// `bd remember <bare-slug>` (no --key): a bare slug naming an EXISTING memory
// is recalled instead of stored; a bare slug naming nothing is refused. The
// caller only invokes it when memoryKeyFlag == "" and the insight round-trips
// through memoryapi.DeriveKey unchanged, having already read the key.
func rememberBareKeyPath(key, insight, existing string) error {
if existing != "" {
// through memoryapi.DeriveKey unchanged, having already read the key. As in
// printRecallResult, presence is found (row existence), never existing != "":
// a bare slug naming a memory stored as the empty string recalls it.
func rememberBareKeyPath(key, insight, existing string, found bool) error {
if found {
if jsonOutput {
return outputJSON(map[string]interface{}{
"key": key,
@ -317,22 +319,24 @@ func printForgetResult(key, existing string) error {
}
// printRecallResult renders the `bd recall` output (including the not-found
// SilentExit contract).
func printRecallResult(key, value string) error {
// SilentExit contract). Presence comes from found — ROW EXISTENCE, per the
// role's RecallResult.Found — never from value != "": a memory stored as the
// empty string is found and recalls as "", and only an absent key is a miss.
func printRecallResult(key, value string, found bool) error {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"key": key,
"value": value,
"found": value != "",
"found": found,
}); jerr != nil {
return jerr
}
if value == "" {
if !found {
return SilentExit()
}
return nil
}
if value == "" {
if !found {
fmt.Fprintf(os.Stderr, "No memory with key %q\n", key)
return SilentExit()
}
@ -436,7 +440,7 @@ Examples:
if err != nil {
return HandleErrorRespectJSON("recalling memory: %v", err)
}
return rememberBareKeyPath(derived, insight, recalled.Value)
return rememberBareKeyPath(derived, insight, recalled.Value, recalled.Found)
}
// Corpus budget (memories.budget-chars, OPT-IN, 0 = off). The
@ -653,7 +657,7 @@ Examples:
return HandleErrorRespectJSON("recalling memory: %v", err)
}
return printRecallResult(result.Key, result.Value)
return printRecallResult(result.Key, result.Value, result.Found)
},
}

View file

@ -16,6 +16,7 @@ import (
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
storagememoryops "github.com/steveyegge/beads/internal/storage/memoryops"
)
// countMemoryDoltCommits reads dolt_log for an embedded workspace. It is how
@ -41,6 +42,30 @@ func countMemoryDoltCommits(t *testing.T, beadsDir string) int {
return count
}
// storeMemoryValueOutOfBand overwrites a memory row's value with SQL, beneath
// every bd code path. It is the only way a test gets an empty-valued memory:
// `bd remember` refuses empty content, so such a row always arrives out of band.
func storeMemoryValueOutOfBand(t *testing.T, beadsDir, key, value string) {
t.Helper()
cfg, _ := configfile.Load(beadsDir)
database := ""
if cfg != nil {
database = cfg.GetDoltDatabase()
}
db, cleanup, err := embeddeddolt.OpenSQL(t.Context(), filepath.Join(beadsDir, "embeddeddolt"), database, "main")
if err != nil {
t.Fatalf("OpenSQL: %v", err)
}
defer cleanup()
res, err := db.ExecContext(t.Context(), "UPDATE config SET value = ? WHERE `key` = ?", value, storagememoryops.StorageKey(key))
if err != nil {
t.Fatalf("update memory %q: %v", key, err)
}
if n, err := res.RowsAffected(); err != nil || n != 1 {
t.Fatalf("update memory %q: %d rows affected (err %v), want 1", key, n, err)
}
}
// bdRemember runs "bd remember" with the given args and returns stdout.
func bdRemember(t *testing.T, bd, dir string, args ...string) string {
t.Helper()
@ -283,6 +308,29 @@ func TestEmbeddedMemory(t *testing.T) {
bdRecallFail(t, bd, dir, "forget-me")
})
// AN EMPTY-VALUED MEMORY IS PRESENT (#5963). These run the real commands, so
// they pin each RunE's wiring and not only its renderer: a call site that
// went back to deciding presence from value != "" fails here while
// TestPrintRecallResult and TestRememberBareKeyPath stay green. Its own
// workspace, because the row is emptied beneath bd.
t.Run("empty_valued_memory_is_present", func(t *testing.T) {
edir, ebeads, _ := bdInit(t, bd, "--prefix", "em")
bdRemember(t, bd, edir, "placeholder the test empties", "--key", "stored-empty")
storeMemoryValueOutOfBand(t, ebeads, "stored-empty", "")
// The placeholder check proves bd sees the emptied row. Without it, a
// write bd never read would leave this test green on a reverted fix.
if out := bdRecall(t, bd, edir, "stored-empty"); strings.Contains(out, "placeholder") {
t.Fatalf("bd recall still sees the placeholder, so the row was not emptied: %s", out)
}
// A bare key naming the empty-valued memory recalls it instead of refusing.
if out := bdRemember(t, bd, edir, "stored-empty"); strings.Contains(out, "placeholder") {
t.Fatalf("bd remember <bare-key> still sees the placeholder: %s", out)
}
bdForget(t, bd, edir, "stored-empty")
bdRecallFail(t, bd, edir, "stored-empty")
})
// THE AUTO-COMMIT EPILOGUE, which is the trap this convergence was most
// likely to spring. A direct-route write lands in the Dolt WORKING SET and
// nothing else commits it: durability is the epilogue in main.go, keyed on

View file

@ -3,7 +3,11 @@
package main
import "testing"
import (
"encoding/json"
"strings"
"testing"
)
// TestMatchesKnownCommand guards the `bd remember <subcommand>` misfire fix
// (GH#4401): a bare word that names a real top-level command must be flagged so
@ -39,3 +43,155 @@ func TestMatchesKnownCommand(t *testing.T) {
})
}
}
// TestPrintRecallResult guards the bd-5963 fix: presence must come from
// `RecallResult.Found` (row existence), never from `value != ""`. Before the
// fix, `bd recall` on a memory stored as the empty string printed "No memory
// with key" and exited 1 even though the row was there and `bd forget` would
// delete it — the CLI disagreed with the role and with the HTTP door about
// what "found" means for that row.
func TestPrintRecallResult(t *testing.T) {
t.Run("found with empty value prints the empty value and exits clean", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = false
defer func() { jsonOutput = savedJSONOutput }()
var err error
out := captureStdout(t, func() error {
err = printRecallResult("empty-key", "", true)
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out != "\n" {
t.Errorf("stdout = %q, want a single newline (the empty value)", out)
}
})
t.Run("found with empty value in JSON reports found true", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = true
defer func() { jsonOutput = savedJSONOutput }()
var err error
out := captureStdout(t, func() error {
err = printRecallResult("empty-key", "", true)
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var body map[string]interface{}
if uerr := json.Unmarshal([]byte(strings.TrimSpace(out)), &body); uerr != nil {
t.Fatalf("unmarshal %q: %v", out, uerr)
}
if body["found"] != true {
t.Errorf("found = %v, want true", body["found"])
}
if body["value"] != "" {
t.Errorf("value = %v, want \"\"", body["value"])
}
if body["key"] != "empty-key" {
t.Errorf("key = %v, want %q", body["key"], "empty-key")
}
})
t.Run("found with non-empty value is unchanged", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = false
defer func() { jsonOutput = savedJSONOutput }()
var err error
out := captureStdout(t, func() error {
err = printRecallResult("k", "hello", true)
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out != "hello\n" {
t.Errorf("stdout = %q, want %q", out, "hello\n")
}
})
t.Run("not found prints the miss and exits 1", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = false
defer func() { jsonOutput = savedJSONOutput }()
var err error
stderr := captureStderr(t, func() {
err = printRecallResult("gone", "", false)
})
if !strings.Contains(stderr, `No memory with key "gone"`) {
t.Errorf("stderr = %q, want it to name the missing key", stderr)
}
ee, ok := err.(*exitError)
if !ok || ee.Code != 1 {
t.Errorf("err = %v, want *exitError{Code: 1}", err)
}
})
t.Run("not found in JSON reports found false and exits 1", func(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = true
defer func() { jsonOutput = savedJSONOutput }()
var err error
out := captureStdout(t, func() error {
err = printRecallResult("gone", "", false)
return nil
})
var body map[string]interface{}
if uerr := json.Unmarshal([]byte(strings.TrimSpace(out)), &body); uerr != nil {
t.Fatalf("unmarshal %q: %v", out, uerr)
}
if body["found"] != false {
t.Errorf("found = %v, want false", body["found"])
}
ee, ok := err.(*exitError)
if !ok || ee.Code != 1 {
t.Errorf("err = %v, want *exitError{Code: 1}", err)
}
})
}
// TestRememberBareKeyPath guards the same presence rule on the
// `bd remember <bare-slug>` read path: a bare slug naming a memory stored as
// the empty string recalls it, and only a slug naming nothing is refused.
func TestRememberBareKeyPath(t *testing.T) {
savedJSONOutput := jsonOutput
jsonOutput = true
defer func() { jsonOutput = savedJSONOutput }()
t.Run("found with empty value recalls it", func(t *testing.T) {
var err error
out := captureStdout(t, func() error {
err = rememberBareKeyPath("empty-key", "empty-key", "", true)
return nil
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var body map[string]interface{}
if uerr := json.Unmarshal([]byte(strings.TrimSpace(out)), &body); uerr != nil {
t.Fatalf("unmarshal %q: %v", out, uerr)
}
if body["action"] != "recalled" || body["found"] != true || body["value"] != "" {
t.Errorf("body = %v, want action recalled, found true, empty value", body)
}
})
t.Run("not found is refused", func(t *testing.T) {
var err error
captureStdout(t, func() error {
err = rememberBareKeyPath("gone", "gone", "", false)
return nil
})
ee, ok := err.(*exitError)
if !ok || ee.Code != 1 {
t.Errorf("err = %v, want *exitError{Code: 1}", err)
}
})
}

View file

@ -1563,7 +1563,7 @@ type Memory struct {
// Value The stored content, verbatim: newlines, surrounding space and unicode as stored, never truncated and never withheld.
//
// Always present. It is the empty string only where a row was written out of band with an empty value, which `GET /v0/beads/memories/{key}` answers as a `404` and `GET /v0/beads/memories` enumerates.
// Always present. It is the empty string only where a row was written out of band with an empty value — a row `GET /v0/beads/memories/{key}` answers `200` for, and `GET /v0/beads/memories` enumerates, the same as any other memory.
Value string `json:"value"`
}
@ -1865,7 +1865,7 @@ type RememberedMemory struct {
// Replaced True when a previous value existed under `key` and this request overwrote it; false when the key was new. It is observed in the same transaction as the write, so it describes the row this request wrote.
//
// A previous value that was the EMPTY STRING reports true: the ROW existed, even though `GET /v0/beads/memories/{key}` would have answered `404` for it. That divergence is the storage seam's conflation showing through, and it is stated rather than smoothed over, because smoothing it would mean this member reporting "nothing was there" about a write that overwrote something.
// A previous value that was the EMPTY STRING reports true: the ROW existed, and `GET /v0/beads/memories/{key}` would have answered `200` for it too, with an empty `value` — this member and that endpoint agree on what counts as present, because both read it off the row rather than off the value it happened to hold.
Replaced bool `json:"replaced"`
// Value The stored content, echoed verbatim. Always present, and never withheld — this plane has no redaction; see the operation description.

View file

@ -162,11 +162,10 @@ func (s *Server) handleGetMemory(w http.ResponseWriter, r *http.Request) {
// SilentExit), and the role answers Found rather than a bare value, so the
// status here reports a distinction that exists rather than inventing one.
//
// A row stored as the EMPTY STRING falls on the miss side of it, because
// that is where the role puts it — the storage seam cannot tell it from an
// absent row, and this handler will not claim to see what the role cannot.
// listMemories enumerates such a row, which is the one way a client tells
// the two apart.
// Found is ROW EXISTENCE, not value truthiness. A row stored as the EMPTY
// STRING is found: it comes back as a 200 with an empty `value`, exactly
// like `GET /v0/beads/memories` already enumerates it. Only a key nothing
// stored is a miss.
if !result.Found {
s.fail(w, r, MemoryNotFound())
return

View file

@ -279,41 +279,54 @@ func TestGetMemoryAnswersTheStoredValue(t *testing.T) {
}
// TestGetMemoryAnswersAMissWithA404 is the deliberate divergence from the
// settings surface's no-404 doctrine.
//
// Both legs are the SAME answer from the role — Found false — and both are a
// 404: a row stored as the empty string is a miss here because the storage seam
// cannot tell it from an absent row, and the wire does not claim to see what
// the role cannot. `GET /v0/beads/memories` enumerating such a row is the one
// way a client tells them apart.
// settings surface's no-404 doctrine: a key nothing stored is Found false from
// the role, and the wire reports a 404 rather than the settings plane's silent
// "(not set)" 200.
func TestGetMemoryAnswersAMissWithA404(t *testing.T) {
for _, tc := range []struct {
name string
result memoryops.RecallResult
}{
{name: "nothing stored", result: memoryops.RecallResult{Key: "gone"}},
{name: "stored as the empty string", result: memoryops.RecallResult{Key: "gone", Value: ""}},
} {
t.Run(tc.name, func(t *testing.T) {
ts := newTestServer(t, rolesConfig(Config{Memories: &roleMemories{recalled: tc.result}}))
ts := newTestServer(t, rolesConfig(Config{Memories: &roleMemories{
recalled: memoryops.RecallResult{Key: "gone"},
}}))
resp := ts.get(t, memoriesPath+"/gone")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if got := body["code"]; got != string(CodeNotFound) {
t.Errorf("code = %v, want %q", got, CodeNotFound)
}
if body["request_id"] == nil {
t.Error("no request_id on the problem body")
}
// The detail is about the MEMORY plane. Reusing the issue-id
// sentence would tell a client its memory key was an issue id.
if got, _ := body["detail"].(string); !strings.Contains(got, "memory") {
t.Errorf("detail = %q, want it to name the memory plane", got)
}
})
resp := ts.get(t, memoriesPath+"/gone")
if resp.StatusCode != http.StatusNotFound {
t.Fatalf("status = %d, want 404: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if got := body["code"]; got != string(CodeNotFound) {
t.Errorf("code = %v, want %q", got, CodeNotFound)
}
if body["request_id"] == nil {
t.Error("no request_id on the problem body")
}
// The detail is about the MEMORY plane. Reusing the issue-id sentence
// would tell a client its memory key was an issue id.
if got, _ := body["detail"].(string); !strings.Contains(got, "memory") {
t.Errorf("detail = %q, want it to name the memory plane", got)
}
}
// TestGetMemoryAnswersAnEmptyValueWith200 pins bd-5963's fix: presence comes
// from the role's Found (row existence), never from Value != "". A row
// written out of band with an empty value is a real row — the same one
// `GET /v0/beads/memories` already enumerates — so this door answers 200 with
// an empty value rather than the 404 it used to share with an absent key.
func TestGetMemoryAnswersAnEmptyValueWith200(t *testing.T) {
memories := &roleMemories{recalled: memoryops.RecallResult{
Key: "gone", Value: "", Found: true,
}}
ts := newTestServer(t, rolesConfig(Config{Memories: memories}))
resp := ts.get(t, memoriesPath+"/gone")
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if got := body["key"]; got != "gone" {
t.Errorf("key = %v, want %q", got, "gone")
}
if got := body["value"]; got != "" {
t.Errorf("value = %v, want \"\"", got)
}
}
@ -440,6 +453,32 @@ func TestForgetMemoryOfAnAbsentKeyIs404AndRemovesNothing(t *testing.T) {
}
}
// TestForgetMemoryOfAnEmptyValuedKeyIs200 is the DELETE half of bd-5963's fix,
// pinned at the door as TestGetMemoryAnswersAnEmptyValueWith200 pins the read:
// a row stored as the empty string is Found, so it was removed, and the answer
// is a 200 carrying the empty value it held. A door that keyed its 404 on
// Value == "" would tell a client "there was nothing to remove" about a row it
// had just deleted, and the role's conformance contract could not see it.
func TestForgetMemoryOfAnEmptyValuedKeyIs200(t *testing.T) {
memories := &roleMemories{forgotten: memoryops.ForgetResult{
Key: "stored-empty", Value: "", Found: true,
}}
ts := newTestServer(t, rolesConfig(Config{Memories: memories}))
resp := ts.forget(t, memoriesPath+"/stored-empty")
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d, want 200: %s", resp.StatusCode, readAll(t, resp))
}
body := decodeBody(t, resp)
if got := body["key"]; got != "stored-empty" {
t.Errorf("key = %v, want %q", got, "stored-empty")
}
if got := body["value"]; got != "" {
t.Errorf("value = %v, want \"\"", got)
}
}
// TestForgetMemoryRefusesAKeyItCannotAddress: the door refuses the same keys
// the read refuses, and the role is never reached — which on a DESTRUCTIVE
// operation is the half that matters. A stored key carrying a control
@ -526,9 +565,8 @@ func TestListMemoriesAnswersThePlaneOrderedByKey(t *testing.T) {
"alpha": "first by key",
"Has Spaces.✓": "an explicit key",
// A row written out of band with an empty value. It is enumerated here
// — its KEY exists — while GET /v0/beads/memories/{key} answers 404 for
// it, and that asymmetry is the one way a client tells a row stored
// empty from a row that is not there.
// like any other row, and GET /v0/beads/memories/{key} answers it with a
// 200 and an empty value (TestGetMemoryAnswersAnEmptyValueWith200).
"stored-empty": "",
}}}
ts := newTestServer(t, rolesConfig(Config{Memories: memories}))

View file

@ -1036,8 +1036,9 @@ var operationCodes = map[string][]Code{
// the CLI itself prints identically, so a 404 would publish an invented
// distinction. Here the CLI already distinguishes a miss — `bd recall` has
// an exit-code contract for it — and the role answers Found rather than a
// value, so the 404 reports a distinction that exists. The stored-empty row
// falls on the miss side of it, which the document states.
// value, so the 404 reports a distinction that exists. Found is row
// existence: a row stored as the empty string is a 200 with an empty value,
// and only an absent row is the 404, which the document states.
OpGetMemory: {CodeInvalidArgument, CodeUnauthenticated, CodeNotFound, CodeBusy, CodeDBUnavailable, CodeInternal},
// The read's vocabulary exactly, because the two operations address the same
// resource the same way and this one's Found false is the same answer: a key
@ -1510,10 +1511,9 @@ func EventsWatchSaturated() Result {
//
// A separate constructor rather than a detail argument on NotFound, because the
// two say different things: that one is about the issue id space, and reusing
// its sentence here would tell a client its memory key was an issue id. The
// detail deliberately does NOT distinguish an absent row from one stored as the
// empty string — the role cannot see the difference, so the wire must not claim
// to.
// its sentence here would tell a client its memory key was an issue id. It is
// only ever the answer for an absent row: a row stored as the empty string is
// found, and the read answers it with a 200.
func MemoryNotFound() Result {
return newResult(CodeNotFound, "this workspace holds no memory under that key")
}

View file

@ -5768,10 +5768,10 @@ paths:
A memory stored as the EMPTY STRING is enumerated here, because its key
exists, while `GET /v0/beads/memories/{key}` answers `404` for it. That
asymmetry is the one way a client can tell a row stored empty from a row
that is not there, and it is the storage seam's conflation showing
through rather than a rule this surface invented.
exists, and `GET /v0/beads/memories/{key}` agrees: it answers `200` for
that same row, with an empty `value`. Presence is row existence on both
surfaces, never whether the value happens to be non-empty; only a key
nothing stored is missing from either one.
The envelope is the paginated one and `has_more` is ALWAYS false:
@ -5928,12 +5928,13 @@ paths:
— so a 404 reports a distinction that exists rather than minting one.
A MEMORY STORED AS THE EMPTY STRING IS A 404 TOO. No front door can
create one — storing empty content is refused — but an out-of-band write
to the config table can, and the role does not invent a distinction the
storage seam beneath it cannot see. `GET /v0/beads/memories` DOES
enumerate such a row, because its key exists, and that asymmetry is the
one way a client can tell the two apart.
A MEMORY STORED AS THE EMPTY STRING IS A 200, WITH AN EMPTY `value`. No
front door can create one — storing empty content is refused — but an
out-of-band write to the config table can, and presence here is row
existence, never whether the value happens to be non-empty. That is the
same rule `GET /v0/beads/memories` already followed by enumerating such
a row because its key exists; the two surfaces now agree rather than
splitting on an asymmetry a client would have had to know about.
MEMORY CONTENT IS SERVED IN FULL, and a configured bearer does not
@ -5975,9 +5976,9 @@ paths:
$ref: '#/components/responses/Unauthenticated'
'404':
description: >-
This workspace holds no memory under that key — or holds one stored
as the empty string, which answers the same way. `detail` says which
plane was asked, not which of those two it was.
This workspace holds no memory under that key. A row stored as the
empty string is not this case: it exists, so this operation returns
it as a `200` with an empty `value`, the same as any other memory.
x-bd-codes: [not_found]
content:
application/problem+json:
@ -6059,9 +6060,10 @@ paths:
$ref: '#/components/responses/Unauthenticated'
'404':
description: >-
This workspace holds no memory under that key — or holds one stored
as the empty string, which answers the same way — and NOTHING WAS
REMOVED.
This workspace holds no memory under that key, and NOTHING WAS
REMOVED. A row stored as the empty string is not this case: it
exists, so forgetting it removes it and answers `200`, the same as
any other memory.
x-bd-codes: [not_found]
content:
application/problem+json:
@ -9355,9 +9357,9 @@ components:
Always present. It is the empty string only where a row was written
out of band with an empty value, which
`GET /v0/beads/memories/{key}` answers as a `404` and
`GET /v0/beads/memories` enumerates.
out of band with an empty value — a row `GET /v0/beads/memories/{key}`
answers `200` for, and `GET /v0/beads/memories` enumerates, the same
as any other memory.
MemoriesPage:
type: object
@ -9445,11 +9447,10 @@ components:
A previous value that was the EMPTY STRING reports true: the ROW
existed, even though `GET /v0/beads/memories/{key}` would have
answered `404` for it. That divergence is the storage seam's
conflation showing through, and it is stated rather than smoothed
over, because smoothing it would mean this member reporting
"nothing was there" about a write that overwrote something.
existed, and `GET /v0/beads/memories/{key}` would have answered
`200` for it too, with an empty `value` — this member and that
endpoint agree on what counts as present, because both read it off
the row rather than off the value it happened to hold.
SetSettingRequest:
type: object

View file

@ -66,9 +66,10 @@ func (m *httpMemories) Recall(ctx context.Context, req memoryops.RecallRequest)
if err != nil {
return memoryops.RecallResult{}, err
}
// Found is Value != "": the role conflates a stored empty string with an
// absent memory, and so does the wire, which 404s the same row.
return memoryops.RecallResult{Key: req.Key, Value: res.Value, Found: res.Value != ""}, nil
// Found is about the ROW, not the value: the wire spells a miss as the 404
// handled above, and a row stored as the empty string as a 200 with an
// empty value. Reading Found off Value would hide that row again.
return memoryops.RecallResult{Key: req.Key, Value: res.Value, Found: true}, nil
}
// Forget removes one memory and reports the value it removed.

View file

@ -80,8 +80,8 @@ func TestServedMemoriesRecallReportsAMissAsNotFoundNotAnError(t *testing.T) {
conformance.RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t, t.Context(), newServedMemoriesFixture(t, "hm09"))
}
func TestServedMemoriesRecallConflatesStoredEmptyWithAbsent(t *testing.T) {
conformance.RunMemoriesRecallConflatesStoredEmptyWithAbsent(t, t.Context(), newServedMemoriesFixture(t, "hm10"))
func TestServedMemoriesEmptyRowIsPresentUntilForgotten(t *testing.T) {
conformance.RunMemoriesEmptyRowIsPresentUntilForgotten(t, t.Context(), newServedMemoriesFixture(t, "hm10"))
}
func TestServedMemoriesForgetRemovesExactlyTheNamedRow(t *testing.T) {

View file

@ -558,10 +558,10 @@ func (c *Client) RememberMemory(ctx context.Context, body apigen.RememberRequest
return &out, nil
}
// RecallMemory reads one memory. A miss — including a row stored as the empty
// string — is a 404, which the problem mapper turns into issueops.ErrNotFound;
// the memory role converts that to its own Found-false result, because
// memoryops has deliberately no ErrNotFound.
// RecallMemory reads one memory. A miss is a 404, which the problem mapper
// turns into issueops.ErrNotFound; the memory role converts that to its own
// Found-false result, because memoryops has deliberately no ErrNotFound. A row
// stored as the empty string is not a miss: it is a 200 with an empty value.
func (c *Client) RecallMemory(ctx context.Context, key string) (*apigen.Memory, error) {
path, err := MemoryPath(key)
if err != nil {

View file

@ -55,15 +55,18 @@ func (m *memories) Recall(ctx context.Context, req memoryops.RecallRequest) (mem
if err != nil {
return memoryops.RecallResult{}, err
}
var value string
var (
value string
found bool
)
if err := m.store.withReadTx(ctx, func(tx *sql.Tx) error {
var err error
value, err = storagememoryops.RecallInTx(ctx, tx, key)
value, found, err = storagememoryops.RecallInTx(ctx, tx, key)
return err
}); err != nil {
return memoryops.RecallResult{}, err
}
return memoryops.RecallResult{Key: key, Value: value, Found: value != ""}, nil
return memoryops.RecallResult{Key: key, Value: value, Found: found}, nil
}
// Forget reads the value and deletes the row in ONE transaction, so the value

View file

@ -55,8 +55,8 @@ func TestMemoriesContract(t *testing.T) {
t.Run("RecallReportsAMissAsNotFoundNotAnError", func(t *testing.T) {
conformance.RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t, ctx, fixture)
})
t.Run("RecallConflatesStoredEmptyWithAbsent", func(t *testing.T) {
conformance.RunMemoriesRecallConflatesStoredEmptyWithAbsent(t, ctx, fixture)
t.Run("EmptyRowIsPresentUntilForgotten", func(t *testing.T) {
conformance.RunMemoriesEmptyRowIsPresentUntilForgotten(t, ctx, fixture)
})
t.Run("ForgetRemovesExactlyTheNamedRow", func(t *testing.T) {
conformance.RunMemoriesForgetRemovesExactlyTheNamedRow(t, ctx, fixture)

View file

@ -55,15 +55,18 @@ func (m *memories) Recall(ctx context.Context, req memoryops.RecallRequest) (mem
if err != nil {
return memoryops.RecallResult{}, err
}
var value string
var (
value string
found bool
)
if err := m.store.withConn(ctx, false, func(tx *sql.Tx) error {
var err error
value, err = storagememoryops.RecallInTx(ctx, tx, key)
value, found, err = storagememoryops.RecallInTx(ctx, tx, key)
return err
}); err != nil {
return memoryops.RecallResult{}, err
}
return memoryops.RecallResult{Key: key, Value: value, Found: value != ""}, nil
return memoryops.RecallResult{Key: key, Value: value, Found: found}, nil
}
func (m *memories) Forget(ctx context.Context, req memoryops.ForgetRequest) (memoryops.ForgetResult, error) {

View file

@ -54,8 +54,8 @@ func TestMemoriesContract(t *testing.T) {
t.Run("RecallReportsAMissAsNotFoundNotAnError", func(t *testing.T) {
conformance.RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t, ctx, fixture)
})
t.Run("RecallConflatesStoredEmptyWithAbsent", func(t *testing.T) {
conformance.RunMemoriesRecallConflatesStoredEmptyWithAbsent(t, ctx, fixture)
t.Run("EmptyRowIsPresentUntilForgotten", func(t *testing.T) {
conformance.RunMemoriesEmptyRowIsPresentUntilForgotten(t, ctx, fixture)
})
t.Run("ForgetRemovesExactlyTheNamedRow", func(t *testing.T) {
conformance.RunMemoriesForgetRemovesExactlyTheNamedRow(t, ctx, fixture)

View file

@ -84,9 +84,7 @@ func MemoriesFromConfig(all map[string]string) map[string]string {
// destroyed.
//
// replaced is about the ROW, not the value: a memory stored as the empty string
// reports true even though a Recall of it would report Found false. See
// memoryops.RememberResult.Replaced, which states that divergence rather than
// smoothing it over.
// reports true, just as Recall reports it found.
func RememberInTx(ctx context.Context, tx *sql.Tx, key, content string) (replaced bool, err error) {
storageKey := StorageKey(key)
replaced, err = configRowExistsInTx(ctx, tx, storageKey)
@ -99,31 +97,33 @@ func RememberInTx(ctx context.Context, tx *sql.Tx, key, content string) (replace
return replaced, nil
}
// RecallInTx reads one memory in the caller's transaction. A key nothing stored
// answers "" with a nil error: the seam cannot tell that from a row stored
// empty, and the role's Found field is where that conflation is stated.
func RecallInTx(ctx context.Context, tx *sql.Tx, key string) (string, error) {
return issueops.GetConfigInTx(ctx, tx, StorageKey(key))
// RecallInTx reads one memory in the caller's transaction and reports whether
// its row exists. A stored empty value is therefore distinct from no row.
func RecallInTx(ctx context.Context, tx *sql.Tx, key string) (value string, found bool, err error) {
storageKey := StorageKey(key)
err = tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", storageKey).Scan(&value)
if errors.Is(err, sql.ErrNoRows) {
return "", false, nil
}
if err != nil {
return "", false, fmt.Errorf("recall memory %s: %w", storageKey, err)
}
return value, true, nil
}
// ForgetInTx removes one memory and returns what it held, both in the caller's
// transaction — which is what makes the returned value the one that was
// actually deleted rather than the one an earlier read happened to see.
//
// found is Recall's found, not the row's: a memory stored as the empty string
// reports found false and IS NOT DELETED. That keeps Forget's answer and
// Recall's answer the same statement, which is what a front door printing
// "No memory with key ..." after a successful Recall would otherwise contradict.
//
// The delete names the one encoded key. There is no LIKE and no prefix sweep in
// it, so forgetting "a" cannot take "a-b" with it.
func ForgetInTx(ctx context.Context, tx *sql.Tx, key string) (previous string, found bool, err error) {
storageKey := StorageKey(key)
previous, err = issueops.GetConfigInTx(ctx, tx, storageKey)
previous, found, err = RecallInTx(ctx, tx, key)
if err != nil {
return "", false, err
}
if previous == "" {
if !found {
return "", false, nil
}
if err := issueops.DeleteConfigInTx(ctx, tx, storageKey); err != nil {

View file

@ -88,11 +88,16 @@ func (m *memories) Recall(ctx context.Context, req memoryops.RecallRequest) (mem
return memoryops.RecallResult{}, err
}
return RunTxRead(ctx, m.provider, func(ctx context.Context, uw UnitOfWork) (memoryops.RecallResult, error) {
value, err := uw.ConfigUseCase().GetConfig(ctx, storagememoryops.StorageKey(key))
// The same whole-table probe as Remember, for the reason given there:
// Found is about the ROW, GetConfig answers "" for a missing row and an
// empty one alike, and the map's key set is the only place the
// difference survives. It is one query on a table of tens of rows.
all, err := uw.ConfigUseCase().GetAllConfig(ctx)
if err != nil {
return memoryops.RecallResult{}, err
}
return memoryops.RecallResult{Key: key, Value: value, Found: value != ""}, nil
value, found := all[storagememoryops.StorageKey(key)]
return memoryops.RecallResult{Key: key, Value: value, Found: found}, nil
})
}
@ -111,11 +116,14 @@ func (m *memories) Forget(ctx context.Context, req memoryops.ForgetRequest) (mem
storageKey := storagememoryops.StorageKey(key)
result, err := RunTxResult(ctx, m.provider, func(ctx context.Context, uw UnitOfWork) (memoryops.ForgetResult, string, error) {
cfg := uw.ConfigUseCase()
previous, err := cfg.GetConfig(ctx, storageKey)
// The row probe Remember and Recall use: gating on GetConfig's "" is
// what left a memory stored empty unforgettable.
all, err := cfg.GetAllConfig(ctx)
if err != nil {
return memoryops.ForgetResult{}, "", err
}
if previous == "" {
previous, found := all[storageKey]
if !found {
return memoryops.ForgetResult{Key: key}, "", nil
}
if err := cfg.DeleteConfig(ctx, storageKey); err != nil {

View file

@ -56,8 +56,8 @@ func TestMemoriesContract(t *testing.T) {
t.Run("RecallReportsAMissAsNotFoundNotAnError", func(t *testing.T) {
conformance.RunMemoriesRecallReportsAMissAsNotFoundNotAnError(t, ctx, fixture)
})
t.Run("RecallConflatesStoredEmptyWithAbsent", func(t *testing.T) {
conformance.RunMemoriesRecallConflatesStoredEmptyWithAbsent(t, ctx, fixture)
t.Run("EmptyRowIsPresentUntilForgotten", func(t *testing.T) {
conformance.RunMemoriesEmptyRowIsPresentUntilForgotten(t, ctx, fixture)
})
t.Run("ForgetRemovesExactlyTheNamedRow", func(t *testing.T) {
conformance.RunMemoriesForgetRemovesExactlyTheNamedRow(t, ctx, fixture)

View file

@ -23,13 +23,8 @@ var ErrValidation = beadserrors.ErrValidation
// THERE IS DELIBERATELY NO ErrNotFound ON THIS ROLE.
//
// beadserrors declares one; this leaf does not re-export it. The storage seam
// beneath it cannot tell an absent config row from a row stored as the empty
// string (issueops/workspaceconfig.go states the same conflation for settings,
// and it is the same table). A role that answered a Recall of an unknown key
// with ErrNotFound would be minting an error out of a distinction it cannot
// actually see, and the first out-of-band empty write would make it a lie.
//
// Misses are RESULT-CARRIED instead — RecallResult.Found, ForgetResult.Found —
// and the front doors translate: the CLI to its SilentExit contract, an HTTP
// door to its 404. That keeps the invention where a door can justify it.
// beadserrors declares one; this leaf does not re-export it. Misses are
// RESULT-CARRIED instead — RecallResult.Found, ForgetResult.Found — and the
// front doors translate: the CLI to its SilentExit contract, an HTTP door to
// its 404. That lets callers handle absence without classifying an operational
// error and keeps presentation policy at the door.

View file

@ -40,11 +40,7 @@ type RememberResult struct {
// observation and the act it describes.
//
// A previous value that was the EMPTY STRING reports Replaced true. The ROW
// existed, even though a Recall of that key would have answered Found
// false. That divergence is the storage seam's conflation showing through
// (see RecallResult.Found); it is stated here rather than smoothed over,
// because smoothing it would mean this field reporting "nothing was there"
// about a write that overwrote something.
// existed, regardless of what it held.
Replaced bool
}
@ -60,15 +56,9 @@ type RecallResult struct {
Key string
// Value is the stored content, or "" — and Found says how to read the "".
Value string
// Found is Value != "". A MEMORY STORED AS THE EMPTY STRING AND AN ABSENT
// MEMORY ARE THE SAME ANSWER: Found false, nil error.
//
// No front door can create the first of those — Remember refuses empty
// content — but an out-of-band config write can, and this role does not
// invent a distinction the seam beneath it cannot see. List DOES enumerate
// such a row, because its KEY exists, and that is the one way a caller can
// tell the two apart: the same same-answer-different-row asymmetry the
// settings contract pins for `bd config get`.
// Found reports whether the row exists, independently of Value. A memory
// stored as the empty string therefore reports Found true; an absent memory
// reports Found false with the same empty Value.
Found bool
}
@ -84,9 +74,8 @@ type ForgetResult struct {
// read in the SAME TRANSACTION as the delete, so it is what was actually
// removed rather than what a previous read happened to see.
Value string
// Found false means nothing was stored under Key (or an empty string was:
// the same conflation RecallResult.Found describes) and NOTHING WAS
// DELETED.
// Found false means no row was stored under Key and NOTHING WAS DELETED. A
// row holding the empty string is found and deleted.
//
// It is a result, not an error. The front doors own the not-found
// presentation — the CLI has an exit-code contract for it — and a role that
@ -160,7 +149,7 @@ type Memories interface {
// THE REFUSALS, in the order they are applied:
//
// - Content empty after trimming is ErrValidation. There is nothing to
// remember, and a row stored empty is a row Recall would then deny;
// remember;
// - Content from which no key can be derived, when Key is empty, is
// ErrValidation. The caller's recourse is an explicit key, which the
// message says.