Skip to content

Implement race-condition-safe DB upsert and use in filecache - #28698

Merged
PVince81 merged 11 commits into
masterfrom
db-upsert
Nov 22, 2017
Merged

PVince81 merged 11 commits into
masterfrom
db-upsert

Conversation

@tomneedham

@tomneedham tomneedham commented Aug 15, 2017 •

Copy link
Copy Markdown
Contributor

Description

Implements a proper upsert method.

Wrapped in a transaction:

  1. Attempts to update row
  2. If not found inserts
  3. Catch insert exception, go to 1.

Tries 10 times (added this in case something else goes crazy and we get stuck) else throws RunTimeException.

Still WIP and open for discussion / thoughts.

One point is that currently I try update, then try insert. This is the opposite when compared to the current implementation - could leave to performance improvements / degradation, depending on common usages of this?

So, checking the usages:
screen shot 2017-08-15 at 17 54 42

I would say most of these are insert-biased - opinions?

Related Issue

#22563

Motivation and Context

Our current insertOrUpdate method is vulnerable to race conditions.

How Has This Been Tested?

UI / files:scan usage so far. And db:stress -f from owncloud/diagnostics:stress branch

Screenshots (if appropriate):

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist:

  • x ] My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

Comment thread lib/private/DB/Adapter.php Outdated

@felixboehm felixboehm Aug 15, 2017 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

increasing count even if done is true. in last loop, will throw error below, also if success.
after loop, having

  • done = true
  • count === $maxTry

Comment thread lib/private/DB/Adapter.php Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

  • show exact query and values, to allow cleanup. If happening, there is some inconsistent metadata.
  • Use $maxTry instead of "10" in exception text.

Comment thread lib/private/DB/Adapter.php Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hack. Please leave comment for easy understanding such hacks

Comment thread lib/private/DB/Adapter.php Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I just don't understand, please explain why wrapping the logic in transaction.

  • Only one changing (successful) query, why keeping it together with the failing ones?
  • This could still lead to a deadlock in DB cluster, right?
  • has this impact on requirements for wsrep_autocommit configs?
  • What would happen without transaction?

