acts_as_list: PG::TRDeadlockDetected

We seem to intermittently get Deadlock errors with acts_as_list and Postgres.

PG::TRDeadlockDetected: ERROR: deadlock detected DETAIL: Process 18092 waits for ShareLock on transaction 53198930; blocked by process 30411. Process 30411 waits for ShareLock on transaction 53198931; blocked by process 18092. HINT: See server log for query details. CONTEXT: while updating tuple (15,28) in relation "payment_methods" : UPDATE "payment_methods" SET "updated_at" = '2016-10-20 00:52:19.754301', "sort_order" = ("payment_methods"."sort_order" - 1) WHERE (user_id = 'user_id' AND deleted_at IS NULL) AND ("payment_methods"."sort_order" > 1) AND ("payment_methods"."sort_order" <= 3 AND "payment_methods".id != 'pm_id')

Is this a known issue? I’m using acts_as_list (0.7.7).

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Reactions: 3
  • Comments: 40 (22 by maintainers)

Most upvoted comments

Thanks again @patleb. That’s a good locking strategy that would apply easily to ranked-model I think. If I’m ever actively developing in that space again I’ll look into it.

Certainly it’s never possible to honour two requests for an identical move or insert because the second will inherently rely on stale data. My push for relative positioning in the new gem (e.g. position: {before: Item.find(33)}) was an alternative to throwing an error and just trying to honour the general intent of the request (e.g. it could potentially placed before another item that wanted to be before 33 just moments ago too, but at least they’d both be before 33. So many ways to skin this cat eh! 😄

Thanks @patleb, that’s great insight. I totally understand that deadlock issue. Unfortunately the solution of ordering on UPDATE only works with MySQL. Postgresl and Sqlite don’t allow an explicit update order. In my gem I work around this (for the uniqueness constraint) by inverting the affected records positions to negative values and then re-inverting them with the adjustment up or down. Not so great, but it works and is predictable. This definitely requires the advisory lock. Ideally the lock would just be around the list management stuff but I end up having to wrap the entire transaction for a reason I can’t remember.

Your list management looks more like ranked-model now in that it’s sparse rather than sequential integers. I’m glad that you found a solution that works 😃

@vi-huynh, if you could do some more digging into this to figure out why, that would be helpful 😃 Keen to get this fixed 😃

@brendon sorry for not getting back to you on this. Sadly I cannot remember what we did back then to “fix” the issue for us. I just checked our error reporting again to be sure. Issue did not pop up for us anymore. We are currently using the latest version.