Skip to content

fix: Reuse Objective-C SDK installation on migration#462

Open
Branchrise wants to merge 3 commits into
parse-community:mainfrom
Branchrise:fix/reuse-objc-installation
Open

fix: Reuse Objective-C SDK installation on migration#462
Branchrise wants to merge 3 commits into
parse-community:mainfrom
Branchrise:fix/reuse-objc-installation

Conversation

@Branchrise

@Branchrise Branchrise commented May 11, 2026

Copy link
Copy Markdown

New Pull Request Checklist

Issue Description

When migrating from the Objective-C SDK, migratingFromObjcSDK copies the Objective-C Keychain installationId into the Swift SDK current installation, but it does not reuse the existing _Installation object from Parse Server. The current installation can therefore remain without the existing objectId, so a later save may create a new installation instead of using the migrated one.

Closes: #426

Approach

When the Objective-C Keychain contains an installationId, initialization now queries _Installation by that installationId using a reload cache policy. If an existing installation is found, it becomes the current installation and is persisted back to the Swift SDK storage/keychain, preserving the existing objectId.

If the lookup misses, the fallback still migrates the Objective-C installationId, but it avoids carrying over an unrelated saved objectId from the current Swift installation.

Added regression coverage for both the empty lookup fallback and the existing-installation reuse path.

TODOs before merging

  • none

Testing

  • git diff --check
  • Attempted swift test --filter InitializeSDKTests locally with Swift 6.3.1 on Windows after installing the Swift toolchain and loading the Visual Studio Build Tools environment. The package currently fails before the targeted tests due to an existing Swift 6 parser error in Sources/ParseSwift/Coding/ParseEncoder.swift, outside this PR's changed files: 'let' binding pattern cannot appear in an expression.

Summary by CodeRabbit

  • Bug Fixes

    • Improved Objective-C SDK migration: better detection of when to migrate, robust lookup and fallback behavior to ensure installation identifiers and existing installation data are synchronized and preserved.
  • Tests

    • Expanded migration tests to cover lookup success, lookup failure, and preservation of pre-existing installations.

Review Change Stack

@parse-github-assistant

Copy link
Copy Markdown

I will reformat the title to use the proper commit message syntax.

@parse-github-assistant parse-github-assistant Bot changed the title fix: reuse Objective-C SDK installation on migration fix: Reuse Objective-C SDK installation on migration May 11, 2026
@parse-github-assistant

parse-github-assistant Bot commented May 11, 2026

Copy link
Copy Markdown

🚀 Thanks for opening this pull request! We appreciate your effort in improving the project. Please let us know once your pull request is ready for review.

Tip

  • Keep pull requests small. Large PRs will be rejected. Break complex features into smaller, incremental PRs.
  • Use Test Driven Development. Write failing tests before implementing functionality. Ensure tests pass.
  • Group code into logical blocks. Add a short comment before each block to explain its purpose.
  • We offer conceptual guidance. Coding is up to you. PRs must be merge-ready for human review.
  • Our review focuses on concept, not quality. PRs with code issues will be rejected. Use an AI agent.
  • Human review time is precious. Avoid review ping-pong. Inspect and test your AI-generated code.

Note

Please respond to review comments from AI agents just like you would to comments from a human reviewer. Let the reviewer resolve their own comments, unless they have reviewed and accepted your commit, or agreed with your explanation for why the feedback was incorrect.

Caution

Pull requests must be written using an AI agent with human supervision. Pull requests written entirely by a human will likely be rejected, because of lower code quality, higher review effort and the higher risk of introducing bugs. Please note that AI review comments on this pull request alone do not satisfy this requirement. Our CI and AI review are safeguards, not development tools. If many issues are flagged, rethink your development approach. Invest more effort in planning and design rather than using review cycles to fix low-quality code.

@coderabbitai

coderabbitai Bot commented May 11, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Migration now triggers when the current installationId differs or the current installation lacks an objectId. On migration, the initializer queries for an existing Installation by the Objective-C installationId (cache-bypassed), reuses and updates it if found, or updates/replaces the current installation otherwise. Tests cover empty, failure, and existing-installation reuse cases.

Changes

Objective-C SDK Installation Migration

Layer / File(s) Summary
Migration Logic Update
Sources/ParseSwift/Parse.swift
Migration condition now triggers when current installationId differs from Objective-C stored value OR when objectId is missing. When migrating, code queries for an existing Installation by Objective-C installationId (cache-bypass), updates its installationId and calls updateAutomaticInfo(), or falls back to updating/replacing the current installation and calling updateAutomaticInfo(); on other errors the initializer returns without changes.
Test Coverage: Empty Result
Tests/ParseSwiftTests/InitializeSDKTests.swift
testMigrateObjcSDK seeds an unrelated Installation, mocks the installation query to return an empty QueryResponse, initializes with migratingFromObjcSDK: true, and verifies migrated Installation.current.installationId and Installation.currentContainer.installationId match the ObjC keychain value while objectId remains unset.
Test Coverage: Preserve on Lookup Failure
Tests/ParseSwiftTests/InitializeSDKTests.swift
New testMigrateObjcSDKPreservesCurrentInstallationOnLookupFailure seeds ObjC keychain and a pre-existing Swift current installation, mocks the lookup to fail, and verifies the pre-existing Swift installation and keychain values are preserved.
Test Coverage: Existing Installation Reuse
Tests/ParseSwiftTests/InitializeSDKTests.swift
New testMigrateObjcSDKReusesExistingInstallation seeds the ObjC keychain installationId, mocks the installation endpoint to return an existing Installation with objectId, channels, and deviceToken, initializes migration, and verifies the migrated Installation and keychain-stored currentInstallation preserve those fields.
Test Coverage: Mock Cleanup
Tests/ParseSwiftTests/InitializeSDKTests.swift
testMigrateObjcSDKNoTest now mocks the installation query to return an empty QueryResponse and defers removal of mock URL requests.

Sequence Diagram

sequenceDiagram
  participant ParseInit as ParseSwift.initialize()
  participant InstallationCurrent as Installation.current
  participant Network as Installation.queryByInstallationId()
  participant InstallationState as InstallationState

  ParseInit->>InstallationCurrent: read installationId and objectId
  ParseInit->>ParseInit: compute shouldMigrateInstallation
  alt migration needed
    ParseInit->>Network: query by ObjC installationId no-cache
    Network-->>ParseInit: return fetched / objectNotFound / error
    alt fetched
      ParseInit->>InstallationState: set installationId
      ParseInit->>InstallationState: call updateAutomaticInfo
      ParseInit->>InstallationCurrent: replace with updatedInstallation
    else objectNotFound
      ParseInit->>InstallationCurrent: replace or keep current and set installationId
      ParseInit->>InstallationCurrent: call updateAutomaticInfo
    else error
      ParseInit-->>ParseInit: return early
    end
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 6 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (6 passed)
Check name Status Explanation
Title check ✅ Passed The title follows the required format with 'fix:' prefix and clearly describes the main change: reusing the Objective-C SDK installation during migration.
Description check ✅ Passed The description is comprehensive and follows the template structure, including all required sections: checklist, issue description with link, approach, and testing details.
Linked Issues check ✅ Passed The PR successfully implements all objectives from issue #426: it detects and reuses existing _Installation objects via installationId lookup [#426], preserves the existing objectId [#426], maintains safe fallback behavior [#426], and adds regression tests for both paths [#426].
Out of Scope Changes check ✅ Passed All code changes are directly related to the migration logic in Parse.swift and migration test coverage in InitializeSDKTests.swift, with no unrelated modifications.
Security Check ✅ Passed Security check passed. Uses parameterized queries, proper error handling, and trusted Keychain sources. All NSKeyedUnarchiver usage is pre-existing, not new to this PR.
Engage In Review Feedback ✅ Passed User engaged with feedback and implemented changes: do/catch handling, objectNotFound-specific fallback, fixed fallback logic, 2 new tests, proper cleanup with defer.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 OpenGrep (1.20.0)

OpenGrep fatal error (exit code 2): [00.10][ERROR]: Error: exception Unix_error: No such file or directory stat Tests/ParseSwiftTests/InitializeSDKTests.swift
Raised by primitive operation at UTmp.replace_named_pipe_by_regular_file_if_needed in file "libs/commons/UTmp.ml", line 145, characters 8-27
Called from Scan_CLI.replace_target_roots_by_regular_files_where_needed.(fun) in file "src/osemgrep/cli_scan/Scan_CLI.ml", lines 1086-1087, characters 19-65
Called from List_.fast_map in file "libs/commons/List_.ml", line 81, characters

🔧 SwiftLint (0.63.2)
Sources/ParseSwift/Parse.swift

