Skip to content
This repository was archived by the owner on Nov 14, 2026. It is now read-only.

Fix crashes and network auto-retry, derive versionCode from the commit time - #136

Merged
dlukt merged 7 commits into
masterfrom
crash-fixes-and-version-code
Sep 18, 2026
Merged

dlukt merged 7 commits into
masterfrom
crash-fixes-and-version-code

Conversation

@dlukt

@dlukt dlukt commented Sep 18, 2026 •

Copy link
Copy Markdown
Owner

Stacked on #135, merge that first. When target-sdk-36 is deleted after #135 is merged, GitHub retargets this PR to master (automatic branch deletion is off in this repo, so use the "Delete branch" button, or change the base by hand).

Four independent fixes for bugs found while working on #135. The auto-retry and versionCode fixes span several commits, partly from review feedback.

Fix crash on Android 6 when uploading or saving media

SecurityUtils.sanitizeFileName() used String.chars(), which needs API 24. Core library desugaring doesn't backport it (D8 emits a direct platform call, confirmed in the dex), so Android 6 threw NoSuchMethodError when attaching media to a post, changing the avatar or header, or saving media from the photo viewer. It now checks for control characters with a loop. Added unit test cases for that check.

Lint also flags Collection.toArray(IntFunction) in SettingsNotificationsFragment. That one is desugared (j$.util.Collection$-EL.toArray), so it's a false positive and left as is.

Fix dropdown menu crashes when it's dismissed

Two NullPointerExceptions when closing the timeline dropdown:

  • Closing within ~150 ms of leaving a submenu. The 300 ms submenu transition outlived the 150 ms dismiss animation, then touched the already cleared container. Any running transition is now finished before the menu is torn down.
  • Closing while the followed hashtags submenu was still loading. onDismiss(), where submenus cancel their requests, only ran when a submenu was popped, so a failed request later popped a submenu of the closed dropdown. Open submenus now get onDismiss() when the dropdown is dismissed.

Fix retrying failed loads when the network comes back

LoaderFragment is meant to retry a failed load when the device reconnects, but this never worked: registerDefaultNetworkCallback() needs ACCESS_NETWORK_STATE, which was never declared, and the SecurityException was swallowed.

Adding the permission alone would have caused a retry loop. The callback reports the current network as soon as it's registered, and the code treated that as a reconnect; a test measured 1,273 retries in 3 seconds. Now it:

  • ignores the network that was the default when the error happened,
  • only retries while the error is still showing,
  • uses the default-network callback only (Android 7+). Auto-retry never worked on Android 6 either,
  • also retries when the default network gets internet access back (not validated → NET_CAPABILITY_VALIDATED), e.g. Wi-Fi that stayed connected during an upstream outage. The first capabilities reported for a network only set the baseline.

Derive versionCode from the commit time, not the build time

The automatic versionCode (seconds since 2024-01-01) was computed while configuring the build. Gradle's configuration cache reuses an earlier configuration when nothing it tracks changes, so a build could get a versionCode from hours or days before: lower than one already published.

It's now derived from git, in the same unit and from the same epoch: the committer time of the commit being built, raised to at least one more than its parents' versionCode. Git timestamps have one-second resolution and don't have to increase from parent to child (1,634 of this repo's 9,741 commits share their parent's timestamp). So every commit gets a higher code than all commits it's based on (this branch: ~85.69M; 1.4.0 from May is ~75.4M), and rebuilding a commit gives the same code. The git output is a tracked configuration input, so a new commit invalidates the cache. Reading the history takes about 65 ms. VERSION_CODE still overrides it.

This needs the full git history. In a shallow clone the build fails with a message saying to run git fetch --unshallow or set VERSION_CODE, and CI now checks out with fetch-depth: 0.

What changes when releasing:

  • Re-uploading an unchanged commit to Play needs a new commit or -PVERSION_CODE.
  • Uncommitted changes don't change the code, so commit before building a release.
  • Building needs a full (not shallow) git checkout, or VERSION_CODE set.

Risk

  • The dropdown and Android 6 fixes are narrow.
  • Auto-retry is new behavior in practice, since it never ran before. It retries once per default-network change after an error and can't loop.
  • The versionCode change affects how releases are numbered; see the list above.

