Skip to content

armgit / memos

Public Imported from GitHub
0

Memos is an open-source, self-hosted note-taking app that brings your everyday thoughts together in a personal timeline. Your data stays yours, and you choose what to keep private or share.

chore(mcp): expose spaces, forward the client address, re-pin evals

boojack619eb8d6b8ab
diff --git a/docs/design/multi-spaces.md b/docs/design/multi-spaces.md
index 2cb834bbb..3c98d1979 100644
--- a/docs/design/multi-spaces.md
+++ b/docs/design/multi-spaces.md
@@ -153,7 +153,7 @@ The Space-user pair is unique and represents one current relationship slot. `INV
The change ships in migration `0.31` for SQLite, MySQL, and PostgreSQL, with equivalent fresh-install schemas. Existing membership rows are backfilled to `ACTIVE`. Existing memos keep their UID, author, visibility, relations, permalink, and become Unassigned. Comment rows and comment visibility are not rewritten. SQLite rebuilds the affected tables where its `ALTER TABLE` support requires it.
-Space creation, invitation transitions, membership changes, placement and audience changes, comment creation, memo deletion, and Space deletion use ordinary transactions where partial application would corrupt directly affected data. On MySQL and PostgreSQL, operations that create or activate a Space relationship serialize with user deletion on the target user row, and invitation creation serializes with Space deletion on the Space row. This prevents a concurrent delete from leaving an orphaned active membership or invitation. Space deletion directly removes assigned memos and their owned rows in the same style as existing user deletion, then uses the existing best-effort attachment storage cleanup after commit. The initial version does not introduce general transaction retries, a cleanup queue, or a global concurrency framework.
+Space creation, invitation transitions, membership changes, placement and audience changes, comment creation, memo deletion, and Space deletion use ordinary transactions where partial application would corrupt directly affected data. On MySQL and PostgreSQL, operations that create or activate a Space relationship serialize with user deletion on the target user row, and invitation creation serializes with Space deletion on the Space row. On SQLite every store transaction begins `IMMEDIATE`, so a transaction that has read a parent row holds the single write lock until it ends and a concurrent delete waits rather than committing underneath it. This prevents a concurrent delete from leaving an orphaned active membership or invitation. Space deletion directly removes assigned memos and their owned rows in the same style as existing user deletion, then uses the existing best-effort attachment storage cleanup after commit. The initial version does not introduce general transaction retries, a cleanup queue, or a global concurrency framework.
### API shape
@@ -169,7 +169,7 @@ Memo listing expresses placement through the CEL filter: `space == "spaces/{spac
Placement and audience use the existing memo update mechanism so the memo author can change them atomically. The Space API does not add an operation for an `ADMIN` to move, withdraw, or otherwise mutate an individual memo.
-MCP memo operations reuse the same memo policy; Space management is not exposed through MCP in the initial version.
+MCP memo operations reuse the same memo policy. The Space service is exposed through MCP as the `space_*` tools, which run in-process against the same REST bindings and therefore the same membership authorization; see `server/mcp/README.md`.
### UI shape
@@ -181,7 +181,7 @@ Creating an invitation also delivers a `SPACE_INVITATION` inbox notification to
Before `SPACE` can be stored, one shared, memo-local, fail-closed policy must cover point reads, lists and counts, files, reactions, relations, notifications, email, webhooks, shares, search, statistics, public feeds, and MCP. Child resources resolve the memo they directly belong to. Application `ADMIN` bypasses only the memo-local checks on named operations; drivers resolve the actor's role inside the mutation transaction alongside the actor's lifecycle state, and an archived administrator holds no privilege.
-Unknown visibility denies access. A missing or invalid placement denies `SPACE` reads and placement-dependent operations. Other audiences continue to govern ordinary reads, but an invalid Space identity is omitted. Inactive users, pending invitations, unknown relationship states, and invalid membership roles deny any access that depends on them. Every membership authorization requires `status = ACTIVE` and role `ADMIN` or `USER`. Where the database supports row locks, relationship creation and activation serialize against user deletion, and invitation creation serializes against Space deletion. Database list and count authorization is applied before pagination:
+Unknown visibility denies access. A missing or invalid placement denies `SPACE` reads and placement-dependent operations. Other audiences continue to govern ordinary reads, but an invalid Space identity is omitted. Inactive users, pending invitations, unknown relationship states, and invalid membership roles deny any access that depends on them. Every membership authorization requires `status = ACTIVE` and role `ADMIN` or `USER`. Where the database supports row locks, relationship creation and activation serialize against user deletion, and invitation creation serializes against Space deletion; on SQLite the same serialization comes from `IMMEDIATE` transactions. Database list and count authorization is applied before pagination:
```text
PRIVATE + active authenticated author
diff --git a/server/mcp/README.md b/server/mcp/README.md
index e697b113a..26878a324 100644
--- a/server/mcp/README.md
+++ b/server/mcp/README.md
@@ -62,7 +62,8 @@ fast on any inconsistency:
6. The caller's `Authorization` header is read from the request (`request.Extra.Header` on the SDK's `*sdkmcp.CallToolRequest`).
7. `apiAdapter.execute` (`adapter.go`) builds the API request
(`buildAPIRequest`: path-parameter substitution, query encoding, JSON body),
- forwards the bearer token, and runs it against the Echo server through an
+ forwards the bearer token, presents the caller's resolved client address as
+ the request peer, and runs it against the Echo server through an
`httptest.ResponseRecorder`.
8. The recorder body is decoded; a non-2xx status becomes a tool error
(`newToolErrorResult`), otherwise the value is wrapped by
@@ -93,8 +94,10 @@ use `$ref`. `openapi.go` resolves these into local definitions:
to `required`. Body `$defs` are lifted to the schema's top-level `$defs`.
- Per-operation overrides relax resource-level requirements for create and
partial-update bodies and remove fields already supplied by a path binding
- from `body: "*"` schemas. Memo updates may omit `updateMask` so the REST
- gateway can infer it from the fields present in the request body.
+ from `body: "*"` schemas. Memo and space updates may omit `updateMask` so the
+ REST gateway can infer it from the fields present in the request body. A
+ `body: "*"` binding whose only field is path-bound (accepting or declining a
+ space invitation) has its `body` made optional instead of demanding `{}`.
- The schema sets `"additionalProperties": false`.
The output schema is the operation's 200 `application/json` schema. When a 200
@@ -122,6 +125,13 @@ response has no JSON body, the fallback is:
the in-process API request. Mutating tools therefore require a valid token
(personal access token or access token); public reads may work without one,
exactly as the REST API allows.
+- **Client address:** the `/mcp` request passes through the same client-address
+ middleware as every other route, which resolves the caller behind trusted
+ proxies. The adapter reads that resolved address from the tool handler's
+ context and sets it as the in-process request's peer, so the middleware's
+ second pass resolves to the same value. Without this every tool call would
+ present `httptest`'s placeholder peer (`192.0.2.1`), and all anonymous MCP
+ callers would share one rate-limit bucket.
- **Origin safety:** `isAllowedMCPOrigin` allows a request when the `Origin`
header is absent (desktop clients commonly omit it), when its host matches
the request `Host` header (host comparison only — scheme is not checked), or
@@ -150,7 +160,9 @@ a personal access token as a bearer credential. Example client config:
## Tool surface
The server exposes a curated allowlist (`curatedOperationIDs` in `catalog.go`),
-centered on memos and attachments, plus two read-only orientation tools:
+centered on memos and attachments, plus the space service (memos carry a
+placement and a `SPACE` audience, so agents must be able to discover and
+administer spaces and answer invitations) and two read-only orientation tools:
`user_list_memo_views` (surfaces a user's named CEL filters for reuse with
`memo_list_memos`) and `auth_get_current_user` (a "whoami" so an agent can
resolve its own user — the single allowed auth/identity operation):
@@ -177,6 +189,22 @@ resolve its own user — the single allowed auth/identity operation):
| `AttachmentService_DeleteAttachment` | `attachment_delete_attachment` |
| `UserService_ListMemoViews` | `user_list_memo_views` |
| `AuthService_GetCurrentUser` | `auth_get_current_user` |
+| `SpaceService_ListSpaces` | `space_list_spaces` |
+| `SpaceService_GetSpace` | `space_get_space` |
+| `SpaceService_CreateSpace` | `space_create_space` |
+| `SpaceService_UpdateSpace` | `space_update_space` |
+| `SpaceService_DeleteSpace` | `space_delete_space` |
+| `SpaceService_ListSpaceMembers` | `space_list_space_members` |
+| `SpaceService_GetSpaceMember` | `space_get_space_member` |
+| `SpaceService_UpdateSpaceMember` | `space_update_space_member` |
+| `SpaceService_DeleteSpaceMember` | `space_delete_space_member` |
+| `SpaceService_ListSpaceInvitations` | `space_list_space_invitations` |
+| `SpaceService_ListUserSpaceInvitations` | `space_list_user_space_invitations` |
+| `SpaceService_GetSpaceInvitation` | `space_get_space_invitation` |
+| `SpaceService_CreateSpaceInvitation` | `space_create_space_invitation` |
+| `SpaceService_AcceptSpaceInvitation` | `space_accept_space_invitation` |
+| `SpaceService_DeclineSpaceInvitation` | `space_decline_space_invitation` |
+| `SpaceService_DeleteSpaceInvitation` | `space_delete_space_invitation` |
**Naming rule** (`toolNameFromOperationID`): drop the `Service` suffix from the
subject and convert both subject and method from camelCase to snake_case, joined
@@ -193,8 +221,11 @@ by `_`. So `MemoService_ListMemos → memo_list_memos`.
Per-operation overrides then correct cases the method heuristic gets wrong.
`MemoService_SetMemoAttachments` and `MemoService_SetMemoRelations` are PATCH
but declaratively replace the full set on a memo, so they report both
-`IdempotentHint: true` and `DestructiveHint: true`. `MemoService_UpdateMemo`
-also reports `DestructiveHint: true` because it can overwrite existing fields.
+`IdempotentHint: true` and `DestructiveHint: true`. `MemoService_UpdateMemo`,
+`SpaceService_UpdateSpace`, and `SpaceService_UpdateSpaceMember` also report
+`DestructiveHint: true` because they overwrite existing fields (a member's role
+included). `SpaceService_DeleteSpace` is destructive by method, and the API
+also deletes every memo placed in the space.
`OpenWorldHint` is `false` for all tools. Annotations are client hints; they do
not replace API authorization.
@@ -271,13 +302,13 @@ go test ./server/mcp/...
- `openapi_test.go` — spec parsing, registry building, `$ref` resolution.
- `catalog_test.go` — tool selection, naming, schema and annotation building.
-- `adapter_test.go` — request construction and in-process execution (`adapter.go`), plus result normalization and error shaping (`result.go`).
+- `adapter_test.go` — request construction and in-process execution (`adapter.go`), including the client-address peer, plus result normalization and error shaping (`result.go`).
- `validation_test.go` — argument validation against input schemas.
- `service_test.go` — the origin-header check, the stateless `2026-07-28`
flow (`server/discover`, `tools/list`, `tools/call` with MCP headers), the
- request body limit, plus the legacy end-to-end MCP protocol
- (`initialize`, `tools/list`, `tools/call`) confirming object-shaped
- `structuredContent`.
+ request body limit, client-address forwarding through the in-process hop,
+ plus the legacy end-to-end MCP protocol (`initialize`, `tools/list`,
+ `tools/call`) confirming object-shaped `structuredContent`.
## Design notes
diff --git a/server/mcp/adapter.go b/server/mcp/adapter.go
index daa0ff84e..c19a00b99 100644
--- a/server/mcp/adapter.go
+++ b/server/mcp/adapter.go
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"io"
+ "net"
"net/http"
"net/http/httptest"
"net/url"
@@ -14,6 +15,8 @@ import (
"github.com/labstack/echo/v5"
sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/pkg/errors"
+
+ "github.com/usememos/memos/internal/clientip"
)
type apiAdapter struct {
@@ -68,7 +71,7 @@ func buildAPIRequest(ctx context.Context, operation *openAPIOperation, arguments
if operation.RequestBody != nil {
bodyValue, ok := arguments["body"]
if !ok || bodyValue == nil {
- if operation.RequestBody.Required {
+ if requestBodyRequired(operation) {
return nil, errors.New(`missing required request body "body"`)
}
bodyValue = map[string]any{}
@@ -82,6 +85,17 @@ func buildAPIRequest(ctx context.Context, operation *openAPIOperation, arguments
}
req := httptest.NewRequest(operation.Method, path, body).WithContext(ctx)
+ // httptest.NewRequest stamps a fixed peer address (192.0.2.1) on every
+ // request. The client-address middleware runs again on this in-process
+ // request and would otherwise key every MCP caller's anonymous rate limit
+ // and address records on that placeholder. The SDK hands the tool handler
+ // the /mcp request's context, so the address resolved for the real caller
+ // is already there; present it as the peer so the middleware resolves to
+ // the same value (a trusted-proxy address with no forwarding headers
+ // resolves to itself).
+ if ip := clientip.FromContext(ctx); ip != "" {
+ req.RemoteAddr = net.JoinHostPort(ip, "0")
+ }
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
diff --git a/server/mcp/adapter_test.go b/server/mcp/adapter_test.go
index 47c8e5788..66ca8c7c0 100644
--- a/server/mcp/adapter_test.go
+++ b/server/mcp/adapter_test.go
@@ -12,6 +12,8 @@ import (
"github.com/labstack/echo/v5"
sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/require"
+
+ "github.com/usememos/memos/internal/clientip"
)
func TestNormalizeStructuredContentKeepsObjects(t *testing.T) {
@@ -118,6 +120,44 @@ func TestBuildAPIRequestMapsPathQueryAndBody(t *testing.T) {
require.JSONEq(t, `{"memo":{"name":"memos/abc123","content":"updated"}}`, string(body))
}
+func TestBuildAPIRequestPresentsResolvedClientAddressAsPeer(t *testing.T) {
+ operation := &openAPIOperation{Method: "GET", Path: "/api/v1/memos"}
+
+ req, err := buildAPIRequest(context.Background(), operation, map[string]any{}, "")
+ require.NoError(t, err)
+ require.Equal(t, "192.0.2.1:1234", req.RemoteAddr, "httptest placeholder stays when no address was resolved")
+
+ ctx := clientip.WithClientIP(context.Background(), "203.0.113.9")
+ req, err = buildAPIRequest(ctx, operation, map[string]any{}, "")
+ require.NoError(t, err)
+ require.Equal(t, "203.0.113.9:0", req.RemoteAddr)
+
+ ctx = clientip.WithClientIP(context.Background(), "2001:db8::9")
+ req, err = buildAPIRequest(ctx, operation, map[string]any{}, "")
+ require.NoError(t, err)
+ require.Equal(t, "[2001:db8::9]:0", req.RemoteAddr)
+}
+
+func TestBuildAPIRequestOmitsOptionalOverriddenBody(t *testing.T) {
+ operation := &openAPIOperation{
+ OperationID: "SpaceService_AcceptSpaceInvitation",
+ Method: "POST",
+ Path: "/api/v1/spaces/{space}/invitations/{invitation}:accept",
+ Parameters: []openAPIParameter{
+ {Name: "space", In: "path", Required: true},
+ {Name: "invitation", In: "path", Required: true},
+ },
+ RequestBody: &openAPIRequestBody{Required: true},
+ }
+
+ req, err := buildAPIRequest(context.Background(), operation, map[string]any{"space": "team", "invitation": "sam"}, "")
+ require.NoError(t, err)
+ require.Equal(t, "/api/v1/spaces/team/invitations/sam:accept", req.URL.Path)
+ body, err := io.ReadAll(req.Body)
+ require.NoError(t, err)
+ require.JSONEq(t, `{}`, string(body))
+}
+
func TestBuildAPIRequestAcceptsResourceNamesForPathParameters(t *testing.T) {
tests := []struct {
name string
diff --git a/server/mcp/catalog.go b/server/mcp/catalog.go
index b693d973c..e7faa5a42 100644
--- a/server/mcp/catalog.go
+++ b/server/mcp/catalog.go
@@ -32,6 +32,25 @@ var curatedOperationIDs = []string{
// The only allowed auth/identity operation: a read-only "whoami" so agents
// can resolve the current user (e.g. for UserService_ListMemoViews).
"AuthService_GetCurrentUser",
+ // Spaces: memos carry a placement (Memo.space) and a SPACE audience, so an
+ // agent needs to discover, create, and administer the spaces it can place
+ // memos in, and to handle the invitations that grant membership.
+ "SpaceService_ListSpaces",
+ "SpaceService_GetSpace",
+ "SpaceService_CreateSpace",
+ "SpaceService_UpdateSpace",
+ "SpaceService_DeleteSpace",
+ "SpaceService_ListSpaceMembers",
+ "SpaceService_GetSpaceMember",
+ "SpaceService_UpdateSpaceMember",
+ "SpaceService_DeleteSpaceMember",
+ "SpaceService_ListSpaceInvitations",
+ "SpaceService_ListUserSpaceInvitations",
+ "SpaceService_GetSpaceInvitation",
+ "SpaceService_CreateSpaceInvitation",
+ "SpaceService_AcceptSpaceInvitation",
+ "SpaceService_DeclineSpaceInvitation",
+ "SpaceService_DeleteSpaceInvitation",
}
type registeredOperation struct {
@@ -53,6 +72,10 @@ type requestBodySchemaOverride struct {
// properties. It replaces a cleared required list for partial updates so an
// empty body is rejected up front instead of failing later at the API.
minProperties int
+ // bodyOptional drops "body" from the tool's required arguments. It is for
+ // body: "*" bindings whose only field is supplied by the path, so that a
+ // caller does not have to pass an empty object to satisfy the schema.
+ bodyOptional bool
}
// requestBodySchemaOverrides adjusts resource schemas to match how each HTTP
@@ -83,6 +106,41 @@ var requestBodySchemaOverrides = map[string]requestBodySchemaOverride{
required: []string{"reaction"},
omittedProperties: []string{"name"},
},
+ // UpdateSpace requires an update mask, which the REST gateway infers from
+ // the fields present in the body. The space name comes from the path.
+ "SpaceService_UpdateSpace": {
+ clearRequired: true,
+ omittedProperties: []string{"name"},
+ minProperties: 1,
+ },
+ // Only a member's role is mutable; the member name and user identity are
+ // both fixed by the path.
+ "SpaceService_UpdateSpaceMember": {
+ required: []string{"role"},
+ omittedProperties: []string{"name", "user"},
+ },
+ // Accept and decline are body: "*" bindings whose single field, the
+ // invitation name, is already bound from the path.
+ "SpaceService_AcceptSpaceInvitation": {
+ clearRequired: true,
+ omittedProperties: []string{"name"},
+ bodyOptional: true,
+ },
+ "SpaceService_DeclineSpaceInvitation": {
+ clearRequired: true,
+ omittedProperties: []string{"name"},
+ bodyOptional: true,
+ },
+}
+
+// requestBodyRequired reports whether a tool call must carry a "body" argument
+// for the operation: the OpenAPI request body is required and no override has
+// made it optional.
+func requestBodyRequired(operation *openAPIOperation) bool {
+ if operation.RequestBody == nil || !operation.RequestBody.Required {
+ return false
+ }
+ return !requestBodySchemaOverrides[operation.OperationID].bodyOptional
}
var wordBoundary = regexp.MustCompile(`([a-z0-9])([A-Z])`)
@@ -215,7 +273,7 @@ func inputSchemaForOperation(operation *openAPIOperation) jsonSchema {
defs[name] = definition
}
properties["body"] = bodySchema
- if operation.RequestBody.Required {
+ if requestBodyRequired(operation) {
required = append(required, "body")
}
}
@@ -304,6 +362,8 @@ var destructiveOperationIDs = map[string]bool{
"MemoService_UpdateMemo": true,
"MemoService_SetMemoAttachments": true,
"MemoService_SetMemoRelations": true,
+ "SpaceService_UpdateSpace": true,
+ "SpaceService_UpdateSpaceMember": true,
}
// annotationsForOperation derives the method-based annotations and then applies
diff --git a/server/mcp/catalog_test.go b/server/mcp/catalog_test.go
index d6a8b8dae..473d6b21e 100644
--- a/server/mcp/catalog_test.go
+++ b/server/mcp/catalog_test.go
@@ -11,7 +11,7 @@ import (
)
func TestCuratedOperationIDsStayMemoFocused(t *testing.T) {
- require.Len(t, curatedOperationIDs, 20)
+ require.Len(t, curatedOperationIDs, 36)
for _, operationID := range curatedOperationIDs {
require.NotContains(t, operationID, "Admin")
@@ -447,3 +447,98 @@ func TestBuildCuratedToolsUseStandardSchemaFormats(t *testing.T) {
}
require.True(t, sawBase64Content, "expected attachment content to advertise contentEncoding base64")
}
+
+func TestBuildToolFromOperationExposesSpaceTools(t *testing.T) {
+ spec, err := loadOpenAPISpec("../../proto/gen/openapi.yaml")
+ require.NoError(t, err)
+ registry, err := buildOperationRegistry(spec)
+ require.NoError(t, err)
+
+ tool, operation := buildToolFromOperation(registry["SpaceService_ListSpaces"])
+ require.Equal(t, "space_list_spaces", tool.Name)
+ require.Equal(t, "GET", operation.Method)
+ require.Equal(t, "/api/v1/spaces", operation.Path)
+ require.True(t, tool.Annotations.ReadOnlyHint)
+
+ tool, operation = buildToolFromOperation(registry["SpaceService_CreateSpace"])
+ require.Equal(t, "space_create_space", tool.Name)
+ require.Equal(t, "POST", operation.Method)
+ input, ok := tool.InputSchema.(jsonSchema)
+ require.True(t, ok)
+ require.Contains(t, input["required"], "body")
+ require.NoError(t, validateToolArguments(input, map[string]any{
+ "body": map[string]any{"title": "Team"},
+ }))
+ require.Error(t, validateToolArguments(input, map[string]any{
+ "body": map[string]any{"description": "no title"},
+ }))
+
+ tool, operation = buildToolFromOperation(registry["SpaceService_DeleteSpace"])
+ require.Equal(t, "space_delete_space", tool.Name)
+ require.Equal(t, "DELETE", operation.Method)
+ require.True(t, *tool.Annotations.DestructiveHint)
+}
+
+func TestBuildToolFromOperationTailorsSpaceUpdateBodies(t *testing.T) {
+ spec, err := loadOpenAPISpec("../../proto/gen/openapi.yaml")
+ require.NoError(t, err)
+ registry, err := buildOperationRegistry(spec)
+ require.NoError(t, err)
+
+ tool, operation := buildToolFromOperation(registry["SpaceService_UpdateSpace"])
+ require.Equal(t, "PATCH", operation.Method)
+ require.True(t, *tool.Annotations.DestructiveHint)
+ input, ok := tool.InputSchema.(jsonSchema)
+ require.True(t, ok)
+ body := schemaProperties(schemaProperties(input["properties"])["body"])
+ require.NotContains(t, schemaProperties(body["properties"]), "name")
+ // The gateway infers the update mask from the fields present, so a partial
+ // body is valid but an empty one is not.
+ require.NoError(t, validateToolArguments(input, map[string]any{
+ "space": "spaces/team",
+ "body": map[string]any{"description": "renamed"},
+ }))
+ require.Error(t, validateToolArguments(input, map[string]any{
+ "space": "spaces/team",
+ "body": map[string]any{},
+ }))
+
+ tool, operation = buildToolFromOperation(registry["SpaceService_UpdateSpaceMember"])
+ require.Equal(t, "PATCH", operation.Method)
+ require.True(t, *tool.Annotations.DestructiveHint)
+ input, ok = tool.InputSchema.(jsonSchema)
+ require.True(t, ok)
+ body = schemaProperties(schemaProperties(input["properties"])["body"])
+ require.NotContains(t, schemaProperties(body["properties"]), "name")
+ require.NotContains(t, schemaProperties(body["properties"]), "user")
+ require.Equal(t, []string{"role"}, body["required"])
+ require.NoError(t, validateToolArguments(input, map[string]any{
+ "space": "spaces/team",
+ "member": "sam",
+ "body": map[string]any{"role": "ADMIN"},
+ }))
+}
+
+func TestBuildToolFromOperationMakesInvitationResponseBodiesOptional(t *testing.T) {
+ spec, err := loadOpenAPISpec("../../proto/gen/openapi.yaml")
+ require.NoError(t, err)
+ registry, err := buildOperationRegistry(spec)
+ require.NoError(t, err)
+
+ for _, operationID := range []string{"SpaceService_AcceptSpaceInvitation", "SpaceService_DeclineSpaceInvitation"} {
+ operation := registry[operationID]
+ require.True(t, operation.RequestBody.Required, operationID)
+ require.False(t, requestBodyRequired(operation), operationID)
+
+ tool, _ := buildToolFromOperation(operation)
+ input, ok := tool.InputSchema.(jsonSchema)
+ require.True(t, ok)
+ require.NotContains(t, input["required"], "body", operationID)
+ body := schemaProperties(schemaProperties(input["properties"])["body"])
+ require.NotContains(t, schemaProperties(body["properties"]), "name", operationID)
+ require.NoError(t, validateToolArguments(input, map[string]any{
+ "space": "spaces/team",
+ "invitation": "sam",
+ }), operationID)
+ }
+}
diff --git a/server/mcp/evals/README.md b/server/mcp/evals/README.md
index c4be9eab2..d057fd239 100644
--- a/server/mcp/evals/README.md
+++ b/server/mcp/evals/README.md
@@ -5,27 +5,41 @@ verify the server *plumbing* (schema resolution, tool naming, annotations),
these check the thing that actually matters for an MCP server: **can an LLM
accomplish realistic tasks by composing the tools?** They are the regression
net for tool descriptions and discoverability — e.g. a bad `filter` description
-leaves the unit tests green but makes question 3/5/9 unanswerable.
+leaves the unit tests green but makes several questions unanswerable.
-`memos_eval.xml` holds 10 question/answer pairs in the format used by the
+`memos_eval.xml` holds 15 question/answer pairs in the format used by the
mcp-builder skill. Each question is independent, read-only, requires multiple
-tool calls, and has a single string-comparable answer.
+tool calls, and has a single string-comparable answer. Questions 1–10 exercise
+the memo tools; 11–15 exercise the space tools and the `space` placement of
+memos.
## Why a fresh seeded instance (not the public demo)
Answers are pinned to the deterministic seed in
-[`store/seed/sqlite/01__dump.sql`](../../../store/seed/sqlite/01__dump.sql)
-(10 memos — 7 top-level + 3 comments — 2 users, 12 reactions, no attachments,
-no memo views).
+[`store/seed/sqlite/01__dump.sql`](../../../store/seed/sqlite/01__dump.sql):
+
+- 4 users: `steven` (instance admin), `johnny`, `bob`, `sam`.
+- 31 memos: 22 top-level + 9 comments, plus 3 `REFERENCE` relations.
+- 35 reactions, all on top-level memos.
+- 4 spaces — `updates` (4 members), `dev`, `travel`, `reading` (3 each).
+ `steven` is a member of all four and administers `updates`; `johnny`, `bob`,
+ and `sam` administer `dev`, `travel`, and `reading` respectively. Two
+ top-level memos (`sam`'s ramen recipe and movie watchlist) are unassigned.
+- One attachment, owned by `bob` and bound to `memos/goldenhour0001`.
+- No saved memo views and no pending invitations.
The public demo (`demo.usememos.com`) signs everyone into the **same shared
-`demo` account**, so visitors continually add/edit/delete memos and reactions.
+account**, so visitors continually add/edit/delete memos, reactions, and spaces.
Its data has already diverged from the seed — do **not** evaluate against it.
The seed uses **relative** timestamps (`strftime('now','-N days')`), so the
questions avoid absolute dates and rely only on relative ordering, counts, and
content, all of which are stable across re-seeds.
+The seed is edited from time to time (most recently to organize memos into
+spaces). When it changes, re-derive every answer against a fresh instance and
+update both this summary and `memos_eval.xml`; nothing in CI catches drift.
+
## Running an evaluation
1. Launch a throwaway demo-mode instance (SQLite, auto-seeded) on a free port:
@@ -37,7 +51,7 @@ content, all of which are stable across re-seeds.
```
2. The MCP endpoint is `http://localhost:8099/mcp`. Authenticate with the seed's
- demo personal access token:
+ demo personal access token, which belongs to `steven`:
```
Authorization: Bearer memos_pat_demo
@@ -62,6 +76,13 @@ content, all of which are stable across re-seeds.
`"work" in tags` (or `tags.exists(t, t == "work")`), not `tag == "work"`.
- `memo_list_memos` returns only top-level memos; comments are reached via
`memo_list_memo_comments`.
-- The seed defines no memo views and no attachments, so `user_list_memo_views`
- and the attachment tools return empty sets against a fresh seed. Add seed rows
- before writing questions that depend on them.
+- Placement is filtered with `space == "spaces/dev"`, `space == null`
+ (unassigned), or `space != null`. `space_list_spaces` returns only spaces the
+ caller is a member of, with `memberCount` and `currentUserRole` filled in.
+- `space_list_space_invitations` requires space-administrator membership;
+ `space_list_user_space_invitations` lists the caller's own pending invitations.
+- `attachment_list_attachments` lists the caller's own attachments, so it is
+ empty for the demo account; the seed's one attachment is reachable through
+ `memo_list_memo_attachments` on `memos/goldenhour0001`. `user_list_memo_views`
+ returns an empty set against a fresh seed. Add seed rows before writing
+ questions that depend on them.
diff --git a/server/mcp/evals/memos_eval.xml b/server/mcp/evals/memos_eval.xml
index 2e5d6028d..acd5b9406 100644
--- a/server/mcp/evals/memos_eval.xml
+++ b/server/mcp/evals/memos_eval.xml
@@ -4,15 +4,16 @@
These questions test whether an LLM can accomplish realistic tasks by
composing the curated MCP tools (memo_list_memos with CEL filters,
- memo_list_memo_comments, memo_list_memo_reactions, user_list_memo_views,
- auth_get_current_user, ...). They are NOT unit tests of the server plumbing —
- see *_test.go for that.
+ memo_list_memo_comments, memo_list_memo_reactions, space_list_spaces,
+ space_list_space_members, user_list_memo_views, auth_get_current_user, ...).
+ They are NOT unit tests of the server plumbing — see *_test.go for that.
Answers are pinned to the deterministic seed in
store/seed/sqlite/01__dump.sql and were verified by querying a fresh
- demo-mode instance. Run against a freshly seeded instance ONLY (the public
- demo at demo.usememos.com is a shared, mutable account and will not match).
- See README.md in this directory for how to launch one.
+ demo-mode instance through the MCP tools. Run against a freshly seeded
+ instance ONLY (the public demo at demo.usememos.com is a shared, mutable
+ account and will not match). See README.md in this directory for how to
+ launch one.
Questions deliberately avoid absolute dates: the seed uses relative
timestamps (strftime('now','-N days')), so only relative ordering, counts,
@@ -20,28 +21,28 @@
-->
<evaluation>
<qa_pair>
- <question>Look at every memo in the instance and add up all the emoji reactions across them. What is the total number of reactions?</question>
- <answer>12</answer>
+ <question>Look at every memo in the instance, including comments, and add up all the emoji reactions across them. What is the total number of reactions?</question>
+ <answer>35</answer>
</qa_pair>
<qa_pair>
<question>How many memos are pinned?</question>
<answer>2</answer>
</qa_pair>
<qa_pair>
- <question>Considering only the memos that are NOT pinned, one of them has more reactions than any other. That memo is about a book the author started reading. What is the title of that book?</question>
- <answer>Deep Work</answer>
+ <question>Considering only memos written by the user johnny, one has more reactions than any other. Give that memo's resource name (memos/...).</question>
+ <answer>memos/johnnyshipped01</answer>
</qa_pair>
<qa_pair>
- <question>Two memos are pinned. One contains external hyperlinks and the other does not. Give the single tag of the pinned memo that contains hyperlinks.</question>
+ <question>Two memos are pinned. One contains a task list and the other does not. Give the single tag of the pinned memo that does NOT contain a task list.</question>
<answer>sponsors</answer>
</qa_pair>
<qa_pair>
<question>How many memos contain at least one fenced code block?</question>
- <answer>2</answer>
+ <answer>4</answer>
</qa_pair>
<qa_pair>
<question>How many distinct users have authored the memos in this instance?</question>
- <answer>2</answer>
+ <answer>4</answer>
</qa_pair>
<qa_pair>
<question>Find the memo that is a cheat sheet of git commands. How many comments does it have?</question>
@@ -57,6 +58,26 @@
</qa_pair>
<qa_pair>
<question>Using the authenticated session, what is the username (login name) of the account these memos belong to?</question>
- <answer>demo</answer>
+ <answer>steven</answer>
+ </qa_pair>
+ <qa_pair>
+ <question>How many spaces is the authenticated user a member of?</question>
+ <answer>4</answer>
+ </qa_pair>
+ <qa_pair>
+ <question>Which space has the most accepted members? Give its title.</question>
+ <answer>Updates</answer>
+ </qa_pair>
+ <qa_pair>
+ <question>Who administers the Travel space? Give that member's username.</question>
+ <answer>bob</answer>
+ </qa_pair>
+ <qa_pair>
+ <question>How many top-level memos (not comments) are placed in the Dev space?</question>
+ <answer>6</answer>
+ </qa_pair>
+ <qa_pair>
+ <question>How many top-level memos (not comments) are not placed in any space?</question>
+ <answer>2</answer>
</qa_pair>
</evaluation>
diff --git a/server/mcp/service_test.go b/server/mcp/service_test.go
index e54f7483b..648755c69 100644
--- a/server/mcp/service_test.go
+++ b/server/mcp/service_test.go
@@ -15,6 +15,7 @@ import (
sdkmcp "github.com/modelcontextprotocol/go-sdk/mcp"
"github.com/stretchr/testify/require"
+ "github.com/usememos/memos/internal/clientip"
"github.com/usememos/memos/internal/profile"
memosproto "github.com/usememos/memos/proto"
)
@@ -111,6 +112,226 @@ func TestMCPToolHandlerForwardsArgumentsAndAuthorization(t *testing.T) {
}, result.StructuredContent)
}
+// TestMCPToolCallForwardsClientAddress covers the in-process hop: the /mcp
+// request resolves the caller (behind a trusted proxy or not), and the API
+// handler that serves the tool call must see that same address, not the
+// httptest placeholder peer (192.0.2.1) that the adapter's synthetic request
+// would otherwise carry into the client-address middleware. It must also not
+// re-open header trust: a forwarding header from an untrusted peer stays
+// ignored on the second pass.
+func TestMCPToolCallForwardsClientAddress(t *testing.T) {
+ tests := []struct {
+ name string
+ remoteAddr string
+ forwardedFor string
+ expectedIP string
+ }{
+ {
+ name: "trusted loopback proxy forwards the client",
+ remoteAddr: "127.0.0.1:5555",
+ forwardedFor: "203.0.113.9",
+ expectedIP: "203.0.113.9",
+ },
+ {
+ name: "direct public peer",
+ remoteAddr: "203.0.113.9:4242",
+ expectedIP: "203.0.113.9",
+ },
+ {
+ name: "forwarding header from an untrusted peer is ignored",
+ remoteAddr: "203.0.113.9:4242",
+ forwardedFor: "198.51.100.1",
+ expectedIP: "203.0.113.9",
+ },
+ {
+ name: "IPv6 client behind a trusted proxy",
+ remoteAddr: "[::1]:5555",
+ forwardedFor: "2001:db8::9",
+ expectedIP: "2001:db8::9",
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ echoServer := echo.New()
+ resolver, err := clientip.ParseTrustedProxies(nil)
+ require.NoError(t, err)
+ echoServer.Use(clientip.Middleware(resolver))
+
+ seen := ""
+ echoServer.GET("/api/v1/memos", func(c *echo.Context) error {
+ seen = clientip.FromContext(c.Request().Context())
+ return c.JSON(http.StatusOK, map[string]any{"memos": []any{}})
+ })
+ service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
+ require.NoError(t, err)
+ service.RegisterRoutes(echoServer)
+ initializeMCP(t, echoServer)
+
+ payload, err := json.Marshal(map[string]any{
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": map[string]any{"name": "memo_list_memos", "arguments": map[string]any{}},
+ })
+ require.NoError(t, err)
+ request := httptest.NewRequest(http.MethodPost, "/mcp", bytes.NewReader(payload))
+ request.RemoteAddr = test.remoteAddr
+ if test.forwardedFor != "" {
+ request.Header.Set("X-Forwarded-For", test.forwardedFor)
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("Accept", "application/json, text/event-stream")
+ recorder := httptest.NewRecorder()
+ echoServer.ServeHTTP(recorder, request)
+ require.Equal(t, http.StatusOK, recorder.Code, recorder.Body.String())
+ require.Equal(t, test.expectedIP, seen)
+ })
+ }
+}
+
+// TestMCPToolCallBindsSpaceResourcesFromPath drives the space tools through the
+// adapter: canonical and nested resource names collapse to path segments, the
+// custom-method suffixes (":accept", ":decline") survive substitution, the
+// path-bound fields removed from the schemas never reappear in the body, and
+// the invitation responses need no body at all.
+func TestMCPToolCallBindsSpaceResourcesFromPath(t *testing.T) {
+ tests := []struct {
+ name string
+ toolName string
+ arguments map[string]any
+ method string
+ path string
+ body map[string]any
+ response map[string]any
+ structured map[string]any
+ }{
+ {
+ name: "accept invitation without body",
+ toolName: "space_accept_space_invitation",
+ arguments: map[string]any{
+ "space": "spaces/team",
+ "invitation": "spaces/team/invitations/sam",
+ },
+ method: http.MethodPost,
+ path: "/api/v1/spaces/team/invitations/sam:accept",
+ body: map[string]any{},
+ response: map[string]any{"name": "spaces/team/members/sam", "role": "USER"},
+ structured: map[string]any{"name": "spaces/team/members/sam", "role": "USER"},
+ },
+ {
+ name: "decline invitation with explicit empty body",
+ toolName: "space_decline_space_invitation",
+ arguments: map[string]any{
+ "space": "team",
+ "invitation": "sam",
+ "body": map[string]any{},
+ },
+ method: http.MethodPost,
+ path: "/api/v1/spaces/team/invitations/sam:decline",
+ body: map[string]any{},
+ response: map[string]any{},
+ structured: map[string]any{},
+ },
+ {
+ name: "update member role without update mask",
+ toolName: "space_update_space_member",
+ arguments: map[string]any{
+ "space": "spaces/team",
+ "member": "spaces/team/members/sam",
+ "body": map[string]any{"role": "ADMIN"},
+ },
+ method: http.MethodPatch,
+ path: "/api/v1/spaces/team/members/sam",
+ body: map[string]any{"role": "ADMIN"},
+ response: map[string]any{"name": "spaces/team/members/sam", "role": "ADMIN"},
+ structured: map[string]any{"name": "spaces/team/members/sam", "role": "ADMIN"},
+ },
+ {
+ name: "partial space update without update mask",
+ toolName: "space_update_space",
+ arguments: map[string]any{
+ "space": "team",
+ "body": map[string]any{"description": "renamed"},
+ },
+ method: http.MethodPatch,
+ path: "/api/v1/spaces/team",
+ body: map[string]any{"description": "renamed"},
+ response: map[string]any{"name": "spaces/team", "title": "Team", "description": "renamed"},
+ structured: map[string]any{"name": "spaces/team", "title": "Team", "description": "renamed"},
+ },
+ {
+ name: "create invitation binds the parent space",
+ toolName: "space_create_space_invitation",
+ arguments: map[string]any{
+ "space": "spaces/team",
+ "body": map[string]any{"invitee": "users/sam", "role": "USER"},
+ },
+ method: http.MethodPost,
+ path: "/api/v1/spaces/team/invitations",
+ body: map[string]any{"invitee": "users/sam", "role": "USER"},
+ response: map[string]any{"name": "spaces/team/invitations/sam"},
+ structured: map[string]any{"name": "spaces/team/invitations/sam"},
+ },
+ {
+ name: "delete member from nested name",
+ toolName: "space_delete_space_member",
+ arguments: map[string]any{
+ "space": "spaces/team",
+ "member": "spaces/team/members/sam",
+ },
+ method: http.MethodDelete,
+ path: "/api/v1/spaces/team/members/sam",
+ response: map[string]any{},
+ structured: map[string]any{},
+ },
+ }
+
+ for _, test := range tests {
+ t.Run(test.name, func(t *testing.T) {
+ echoServer := echo.New()
+ routeHits := 0
+ echoServer.Any("/api/v1/spaces/*", func(c *echo.Context) error {
+ routeHits++
+ require.Equal(t, test.method, c.Request().Method)
+ require.Equal(t, test.path, c.Request().URL.Path)
+ require.Empty(t, c.QueryParam("updateMask"))
+ if test.body != nil {
+ body := map[string]any{}
+ require.NoError(t, json.NewDecoder(c.Request().Body).Decode(&body))
+ require.Equal(t, test.body, body)
+ require.NotContains(t, body, "name")
+ require.NotContains(t, body, "user")
+ } else {
+ require.Empty(t, c.Request().Header.Get("Content-Type"))
+ }
+ return c.JSON(http.StatusOK, test.response)
+ })
+
+ service, err := NewMCPService(&profile.Profile{Version: "test-version"}, echoServer)
+ require.NoError(t, err)
+ service.RegisterRoutes(echoServer)
+
+ initializeMCP(t, echoServer)
+ response := postMCP(t, echoServer, map[string]any{
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": map[string]any{
+ "name": test.toolName,
+ "arguments": test.arguments,
+ },
+ })
+
+ result, ok := response["result"].(map[string]any)
+ require.True(t, ok)
+ require.NotEqual(t, true, result["isError"], result)
+ require.Equal(t, test.structured, result["structuredContent"])
+ require.Equal(t, 1, routeHits)
+ })
+ }
+}
+
func TestMCPProtocolListsCuratedToolsOnly(t *testing.T) {
echoServer := echo.New()
diff --git a/store/db/sqlite/sqlite.go b/store/db/sqlite/sqlite.go
index 549514740..f54c3cb94 100644
--- a/store/db/sqlite/sqlite.go
+++ b/store/db/sqlite/sqlite.go
@@ -42,6 +42,14 @@ func NewDB(profile *profile.Profile) (store.Driver, error) {
// - Journal mode set to WAL: it's the recommended journal mode for most applications
// as it prevents locking issues.
// - mmap size set to 0: it disables memory mapping, which can cause OOM errors on some systems.
+ // - Transactions begin IMMEDIATE: several drivers' transactions read before they
+ // write (a membership or lifecycle check, then an insert). With the default
+ // DEFERRED mode such a transaction holds a read snapshot when it tries to
+ // write, and if any other connection committed in between (for example the
+ // asynchronous personal-access-token last-used update that runs on every
+ // token-authenticated request) SQLite refuses the upgrade with SQLITE_BUSY
+ // at once, without consulting busy_timeout. Taking the write lock up front
+ // makes those transactions queue behind the busy handler instead.
//
// Notes:
// - When using the `modernc.org/sqlite` driver, each pragma must be prefixed with `_pragma=`.
@@ -50,7 +58,7 @@ func NewDB(profile *profile.Profile) (store.Driver, error) {
// - https://pkg.go.dev/modernc.org/sqlite#Driver.Open
// - https://www.sqlite.org/sharedcache.html
// - https://www.sqlite.org/pragma.html
- sqliteDB, err := sql.Open("sqlite", profile.DSN+"?_pragma=foreign_keys(0)&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=mmap_size(0)")
+ sqliteDB, err := sql.Open("sqlite", profile.DSN+"?_pragma=foreign_keys(0)&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=mmap_size(0)&_txlock=immediate")
if err != nil {
return nil, errors.Wrapf(err, "failed to open db with dsn: %s", profile.DSN)
}
diff --git a/store/test/space_concurrency_test.go b/store/test/space_concurrency_test.go
new file mode 100644
index 000000000..c1e09152f
--- /dev/null
+++ b/store/test/space_concurrency_test.go
@@ -0,0 +1,74 @@
+package test
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+ "google.golang.org/protobuf/types/known/timestamppb"
+
+ storepb "github.com/usememos/memos/proto/gen/store"
+ "github.com/usememos/memos/store"
+)
+
+// TestSpaceWritesSurviveConcurrentTokenUsageUpdates reproduces the shape of a
+// personal-access-token authenticated request: the authenticator records the
+// token's last-used time asynchronously on every request, while the request
+// handler runs a transaction that reads (the actor's lifecycle state) before it
+// writes. On SQLite a DEFERRED transaction that has read cannot upgrade to a
+// write once another connection has committed, and fails with SQLITE_BUSY at
+// once instead of waiting; the store opens its transactions IMMEDIATE so these
+// writes queue behind the busy handler. The other drivers take row locks and
+// are unaffected, but the scenario is valid for all of them.
+func TestSpaceWritesSurviveConcurrentTokenUsageUpdates(t *testing.T) {
+ ctx := context.Background()
+ ts := NewTestingStore(ctx, t)
+ defer ts.Close()
+
+ owner, err := ts.CreateUser(ctx, &store.User{Username: "space-owner", Role: store.RoleUser, PasswordHash: "hash"})
+ require.NoError(t, err)
+ invitee, err := ts.CreateUser(ctx, &store.User{Username: "space-invitee", Role: store.RoleUser, PasswordHash: "hash"})
+ require.NoError(t, err)
+ require.NoError(t, ts.AddUserPersonalAccessToken(ctx, owner.ID, &storepb.PersonalAccessTokensUserSetting_PersonalAccessToken{
+ TokenId: "pat-1",
+ TokenHash: "pat-hash-1",
+ }))
+
+ stop := make(chan struct{})
+ var wg sync.WaitGroup
+ wg.Go(func() {
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ // Mirrors Authenticator.recordPATUsage: a detached context and a
+ // fresh timestamp so every iteration is a real write.
+ if err := ts.UpdatePATLastUsed(context.Background(), owner.ID, "pat-1", timestamppb.Now()); err != nil {
+ t.Errorf("update PAT last used: %v", err)
+ return
+ }
+ }
+ })
+
+ const iterations = 40
+ for i := range iterations {
+ space, err := ts.CreateSpace(ctx, &store.Space{UID: fmt.Sprintf("race-%d", i), Title: "Race"}, owner.ID)
+ require.NoError(t, err, "create space %d", i)
+ _, err = ts.CreateSpaceInvitation(ctx, &store.SpaceInvitation{
+ SpaceID: space.ID,
+ UserID: invitee.ID,
+ Role: store.SpaceMemberRoleUser,
+ }, owner.ID)
+ require.NoError(t, err, "create invitation %d", i)
+ }
+ close(stop)
+ wg.Wait()
+
+ spaces, err := ts.ListSpaces(ctx, &store.FindSpace{MemberUserID: &owner.ID})
+ require.NoError(t, err)
+ require.Len(t, spaces, iterations)
+}
diff --git a/store/test/space_parent_lock_test.go b/store/test/space_parent_lock_test.go
index 2791ec21f..0e75f4eb3 100644
--- a/store/test/space_parent_lock_test.go
+++ b/store/test/space_parent_lock_test.go
@@ -11,9 +11,17 @@ import (
"github.com/usememos/memos/store"
)
-func TestSQLiteStaleRelationshipWriteCannotOutliveDeletedParent(t *testing.T) {
+// TestSQLiteRelationshipWriteSerializesWithParentDelete confirms how SQLite
+// keeps a relationship write from outliving a deleted parent. The store opens
+// every transaction IMMEDIATE, so a transaction that has read the parent holds
+// the write lock until it ends: a concurrent delete waits instead of committing
+// underneath it (with DEFERRED transactions the delete would commit and the
+// later insert would fail with SQLITE_BUSY at once). Once the transaction ends
+// the delete proceeds, and a fresh relationship write for the deleted parent
+// fails on its own read.
+func TestSQLiteRelationshipWriteSerializesWithParentDelete(t *testing.T) {
if getDriverFromEnv() != "sqlite" {
- t.Skip("this test confirms SQLite's stale-snapshot write serialization")
+ t.Skip("this test confirms SQLite's IMMEDIATE transaction serialization")
}
ctx := context.Background()
@@ -26,23 +34,45 @@ func TestSQLiteStaleRelationshipWriteCannotOutliveDeletedParent(t *testing.T) {
space, err := ts.CreateSpace(ctx, &store.Space{UID: "sqlite-stale-space", Title: "SQLite Stale Parent"}, owner.ID)
require.NoError(t, err)
- staleTx, err := ts.GetDriver().GetDB().BeginTx(ctx, nil)
+ writer, err := ts.GetDriver().GetDB().BeginTx(ctx, nil)
require.NoError(t, err)
- staleTxOpen := true
+ writerOpen := true
defer func() {
- if staleTxOpen {
- _ = staleTx.Rollback()
+ if writerOpen {
+ _ = writer.Rollback()
}
}()
var storedUserID int32
- require.NoError(t, staleTx.QueryRowContext(ctx, "SELECT id FROM user WHERE id = ?", target.ID).Scan(&storedUserID))
+ require.NoError(t, writer.QueryRowContext(ctx, "SELECT id FROM user WHERE id = ?", target.ID).Scan(&storedUserID))
- _, err = ts.DeleteUser(ctx, &store.DeleteUser{ID: target.ID})
+ deleteDone := make(chan error, 1)
+ go func() {
+ _, deleteErr := ts.DeleteUser(context.Background(), &store.DeleteUser{ID: target.ID})
+ deleteDone <- deleteErr
+ }()
+ select {
+ case deleteErr := <-deleteDone:
+ require.FailNowf(t, "user deletion did not wait", "deletion finished while a transaction that read the user was open: %v", deleteErr)
+ case <-time.After(300 * time.Millisecond):
+ }
+
+ // The transaction that read the parent may still write it: the delete has
+ // not happened yet, and it will clean this row up when it does.
+ _, err = writer.ExecContext(ctx, `INSERT INTO space_member (space_id, user_id, status, role) VALUES (?, ?, 'INVITED', 'USER')`, space.ID, target.ID)
require.NoError(t, err)
- _, err = staleTx.ExecContext(ctx, `INSERT INTO space_member (space_id, user_id, status, role) VALUES (?, ?, 'INVITED', 'USER')`, space.ID, target.ID)
- require.Error(t, err, "a transaction with a stale parent snapshot must not upgrade to write an orphan relationship")
- require.NoError(t, staleTx.Rollback())
- staleTxOpen = false
+ require.NoError(t, writer.Commit())
+ writerOpen = false
+
+ select {
+ case deleteErr := <-deleteDone:
+ require.NoError(t, deleteErr)
+ case <-time.After(15 * time.Second):
+ require.FailNow(t, "timed out waiting for user deletion after the transaction ended")
+ }
+
+ // After the delete, a relationship write for the parent fails on its own read.
+ _, err = ts.CreateSpaceInvitation(ctx, &store.SpaceInvitation{SpaceID: space.ID, UserID: target.ID, Role: store.SpaceMemberRoleUser}, owner.ID)
+ require.ErrorIs(t, err, store.ErrSpaceMemberNotActive)
var relationshipCount int
require.NoError(t, ts.GetDriver().GetDB().QueryRowContext(ctx,
@@ -54,7 +84,7 @@ func TestSQLiteStaleRelationshipWriteCannotOutliveDeletedParent(t *testing.T) {
func TestSpaceInvitationWaitsForConcurrentUserDelete(t *testing.T) {
driver := getDriverFromEnv()
if driver == "sqlite" || driver == "d1" {
- t.Skip("SQLite serializes the competing writes and rejects stale transaction upgrades; D1 has no row locks")
+ t.Skip("SQLite transactions begin IMMEDIATE and serialize competing writes without row locks; D1 has no row locks")
}
setupCtx := context.Background()
@@ -117,7 +147,7 @@ func TestSpaceInvitationWaitsForConcurrentUserDelete(t *testing.T) {
func TestSpaceInvitationWaitsForConcurrentSpaceDelete(t *testing.T) {
driver := getDriverFromEnv()
if driver == "sqlite" || driver == "d1" {
- t.Skip("SQLite serializes the competing writes and rejects stale transaction upgrades; D1 has no row locks")
+ t.Skip("SQLite transactions begin IMMEDIATE and serialize competing writes without row locks; D1 has no row locks")
}
setupCtx := context.Background()