Error: No lintable files found at paths: 'Sources/ParseSwift/Parse.swift'

Tests/ParseSwiftTests/InitializeSDKTests.swift

Error: No lintable files found at paths: 'Tests/ParseSwiftTests/InitializeSDKTests.swift'

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 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 `@Sources/ParseSwift/Parse.swift`:
- Around line 167-181: The fallback path currently reuses
BaseParseInstallation.current (updatedInstallation) and only updates
installationId, which preserves a saved objectId and can accidentally mutate a
server row; change the else branch handling so that if updatedInstallation is a
persisted installation (e.g., updatedInstallation?.objectId != nil or otherwise
indicates saved state) you replace it with a fresh unsaved BaseParseInstallation
instance (or clear its saved identity fields) before assigning installationId
and calling updateAutomaticInfo as needed; then continue to set
BaseParseInstallation.currentContainer.installationId/currentInstallation and
call BaseParseInstallation.saveCurrentContainerToKeychain() so the code no
longer preserves an unrelated objectId when the lookup misses.

In `@Tests/ParseSwiftTests/InitializeSDKTests.swift`:
- Around line 586-607: Wrap the MockURLProtocol cleanup in a defer immediately
after calling MockURLProtocol.mockRequests so removeAll() always runs even on
early returns; specifically, after the MockURLProtocol.mockRequests { ... }
invocation add defer { MockURLProtocol.removeAll() } to ensure the mock is
unregistered for the test that initializes ParseSwift (the block that calls
ParseSwift.initialize and accesses Installation.current and
Installation.currentContainer) and apply the same pattern to the other similar
test blocks mentioned.
🪄 Autofix (Beta)

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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: e34da14c-c07f-432e-a1ee-951d68a0bacc

📥 Commits

Reviewing files that changed from the base of the PR and between 645180e and 497830c.

📒 Files selected for processing (2)
  • Sources/ParseSwift/Parse.swift
  • Tests/ParseSwiftTests/InitializeSDKTests.swift

Comment thread Sources/ParseSwift/Parse.swift
Comment thread Tests/ParseSwiftTests/InitializeSDKTests.swift Outdated
@Branchrise

Copy link
Copy Markdown
Author

Ready for review.

I addressed the CodeRabbit feedback in 6c7f78a:

  • The fallback path no longer preserves an unrelated saved objectId when the lookup by Objective-C installationId misses.
  • The tests now use defer { MockURLProtocol.removeAll() } for mock cleanup.

Local validation:

  • git diff --check passes.
  • I attempted swift test --filter InitializeSDKTests with Swift 6.3.1 on Windows, but the package fails before these tests due to an existing Swift 6 parser error in Sources/ParseSwift/Coding/ParseEncoder.swift, outside this PR's changed files.

@Branchrise

Copy link
Copy Markdown
Author

@coderabbitai review

The two actionable comments are now marked addressed in commit 6c7f78a. Please re-review the latest head commit so the stale requested-changes state can be refreshed.

@coderabbitai

coderabbitai Bot commented May 11, 2026

Copy link
Copy Markdown

@Branchrise: Thanks for the update! I'll kick off a fresh review of the latest head commit now to reflect the changes made in 6c7f78a.

✅ Actions performed

Full review triggered.

@Branchrise

Copy link
Copy Markdown
Author

@coderabbitai review

The rate-limit window has elapsed. Please re-review the latest head commit 6c7f78a; the two inline findings are already marked addressed on the review comments, but the PR review decision still shows stale requested changes.

@coderabbitai

coderabbitai Bot commented May 11, 2026

Copy link
Copy Markdown

@Branchrise: Understood! Triggering a fresh full review of the latest head commit 6c7f78a now. The stale requested-changes state should be refreshed once the review completes.

✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 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 `@Sources/ParseSwift/Parse.swift`:
- Around line 169-186: Replace the use of try? on
BaseParseInstallation.query(...).first(...) with an explicit do-try-catch so you
only treat a nil/empty query result as a lookup miss; if the query returns nil,
create a new BaseParseInstallation and set installationId/updateAutomaticInfo,
but if the query throws (network/auth/decoding errors) catch and preserve the
existing updatedInstallation (do not replace or clear it) and propagate or
rethrow the error instead of falling through to the "not found" branch; update
the logic around BaseParseInstallation.query, foundInstallation,
updatedInstallation, and installationId accordingly.
🪄 Autofix (Beta)

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: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b6ff6d11-2652-4aeb-a0c4-b6b92e1c9060