Comment thread lib/private/DB/Adapter.php Outdated

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I would expect this function to insert or not. So if the constraint violation is due to $compare values (race condition, other process inserted s.th.) all is fine (don't throw error), return 0 and handle as if existing already.
If violation is due to primary key, then recheck and retry.

@felixboehm

Copy link
Copy Markdown
Contributor

Are there "integration tests" for testing our "DB Layer" against a real DB?

Does it make sense to have our DB Layer in a separat lib with clear testing coverage?

@tomneedham
tomneedham force-pushed the db-upsert branch 2 times, most recently from adf84eb to c6e3415 Compare August 15, 2017 19:03
@tomneedham

Copy link
Copy Markdown
Contributor Author

Are there "integration tests" for testing our "DB Layer" against a real DB?

Yes - they live in the /tests/ folder and the classes use @group DB annotation on the class to allow access to the real DB. They perform their own setup and cleanup.

@tomneedham

Copy link
Copy Markdown
Contributor Author

Ahhhh, I just found IDBConnection->setValues() which calls insertIfNotExsits and then update.... hmmmm

@tomneedham

Copy link
Copy Markdown
Contributor Author

Currently, testing this with db:stress -f with three executions in parallel on my local single node mariadb I get:

[Doctrine\DBAL\Exception\DriverException]
  An exception occurred while executing 'UPDATE `oc_filecache` SET `size`  = ?, `mtime`  = ?, `mimepart`  = ?, `mimetype`  = ?, `etag`  = ?, `path_hash`  = ?, `path`  = ?, `pare
  nt`  = ?, `name`  = ?, `storage` = ?  WHERE`storage` = ? AND `path_hash` = ?' with params [0, 1502897261, "1", "3", "diag-fci-pid:4829-i:0", "6e3f383daca0a9e884dc1e706eb7a03d"
  , "diagnostics\/fci-1502897261", 2, "fci-1502897261", 1, 1, "6e3f383daca0a9e884dc1e706eb7a03d"]:
  SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction

very occasionally.

@tomneedham

Copy link
Copy Markdown
Contributor Author

Is this because of nested transactions in DBAL? Does the lock actually get removed from the row until the final commit() ?

@tomneedham

Copy link
Copy Markdown
Contributor Author

So added a catch for the deadlock exception and continues the loop of attempts. DeadLockException is in doctrine 2.6+, which has a min php verison of 7.1 😒 How about 10.0.3 requires PHP 7.1?! 🙈

@phil-davis

Copy link
Copy Markdown
Contributor

At least when PHP 5.* is no longer being supported, go straight to 7.1 - I don't see any joy in supporting 7.0

@tomneedham

Copy link
Copy Markdown
Contributor Author

Caught any other exceptions and throw them onwards. Working on an enhanced test suite for this with all the $compare magic handled.

@tomneedham
tomneedham force-pushed the db-upsert branch 2 times, most recently from 21b5b36 to 0c70af8 Compare August 28, 2017 12:26
@tomneedham

Copy link
Copy Markdown
Contributor Author

Rebased to kick Jenkins

@tomneedham
tomneedham force-pushed the db-upsert branch 2 times, most recently from fbe3ee7 to ec0b313 Compare August 28, 2017 14:16
@PVince81

Copy link
Copy Markdown
Contributor

First breaking commit: 120005b

@PVince81

Copy link
Copy Markdown
Contributor

restarted build

@PVince81

PVince81 commented Oct 26, 2017 •

Copy link
Copy Markdown
Contributor

@tomneedham guess who's unhappy:

11:58:38 1) Test\DB\AdapterTest::testUpsertWhenCompareColumnValueIsEmpty
11:58:38 RuntimeException: DB upsert failed after 5 attempts. UpdateQuery: UPDATE `*PREFIX*appconfig` SET `appid` = :appid, `configvalue` = :configvalue, `configkey` = :configkey WHERE (to_char(`appid`) = 'testadapter') AND (to_char(`configkey`) = 'test5-key') AND (to_char(`configvalue`) = '') InsertQuery: INSERT INTO `*PREFIX*appconfig` (`appid`, `configvalue`, `configkey`) VALUES(:appid, :configvalue, :configkey)
11:58:38 
11:58:38 /var/lib/jenkins/workspace/owncloud-core_core_PR-28698-66QUNXELAKHHNS5F7PDSROWPS4ZYRDSOVQUUKPO6FTW4BA4CINTA/lib/private/DB/Adapter.php:215
11:58:38 /var/lib/jenkins/workspace/owncloud-core_core_PR-28698-66QUNXELAKHHNS5F7PDSROWPS4ZYRDSOVQUUKPO6FTW4BA4CINTA/tests/lib/DB/AdapterTest.php:123

OCI!

@PVince81 PVince81 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

👍 from me for @tomneedham's commit.

Would be good to get a second review from @DeepDiver1975 or @butonic as this is slightly dangerous DB stuff

@tomneedham

Copy link
Copy Markdown
Contributor Author

Yup - expected that issue with OCI - and agree with the fix

@tomneedham

Copy link
Copy Markdown
Contributor Author

👍

@codecov

codecov Bot commented Oct 26, 2017 •

Copy link
Copy Markdown

Codecov Report

Merging #28698 into master will increase coverage by 0.05%.
The diff coverage is 80%.

Impacted file tree graph

@@             Coverage Diff              @@
##             master   #28698      +/-   ##
============================================
+ Coverage     60.21%   60.26%   +0.05%     
- Complexity    17182    17202      +20     
============================================
  Files          1030     1030              
  Lines         57271    57328      +57     
============================================
+ Hits          34485    34549      +64     
+ Misses        22786    22779       -7
Impacted Files Coverage Δ Complexity Δ
lib/private/AppFramework/Db/Db.php 3.12% <0%> (-0.11%) 31 <1> (+1)
lib/private/DB/Connection.php 66.41% <100%> (+0.52%) 46 <1> (+1) ⬆️
lib/private/Files/Cache/Cache.php 97.21% <100%> (+1.21%) 100 <0> (-2) ⬇️
lib/private/DB/Adapter.php 60.49% <80.35%> (+46.2%) 25 <16> (+16) ⬆️
lib/private/Server.php 82.22% <0%> (-0.22%) 118% <0%> (ø)
lib/private/Settings/SettingsManager.php 72.72% <0%> (-0.18%) 44% <0%> (ø)
settings/templates/settingsPage.php 0% <0%> (ø) 0% <0%> (ø) ⬇️
lib/private/Files/Storage/Wrapper/Encryption.php 68.51% <0%> (+0.07%) 151% <0%> (+1%) ⬆️
lib/private/User/Session.php 62.61% <0%> (+1%) 118% <0%> (+1%) ⬆️
settings/Controller/SettingsPageController.php 70.68% <0%> (+2.68%) 14% <0%> (+2%) ⬆️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update b08c9cd...c5783e6. Read the comment docs.

@PVince81 PVince81 modified the milestones: development, planned Nov 3, 2017
@PVince81

PVince81 commented Nov 3, 2017

Copy link
Copy Markdown
Contributor

Moving to planned for next release.

As soon as 10.0.4 is out I'd like to merge this to have it in the first 10.0.5 beta1 for proper testing.
@DeepDiver1975 @butonic please make sure to give your feedback until then as this is DB intensive stuff and risky.

@PVince81 PVince81 modified the milestones: planned, development Nov 22, 2017
@PVince81
PVince81 merged commit ff91633 into master Nov 22, 2017
@PVince81
PVince81 deleted the db-upsert branch November 22, 2017 16:04
@butonic

butonic commented Nov 22, 2017

Copy link
Copy Markdown
Contributor

Yeeeeeehaaaawwwww! Now we just need to retest Galera Multi Master under load!

@PVince81

Copy link
Copy Markdown
Contributor

and it's not the end of the story: there are likely more code paths where we want to switch from insertIfNotExists to upsert

@PVince81

Copy link
Copy Markdown
Contributor

Please backport!

@lock

lock Bot commented Aug 1, 2019

Copy link
Copy Markdown

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@lock lock Bot locked as resolved and limited conversation to collaborators Aug 1, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

3 - To Review p1-urgent Critical issue, need to consider hotfix with just that issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants