File could not be edited because is not up to date

I want to edit file AAA on PostHook action when merge to master branch (the file always exists and the path is always the same), use Content Service for it.
There is ‘Merge commit–no-ff’ as merge strategy.

Addon works like:

  1. there is one commit on branch master - for example masterInitialCommit

  2. there is one commit on develop branch - for example developCommit

  3. I merge develop branch to master

  4. there are three commits on branch master:
    a) masterInitialCommit
    b) developCommit
    c) mergeCommit

  5. post hook modifies AAA file in postUpdate method by using:

                         `EditFileRequest request = new EditFileRequest.Builder(MASTER_BRANCH, PATH_TO_AAA_FILE, REPOSITORY)
                                 .content(new InputSupplier<InputStream>() {
                                     @Nonnull
                                     @Override
                                     public InputStream open() throws IOException {
                                         return new ByteArrayInputStream(newFileContent.getBytes(StandardCharsets.UTF_8));
                                     }
                                 })
                                 .message("commitAfterEditAAAFile")
                                 .sourceCommitId(pullRequestMergeHookRequest.getToRef().getLatestCommit())
                                 .build();
                         this.contentService.editFile(request);`
    

the result is:
a) if the commit developCommit doesn’t update AAA file - everything works fine and there is one more commit on branch master - commitAfterEditAAAFile
b) if the commit developCommit updates AAA file - there is an error, from logs:

com.atlassian.bitbucket.content.FileOutOfDateException: 'AAA' could not be edited because it has been changed on the 'SimpleBranch{id=refs/heads/master, displayId=master, latestCommit=mergeCommit, default=true}' branch.

After point 4) the commit on branch master looks like (hierarchy is by the newest one):
-mergeCommit
-developCommit
-masterInitialCommit

so the error says that AAA file was modified by the latest, mergeCommit - and that’s true.

the problem is because pullRequestMergeHookRequest.getToRef().getLatestCommit() (from point 5)) doesn’t return mergeCommit, it returns masterInitialCommit.
I’m not sure why does it happen, tried to do something like sleep(10) on the beginning of postUpdate method and the result is that the developCommit and mergeCommit exists on master branch (I’m able to see that on Bitbucket UI), then the code from point 5) starts but pullRequestMergeHookRequest.getToRef().getLatestCommit() always returns masterInitialCommit so its not up to date and there is an error.

Is there any way to solve this issue?