Files
pad/internal/items/validate_test.go
T
xarmian bed933d7fd feat(items): field-level PATCH + conflict envelope + read-only version history (TASK-2022) (#876)
* feat(items): field-level PATCH + conflict envelope + version history

Adds three related item-update primitives (TASK-2022 / IDEA-1480):

- Field-level merge: PATCH `fields_patch` shallow-merges onto the item's
  current fields INSIDE the write transaction (null deletes a key), so
  concurrent single-field updates no longer clobber each other via the
  full-blob read-modify-write. `pad item update` and the MCP `pad_item.update`
  action now send only the changed keys.
- Optimistic concurrency: optional `expected_updated_at` on update; on
  mismatch the store returns *UpdateConflictError and the handler emits the
  pad-structured-error/v1 conflict envelope (HTTP 409, code=update_conflict).
  Surfaced on CLI (`--expected-updated-at`) and MCP (`expected_updated_at`).
- Read-only version history: `pad item history <ref>` (alias `versions`) and
  MCP `pad_item.history`, reusing the existing item_versions store + versions
  endpoint (no new store, no schema change).

MCP ToolSurfaceVersion bumped 0.9 -> 1.0 (new action + param; update
behavior change). No migration required.

Claude-Session: https://claude.ai/code/session_019knGmnHcx5rrgWXQ8V8DZS

* fix(items): address Codex review — dispatcher fields_patch, OCC ordering, date/required guards

Round 1+2 review fixes for TASK-2022:
- HTTP MCP dispatcher (dispatch_http_advanced.go) now sends fields_patch (only
  changed keys) instead of a client-side merged full fields blob, and forwards
  expected_updated_at — remote MCP callers get the same race-free merge +
  optimistic concurrency the CLI/HTTP paths do.
- ValidatePartialFields rejects null-deleting a schema-declared REQUIRED field
  (would otherwise persist a blob the full-update validator rejects).
- Open-children guard on the fields_patch path merges the patch onto the IN-TX
  locked row inside the precheck (not a stale pre-lock preview), so a
  priority-only patch can't false-fire the guard.
- Optimistic-concurrency check now runs BEFORE the open-children precheck in the
  store, so a stale expected_updated_at yields update_conflict (not
  open_children) — single in-tx re-read shared by both.
- Date auto-population on the patch path only fills an EMPTY current date; an
  existing end_date the caller isn't touching is preserved.

Tests added for each fix.

Claude-Session: https://claude.ai/code/session_019knGmnHcx5rrgWXQ8V8DZS
2026-07-08 16:47:34 -04:00

415 lines
10 KiB
Go

package items
import (
"testing"
"github.com/PerpetualSoftware/pad/internal/models"
)
func taskSchema() models.CollectionSchema {
return models.CollectionSchema{
Fields: []models.FieldDef{
{
Key: "status",
Label: "Status",
Type: "select",
Options: []string{"open", "in-progress", "done", "cancelled"},
Default: "open",
Required: true,
},
{
Key: "priority",
Label: "Priority",
Type: "select",
Options: []string{"low", "medium", "high", "critical"},
Default: "medium",
},
{
Key: "assignee",
Label: "Assignee",
Type: "text",
},
{
Key: "due_date",
Label: "Due Date",
Type: "date",
},
{
Key: "effort_hours",
Label: "Effort",
Type: "number",
},
{
Key: "done",
Label: "Done",
Type: "checkbox",
},
},
}
}
func TestValidateFields_RequiredWithDefault(t *testing.T) {
schema := taskSchema()
fields := map[string]any{}
err := ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
// Required field "status" should have been filled with default
if fields["status"] != "open" {
t.Errorf("expected status default 'open', got %v", fields["status"])
}
// Optional field "priority" should have been filled with default
if fields["priority"] != "medium" {
t.Errorf("expected priority default 'medium', got %v", fields["priority"])
}
}
func TestValidateFields_RequiredMissingNoDefault(t *testing.T) {
schema := models.CollectionSchema{
Fields: []models.FieldDef{
{Key: "name", Label: "Name", Type: "text", Required: true},
},
}
fields := map[string]any{}
err := ValidateFields(fields, schema)
if err == nil {
t.Fatal("expected error for missing required field without default")
}
}
func TestValidateFields_SelectInvalid(t *testing.T) {
schema := taskSchema()
fields := map[string]any{
"status": "invalid-value",
}
err := ValidateFields(fields, schema)
if err == nil {
t.Fatal("expected error for invalid select value")
}
}
func TestValidateFields_SelectValid(t *testing.T) {
schema := taskSchema()
fields := map[string]any{
"status": "done",
"priority": "high",
}
err := ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
}
func TestValidateFields_NumberType(t *testing.T) {
schema := taskSchema()
// Valid number
fields := map[string]any{
"effort_hours": float64(5),
}
err := ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error for valid number, got: %v", err)
}
// Invalid number
fields = map[string]any{
"effort_hours": "not-a-number",
}
err = ValidateFields(fields, schema)
if err == nil {
t.Fatal("expected error for string in number field")
}
}
func TestValidateFields_CheckboxType(t *testing.T) {
schema := taskSchema()
// Valid boolean
fields := map[string]any{
"done": true,
}
err := ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error for valid checkbox, got: %v", err)
}
// Invalid boolean
fields = map[string]any{
"done": "yes",
}
err = ValidateFields(fields, schema)
if err == nil {
t.Fatal("expected error for string in checkbox field")
}
}
func TestValidateFields_DateType(t *testing.T) {
schema := taskSchema()
// Valid date
fields := map[string]any{
"due_date": "2026-03-25",
}
err := ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error for valid date, got: %v", err)
}
// Valid RFC3339
fields = map[string]any{
"due_date": "2026-03-25T10:00:00Z",
}
err = ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error for valid RFC3339, got: %v", err)
}
// Invalid date
fields = map[string]any{
"due_date": "not-a-date",
}
err = ValidateFields(fields, schema)
if err == nil {
t.Fatal("expected error for invalid date")
}
// Empty date is OK (optional)
fields = map[string]any{
"due_date": "",
}
err = ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error for empty date, got: %v", err)
}
}
func TestValidateFields_TextType(t *testing.T) {
schema := taskSchema()
// Valid
fields := map[string]any{
"assignee": "alice",
}
err := ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
// Invalid
fields = map[string]any{
"assignee": 42,
}
err = ValidateFields(fields, schema)
if err == nil {
t.Fatal("expected error for number in text field")
}
}
func TestValidateFields_MultiSelect(t *testing.T) {
schema := models.CollectionSchema{
Fields: []models.FieldDef{
{
Key: "labels",
Label: "Labels",
Type: "multi_select",
Options: []string{"bug", "feature", "docs"},
},
},
}
// Valid
fields := map[string]any{
"labels": []any{"bug", "feature"},
}
err := ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
// Invalid option
fields = map[string]any{
"labels": []any{"bug", "invalid"},
}
err = ValidateFields(fields, schema)
if err == nil {
t.Fatal("expected error for invalid multi_select option")
}
}
func TestValidateFields_JSONType(t *testing.T) {
schema := models.CollectionSchema{
Fields: []models.FieldDef{
{Key: "arguments", Label: "Arguments", Type: "json"},
},
}
cases := []struct {
name string
val any
wantErr bool
}{
{"array", []any{"a", "b"}, false},
{"object", map[string]any{"k": "v"}, false},
{"nil", nil, false}, // optional + nil is allowed
// Scalars are rejected: a generic web text input would corrupt a
// structured field by emitting strings like `"[]"` instead of
// arrays. Use "text" / "number" / "checkbox" for scalars.
{"string-rejected", "hello", true},
{"number-rejected", float64(42), true},
{"bool-rejected", true, true},
{"struct-not-decoded", struct{ X int }{1}, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
fields := map[string]any{"arguments": tc.val}
err := ValidateFields(fields, schema)
if tc.wantErr && err == nil {
t.Fatalf("expected error, got nil")
}
if !tc.wantErr && err != nil {
t.Fatalf("expected no error, got: %v", err)
}
})
}
}
func TestValidateFields_PatternMatch(t *testing.T) {
schema := models.CollectionSchema{
Fields: []models.FieldDef{
{
Key: "invocation_slug",
Label: "Invocation slug",
Type: "text",
Pattern: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`,
},
},
}
cases := []struct {
name string
val string
wantErr bool
}{
{"valid-kebab", "ship", false},
{"valid-with-digits", "ship-blog-2", false},
{"valid-min-two-chars", "ab", false},
{"empty-allowed", "", false},
{"single-char-rejected", "a", true},
{"uppercase", "Ship", true},
{"underscore", "ship_blog", true},
{"leading-dash", "-ship", true},
{"trailing-dash", "ship-", true},
{"space", "ship blog", true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
fields := map[string]any{"invocation_slug": tc.val}
err := ValidateFields(fields, schema)
if tc.wantErr && err == nil {
t.Fatalf("expected error for %q, got nil", tc.val)
}
if !tc.wantErr && err != nil {
t.Fatalf("expected no error for %q, got: %v", tc.val, err)
}
})
}
}
func TestValidateFields_InvalidPattern(t *testing.T) {
schema := models.CollectionSchema{
Fields: []models.FieldDef{
{
Key: "field",
Label: "Field",
Type: "text",
Pattern: `[unclosed`,
},
},
}
fields := map[string]any{"field": "value"}
err := ValidateFields(fields, schema)
if err == nil {
t.Fatal("expected error for invalid schema pattern")
}
}
func TestValidateFields_DefaultsApplied(t *testing.T) {
schema := taskSchema()
fields := map[string]any{
"assignee": "bob",
}
err := ValidateFields(fields, schema)
if err != nil {
t.Fatalf("expected no error, got: %v", err)
}
// Defaults should be applied
if fields["status"] != "open" {
t.Errorf("expected status default, got %v", fields["status"])
}
if fields["priority"] != "medium" {
t.Errorf("expected priority default, got %v", fields["priority"])
}
// Explicitly set field should remain
if fields["assignee"] != "bob" {
t.Errorf("expected assignee 'bob', got %v", fields["assignee"])
}
}
// --- ValidatePartialFields (TASK-2022 field-level PATCH) ---
func TestValidatePartialFields_ValidatesOnlyPresentKeys(t *testing.T) {
schema := taskSchema()
// Patch touches only priority; status (required) is absent and must NOT
// be flagged missing, and no defaults should be injected.
patch := map[string]any{"priority": "high"}
if err := ValidatePartialFields(patch, schema); err != nil {
t.Fatalf("expected no error validating a partial patch, got: %v", err)
}
if _, injected := patch["status"]; injected {
t.Errorf("ValidatePartialFields must NOT inject defaults for absent keys; got %v", patch)
}
}
func TestValidatePartialFields_RejectsBadEnum(t *testing.T) {
schema := taskSchema()
patch := map[string]any{"status": "not-a-status"}
if err := ValidatePartialFields(patch, schema); err == nil {
t.Fatal("expected an error for an out-of-enum select value in the patch")
}
}
func TestValidatePartialFields_AllowsOrphanKeys(t *testing.T) {
schema := taskSchema()
patch := map[string]any{"pad_source_url": "https://example.com"}
if err := ValidatePartialFields(patch, schema); err != nil {
t.Fatalf("orphan (non-schema) keys should be allowed, got: %v", err)
}
}
func TestValidatePartialFields_RejectsDeletingRequiredField(t *testing.T) {
schema := taskSchema()
// status is required — a null-delete of it would leave an invalid blob.
patch := map[string]any{"status": nil}
if err := ValidatePartialFields(patch, schema); err == nil {
t.Fatal("expected an error deleting a required field via null")
}
}
func TestValidatePartialFields_AllowsDeletingOptionalField(t *testing.T) {
schema := taskSchema()
// priority is optional — null-delete is fine.
patch := map[string]any{"priority": nil}
if err := ValidatePartialFields(patch, schema); err != nil {
t.Fatalf("deleting an optional field via null should be allowed, got: %v", err)
}
}