Verification

  • ./gradlew :mastodon:assembleDebug :mastodon:testDebugUnitTest -x lint: 31/31 unit tests pass. :mastodon:minifyPlayReleaseWithR8 also passes.
  • Lint: the NewApi error for String.chars() and appkit's two MissingPermission errors are gone.
  • New instrumentation tests, ToolbarDropdownMenuControllerTest (2) and LoaderFragmentTest (1): 6/6 together with BackNavigationTest on an Android 17 emulator. Each new test fails on the old code: an NPE crash, a failed assertion, and 1,273 loads instead of 1.
  • Auto-retry, checked by hand on the emulator:
    • error while online → no retry,
    • airplane mode on → no retries,
    • network back → one retry per network change or regained validation (3 in the first seconds: mobile data came up unvalidated, got validated, then Wi-Fi took over),
    • no loop afterwards,
    • same network losing and regaining validation (the registered callback fed the network's real capabilities): no retry while unvalidated, one when validated again.
  • versionCode:
    • same commit → same code, with the configuration cache reused,
    • a child with the same committer timestamp as its parent → parent + 1,
    • a child dated a day earlier than its parent → parent + 1,
    • new commit → cache invalidated and the code goes up,
    • -PVERSION_CODE=123 → 123,
    • not a git checkout → clear error,
    • shallow clone → clear error, and it still builds with -PVERSION_CODE.

To run the new tests: ./gradlew :mastodon:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=de.icod.techidon.test.ToolbarDropdownMenuControllerTest,de.icod.techidon.test.LoaderFragmentTest

🤖 Generated with Claude Code

dlukt and others added 4 commits September 18, 2026 19:50
sanitizeFileName() used String.chars(), which only exists on API 24+.
Core library desugaring doesn't backport it (D8 emits a direct platform
call), so on Android 6 it threw NoSuchMethodError whenever a file name
was sanitized: attaching media to a post, changing the avatar or
header, and saving media from the photo viewer. Check for control
characters with a plain loop instead.

Add test cases for the control character check.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Closing the timeline dropdown could crash the app with a
NullPointerException in two ways:

- Dismissing it within ~150 ms of leaving a submenu, e.g. tapping the
  submenu's back item and then outside the menu. The submenu transition
  (300 ms) outlasted the dismiss animation (150 ms), and its end
  listener then touched the already cleared menu container. Finish any
  running transition before tearing the menu down.
- Closing it while the followed hashtags submenu was still loading.
  onDismiss(), where submenus cancel their requests, only ran when a
  submenu was popped, so a failed request later popped a submenu of the
  closed dropdown. Call onDismiss() for all open submenus when the
  dropdown is dismissed.

Add ToolbarDropdownMenuControllerTest covering both. Share the dropdown
test stubs with BackNavigationTest, which no longer has to wait for the
submenu transition before pressing back again.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
LoaderFragment is meant to retry a failed load once the device
reconnects, but ConnectivityManager.registerDefaultNetworkCallback()
requires ACCESS_NETWORK_STATE, which the app never declared. The
SecurityException was swallowed, so this never worked.

Declaring the permission alone would have made things worse: the
callback reports the current network as soon as it's registered, and
the retry treated that as a reconnect. Any error while online was
retried immediately, in a loop (over 1000 retries in 3 s in a test).
The broadcast receiver this code replaced skipped that initial report.

- Declare ACCESS_NETWORK_STATE in appkit, which uses it.
- Ignore the network that was the default when the error happened and
  only retry once it changes.
- Only retry while the error is still showing, so a late callback can't
  start a second load after a manual retry.
- Drop the pre-Android 7 fallback. It reports every connected network
  rather than the default one, so it would loop the same way. Auto-retry
  never worked there either.

Add LoaderFragmentTest for the retry loop.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
versionCode was the number of seconds since 2024-01-01 at build time,
computed while configuring the build. With the configuration cache,
Gradle reuses an earlier build's configuration as long as nothing it
tracks has changed, so a build could get a versionCode from hours or
days before: lower than one already installed or published.

