Repository navigation
feat(go): implement safe event writes (#167) - #189
Conversation
Co-authored-by: Copilot <[email protected]> Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
Warning Review limit reached
Next review available in: 50 minutes You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughThe CLI now supports ChangesEvent write commands
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant CLI
participant Execute
participant EventWriteWorkflow
participant PartifulClient
participant Firestore
CLI->>Execute: Invoke event write command
Execute->>EventWriteWorkflow: Parse and execute request
EventWriteWorkflow->>PartifulClient: Submit create or cancel mutation
EventWriteWorkflow->>Firestore: Apply update patch
PartifulClient-->>EventWriteWorkflow: Return validated mutation response
Firestore-->>EventWriteWorkflow: Return validated patch response
EventWriteWorkflow-->>CLI: Return planned or submitted result
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Co-authored-by: Copilot <[email protected]> Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (5)
internal/app/event_write_input.go (1)
376-381: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winValidate flag values before you place them in the JSON document.
Lines 377 and 380 insert the raw flag text into
json.RawMessagewithout validation.decodeNullablePositiveIntegerthen decodes with a stream decoder and does not check for trailing tokens, so--guest-limit '5 garbage'decodes as5.--notify-guests TRUEworks only because of thestrings.ToLowercall, and any other text falls through to a decode error. Parse both values explicitly so the accepted input set matches the documented input schema.♻️ Proposed stricter flag decoding
if value, ok := values["--notify-guests"]; ok { - document["notifyGuests"] = json.RawMessage(strings.ToLower(value)) + switch strings.ToLower(strings.TrimSpace(value)) { + case "true": + document["notifyGuests"] = json.RawMessage("true") + case "false": + document["notifyGuests"] = json.RawMessage("false") + default: + return nil, eventWriteInputFailure("NOTIFY_GUESTS_INVALID", "notifyGuests must be true or false.") + } } if value, ok := values["--guest-limit"]; ok { - document["guestLimit"] = json.RawMessage(value) + parsed, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil || parsed < 1 { + return nil, eventWriteInputFailure("GUEST_LIMIT_INVALID", "Guest limit must be a positive integer or null.") + } + document["guestLimit"] = json.RawMessage(strconv.Itoa(parsed)) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/app/event_write_input.go` around lines 376 - 381, Validate and parse the --notify-guests and --guest-limit values before assigning document["notifyGuests"] and document["guestLimit"], rather than wrapping raw text in json.RawMessage. Use strict parsing that rejects trailing tokens, accepts only the documented boolean values for notify-guests, and enforces the documented positive-integer constraints for guest-limit; return the appropriate validation error instead of inserting invalid JSON.tests/remote-api-contract.test.js (1)
2151-2158: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the duplicated revision literals.
The revision string
2026-08-12.4is asserted at lines 502-503, 1619-1620, and 2158. Line 2155 and line 2157 also assertspec.info.versiontwice, which is redundant onceshippedRevisionequalsdocumentedRevision. Define one module-level constant for the expected revision and reuse it, so the next promotion changes one line.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/remote-api-contract.test.js` around lines 2151 - 2158, Define a single module-level expected revision constant in the test and replace the duplicated 2026-08-12.4 literals across the assertions, including the checks near shippedRevision, documentedRevision, and appSource. Remove the redundant duplicate spec.info.version assertion, retaining the comparison against the shared expected revision through the existing shippedRevision/documentedRevision values.internal/app/event_write.go (1)
497-533: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the redundant check and the unused parameters.
Three items reduce clarity in these functions:
- Line 498 rejects
remote.FieldAbsent, and line 510 then rejects any state other thanremote.FieldValue. The second check makes the first one redundant. Keep one check.buildUpdatePreconditionsdiscardscurrentUserIDwith_ = currentUserIDat line 531. The caller already verified ownership at line 222. Drop the parameter.buildUpdateRequestdiscardseventwith_ = eventat line 611. Drop the parameter.Also applies to: 537-546, 607-613
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/app/event_write.go` around lines 497 - 533, Simplify the event update helpers by removing redundant checks and unused parameters: in buildUpdatePreconditions, keep only the HasGuests state validation, remove the unused currentUserID parameter and its discard assignment, and update all callers; in buildUpdateRequest, remove the unused event parameter and its discard assignment, updating callers accordingly.internal/app/events_write_test.go (1)
544-609: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the host check and the structured input path.
The suite does not cover two reviewed safeguards:
events.cancelandevents.updatewith anownerIdslist that excludes the session user, which must returnpermission.denied.--inputwith a JSON document, plus theINPUT_SOURCE_CONFLICTfailure when--inputis combined with a field flag.Also note that these subtests mutate the shared
dependenciesvalue and consume the sharedMutationRandomreader, so the cases depend on execution order. Build the dependencies inside each subtest to remove that coupling.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/app/events_write_test.go` around lines 544 - 609, Expand TestExecuteEventCancelFailsClosedOnMalformedFactsAndSubmissionUncertainty to cover events.cancel and events.update ownerIds that exclude the session user, asserting permission.denied, and cover JSON --input plus INPUT_SOURCE_CONFLICT when combined with a field flag. Create fresh eventWriteDependencies and MutationRandom state inside each subtest instead of sharing them across cases, preserving existing assertions while removing execution-order coupling.internal/remote/event_writes.go (1)
265-280: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winReject an empty update mask in the transport.
FirestorePatchEventsends the patch even whenupdateMaskis empty. Firestore then replaces the whole document withdocument, which deletes every unlisted field.buildUpdateRequestalways appendsupdatedBy, so the current callers are safe. Add the guard so a future caller cannot destroy event data.🛡️ Proposed guard
if client.HTTP == nil { return fmt.Errorf("%w: firestore transport", ErrUnavailable) } + if len(updateMask) == 0 { + return fmt.Errorf("%w: firestore update mask", ErrProtocolChanged) + } payload, _ := json.Marshal(document)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/remote/event_writes.go` around lines 265 - 280, Update FirestorePatchEvent to reject an empty updateMask before marshaling or sending the patch request, returning the package’s established invalid-argument error with a clear message. Preserve the existing behavior for non-empty masks, including updatedBy handling by current callers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/app/app.go`:
- Around line 350-381: Update schemaSuccessSchema’s safety.kind enum to include
the consequential-action value used by consequentialActionSafety(). Preserve the
existing read-only, local-mutation, and standard-mutation values so success
envelopes for all commands remain valid.
In `@internal/app/event_write.go`:
- Around line 747-764: Update requiredCurrentEventTime and
optionalCurrentEventTime to accept command and pretty parameters, and pass them
to eventWriteProtocolChangedFailure instead of hardcoding events.update,
EVENT_UPDATE_PROTOCOL_CHANGED, and false. Update buildCancelPreconditions and
all other callers to provide their command path and --pretty state, and
propagate pretty through eventPreconditionFailure. Remove the prettyFalse
package variable and preserve caller-specific command metadata, protocol codes,
and output formatting.
In `@internal/remote/event_writes.go`:
- Line 238: Update both deferred response body cleanup calls in the relevant
event-writing functions to explicitly discard the return value from
response.Body.Close(), satisfying errcheck while preserving deferred cleanup
behavior.
In `@internal/remote/events.go`:
- Around line 440-447: Update internal/remote/events.go lines 440-447 in the
event decoding path to pass nullAllowed=true when decoding guestCount and
hasGuests, while preserving the strict remote.FieldValue requirement in
buildCancelPreconditions. In internal/remote/posters.go lines 175-190, update
the blurHash decoder to map explicit JSON null to a nil pointer instead of
returning ErrProtocolChanged, unless the reviewed remote contract explicitly
forbids null.
---
Nitpick comments:
In `@internal/app/event_write_input.go`:
- Around line 376-381: Validate and parse the --notify-guests and --guest-limit
values before assigning document["notifyGuests"] and document["guestLimit"],
rather than wrapping raw text in json.RawMessage. Use strict parsing that
rejects trailing tokens, accepts only the documented boolean values for
notify-guests, and enforces the documented positive-integer constraints for
guest-limit; return the appropriate validation error instead of inserting
invalid JSON.
In `@internal/app/event_write.go`:
- Around line 497-533: Simplify the event update helpers by removing redundant
checks and unused parameters: in buildUpdatePreconditions, keep only the
HasGuests state validation, remove the unused currentUserID parameter and its
discard assignment, and update all callers; in buildUpdateRequest, remove the
unused event parameter and its discard assignment, updating callers accordingly.
In `@internal/app/events_write_test.go`:
- Around line 544-609: Expand
TestExecuteEventCancelFailsClosedOnMalformedFactsAndSubmissionUncertainty to
cover events.cancel and events.update ownerIds that exclude the session user,
asserting permission.denied, and cover JSON --input plus INPUT_SOURCE_CONFLICT
when combined with a field flag. Create fresh eventWriteDependencies and
MutationRandom state inside each subtest instead of sharing them across cases,
preserving existing assertions while removing execution-order coupling.
In `@internal/remote/event_writes.go`:
- Around line 265-280: Update FirestorePatchEvent to reject an empty updateMask
before marshaling or sending the patch request, returning the package’s
established invalid-argument error with a clear message. Preserve the existing
behavior for non-empty masks, including updatedBy handling by current callers.
In `@tests/remote-api-contract.test.js`:
- Around line 2151-2158: Define a single module-level expected revision constant
in the test and replace the duplicated 2026-08-12.4 literals across the
assertions, including the checks near shippedRevision, documentedRevision, and
appSource. Remove the redundant duplicate spec.info.version assertion, retaining
the comparison against the shared expected revision through the existing
shippedRevision/documentedRevision values.
🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID: d9feb18a-2c4a-4817-a5ac-8a972f12b244
📒 Files selected for processing (12)
docs/CLI-PRODUCT-CONTRACT.mddocs/REMOTE-API-CONTRACT.mdinternal/app/app.gointernal/app/event_write.gointernal/app/event_write_input.gointernal/app/events_write_test.gointernal/app/execute_test.gointernal/remote/event_writes.gointernal/remote/events.gointernal/remote/posters.gospec/partiful.api-evidence.jsontests/remote-api-contract.test.js
Co-authored-by: Copilot <[email protected]> Copilot-Session: 7b842425-e150-41a6-9cd2-6b0842fe8c01
Summary
Implements the evidence-backed Go event-write contract for #167.
events create,events update, and confirmedevents cancelthroughapp.Execute2026-08-12.4No live Partiful mutation or credential access was used.
Validation
go test -race ./...go vet ./...go build ./...go mod verifynpm test -- tests/remote-api-contract.test.jsnpm run typecheckCloses #167.
Summary by CodeRabbit
2026-08-12.4.