📥 Commits

Reviewing files that changed from the base of the PR and between 645180e and 6c7f78a.

📒 Files selected for processing (2)
  • Sources/ParseSwift/Parse.swift
  • Tests/ParseSwiftTests/InitializeSDKTests.swift

Comment thread Sources/ParseSwift/Parse.swift Outdated
@Branchrise

Copy link
Copy Markdown
Author

Addressed the latest CodeRabbit feedback in 55c133c1.

  • Replaced the Objective-C installation lookup try? with explicit do/catch handling.
  • Only ParseError.Code.objectNotFound is treated as a lookup miss and allowed to fall back to a fresh installation.
  • Other lookup failures leave the current installation untouched because initialize is non-throwing.
  • Added a regression test for preserving the current installation when the lookup fails.

Validation:

  • git diff --check passes.
  • swift test --filter InitializeSDKTests is still blocked locally by the existing Swift 6 parser error in Sources/ParseSwift/Coding/ParseEncoder.swift:839, outside this PR's changed files.

@Branchrise

Copy link
Copy Markdown
Author

@coderabbitai review

The rate-limit window has elapsed. Please re-review the latest head commit 55c133c1, which addresses the previous lookup-failure feedback by distinguishing objectNotFound from other query errors and preserving the current installation on lookup failures.

@coderabbitai

coderabbitai Bot commented May 11, 2026

Copy link
Copy Markdown

@Branchrise: Understood! Triggering a fresh full review of the latest head commit 55c133c1 now. The changes — distinguishing objectNotFound from other query errors and preserving the current installation on other lookup failures — will be evaluated in the updated review.

✅ Actions performed

Full review triggered.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
Tests/ParseSwiftTests/InitializeSDKTests.swift (1)

679-682: ⚡ Quick win

Assert the cache bypass in the reuse-path request.

This fix depends on querying _Installation with .reloadIgnoringLocalCacheData, but the mock currently only checks method and URL. Adding a cache-policy assertion here would keep that part of the contract from silently regressing.

Suggested test assertion
         MockURLProtocol.mockRequests { request in
             XCTAssertEqual(request.httpMethod, "GET")
+            XCTAssertEqual(request.cachePolicy, .reloadIgnoringLocalCacheData)
             XCTAssertTrue(request.url?.absoluteString.contains("_Installation") == true)
             XCTAssertTrue(request.url?.absoluteString.contains("installationId") == true)
             do {
🤖 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/ParseSwiftTests/InitializeSDKTests.swift` around lines 679 - 682, The
test MockURLProtocol.mockRequests closure currently asserts only httpMethod and
URL but misses verifying the cache policy used for the `_Installation` reload;
update the closure used in InitializeSDKTests (MockURLProtocol.mockRequests) to
assert that the incoming URLRequest.cachePolicy equals
.reloadIgnoringLocalCacheData so the reuse-path query to `_Installation` can't
regress silently—locate the closure where XCTAssertEqual(request.httpMethod,
"GET") and XCTAssertTrue(request.url?... contains("_Installation")) are checked
and add an assertion checking request.cachePolicy (or
request.cachePolicy.rawValue if needed) for .reloadIgnoringLocalCacheData.
🤖 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.

Nitpick comments:
In `@Tests/ParseSwiftTests/InitializeSDKTests.swift`:
- Around line 679-682: The test MockURLProtocol.mockRequests closure currently
asserts only httpMethod and URL but misses verifying the cache policy used for
the `_Installation` reload; update the closure used in InitializeSDKTests
(MockURLProtocol.mockRequests) to assert that the incoming
URLRequest.cachePolicy equals .reloadIgnoringLocalCacheData so the reuse-path
query to `_Installation` can't regress silently—locate the closure where
XCTAssertEqual(request.httpMethod, "GET") and XCTAssertTrue(request.url?...
contains("_Installation")) are checked and add an assertion checking
request.cachePolicy (or request.cachePolicy.rawValue if needed) for
.reloadIgnoringLocalCacheData.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 511a7cd2-edb7-479c-976e-339f4a222ba0

📥 Commits

Reviewing files that changed from the base of the PR and between 645180e and 55c133c.

📒 Files selected for processing (2)
  • Sources/ParseSwift/Parse.swift
  • Tests/ParseSwiftTests/InitializeSDKTests.swift

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auto-reuse existing installation object when migrating from ObjC SDK

1 participant