Use the committer time of HEAD instead, in the same unit and from the
same epoch. Every new commit gets a higher versionCode than anything
built before it, including releases made with the old scheme, and
rebuilding a commit gives the same one. The git output is a
configuration input, so a new commit invalidates the cached
configuration. VERSION_CODE still overrides it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@dlukt
dlukt force-pushed the crash-fixes-and-version-code branch from edc1470 to 6b3f2e6 Compare September 18, 2026 17:50

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: edc1470995

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread mastodon/build.gradle Outdated
// The git output is a configuration input, a new commit invalidates the cache.
int versionCodeFromHeadCommit(){
def git=providers.exec{
commandLine 'git', 'log', '-1', '--no-show-signature', '--format=%ct', 'HEAD'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use a monotonic source for generated version codes

%ct has one-second resolution, and Git does not require a descendant's committer timestamp to increase; for example, two successive commits created with the same timestamp both produce 1767225600 from git log --format='%ct'. If an artifact from the first commit has been published, the second can therefore receive an equal or lower versionCode and be rejected by Play despite being newer. Use a strictly monotonic value or validate and bump the result against the last released code.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in b762e13. Each commit's versionCode is now its committer time (seconds since 2024-01-01), raised to at least one more than its parents' versionCode, so it strictly increases along the history. Checked with a child committed in the same second as its parent and one dated a day earlier: both get the parent's code + 1. This matters here: 1,634 of the repo's 9,741 commits share their parent's timestamp.

Committer timestamps have one-second resolution and don't have to
increase from parent to child. Commits made within the same second or
on a machine with a skewed clock got the same or a lower versionCode
than a commit they're based on; 1634 of the 9741 commits in this
repository share their parent's timestamp, e.g. after rebases. If the
earlier commit had been released, Play would reject the newer build.

Raise each commit's versionCode to at least one more than its parents'
so every commit gets a higher versionCode than all of its ancestors.
Reading the history takes about 65 ms.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@dlukt

dlukt commented Sep 18, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@dlukt
dlukt deleted the branch master September 18, 2026 18:05
@dlukt dlukt closed this Sep 18, 2026
@dlukt dlukt reopened this Sep 18, 2026
@dlukt
dlukt changed the base branch from target-sdk-36 to master September 18, 2026 18:06

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b762e13722

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread mastodon/build.gradle
// a lower versionCode than the last one. The git output is a configuration input, a new commit invalidates the cache.
int versionCodeFromGitHistory(){
def git=providers.exec{
commandLine 'git', 'log', '--reverse', '--topo-order', '--no-show-signature', '--format=%H %ct %P', 'HEAD'

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject shallow history before deriving the version code

In a depth-1 checkout, git log succeeds but reports only HEAD and omits its parents, so this loop falls back to the raw committer timestamp and loses the promised parent+1 monotonicity. This repository's PR workflow uses actions/checkout without fetching full history (.github/workflows/pr-quality-gates.yml:27-29), and similarly configured release checkouts can therefore produce an equal or lower versionCode and have uploads rejected. Fresh evidence beyond the earlier timestamp finding is that the new algorithm silently gives the same unsafe result when the repository is shallow; detect a shallow repository and require full history or an explicit VERSION_CODE.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 67f93cf. The build now checks git rev-parse --is-shallow-repository and fails with "versionCode needs the full git history, but this is a shallow clone. Run 'git fetch --unshallow' or set VERSION_CODE." (A shallow clone shows its oldest commit with no parents, so the missing ancestors can't be detected from git log itself.) CI now checks out with fetch-depth: 0. Verified in a depth-1 clone: it fails with that message and still builds with -PVERSION_CODE.

Comment on lines +48 to +50
public void onAvailable(Network network){
// The current default network is reported right after registering, only retry once it changes
if(network.equals(networkAtError))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Retry when the current network regains connectivity

When a device stays associated with the same Wi-Fi network while its upstream Internet connection disappears and later returns, Android keeps the same Network object and reports the validation change through onCapabilitiesChanged; it does not deliver a new onAvailable for that network. Because this callback implements only onAvailable and explicitly ignores networkAtError, a load that fails during this common outage remains on the error screen after connectivity is restored until the user retries manually. Track the loss and restoration of NET_CAPABILITY_VALIDATED (or otherwise detect restored connectivity) for the existing default network as well as default-network replacements.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Fixed in 5268ba6. The callback now also implements onCapabilitiesChanged(): when the current default network goes from not validated to NET_CAPABILITY_VALIDATED, it retries. The first capabilities reported for a network only set the baseline, so an error while online still doesn't retry (LoaderFragmentTest still passes). Updates that don't change validation, like signal strength, don't retry either. This also covers a new default network that wasn't validated yet when it was reported. Verified by feeding the registered callback the network's real capabilities: update while validated → no retry; validation lost → no retry; validation back → one retry.

dlukt and others added 2 commits September 18, 2026 20:13
A shallow clone shows its oldest commit as if it had no parents, so the
versionCode silently fell back to that commit's timestamp and could be
equal to or lower than the code of a commit it's based on. Fail with a
clear message instead, and fetch the full history in CI.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
When the device stays on the same network while its internet connection
drops and comes back, e.g. Wi-Fi during an upstream outage, Android
reports that through onCapabilitiesChanged() with
NET_CAPABILITY_VALIDATED, not onAvailable(), so such loads stayed on
the error screen. Also retry when the default network goes from
unvalidated to validated. This also covers a new default network that
wasn't validated yet when it was first reported.

The first capabilities reported for a network only set the baseline,
so an error while online still doesn't cause a retry.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@dlukt

dlukt commented Sep 18, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 5268ba6171

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@dlukt
dlukt merged commit e1be97e into master Sep 18, 2026
2 checks passed
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant