capybara icon indicating copy to clipboard operation
capybara copied to clipboard

StaleElementReferenceError race condition when removing nodes (with text?)

Open joliss opened this issue 14 years ago • 51 comments

Originally reported by [email protected] in https://groups.google.com/d/topic/ruby-capybara/O3Ib6INOP58/discussion

There seems to be a race condition when nodes go away, and we filter on something (like :text).

Jake was nice enough to make a minimal sample app and add a sleep in the right place, so we can reliably reproduce this:

Demo repository for 1.1.2, with README explaining the issue: https://github.com/shepmaster/capybara-race Just run bundle exec rspec.

Updated against master, or rather, 7fa75e5, the last commit before the rspec change: https://github.com/joliss/capybara-race

joliss avatar Oct 07 '12 17:10 joliss

Interestingly I was just working on this issue today. @ramhoj and I discovered this a couple of weeks ago, kind of boggles my mind that no one has noticed it until now. It's damned difficult to write a test case for it though.

jnicklas avatar Oct 07 '12 18:10 jnicklas

I know exactly what is causing the problem, but it's a bit difficult to explain and the solution is the easy part anyway ;)

jnicklas avatar Oct 07 '12 18:10 jnicklas

I'm interested to see the solution. I had a few (bad) ideas:

  1. Load all the data immediately instead of looking it up later, which seems really expensive.
  2. Inform the driver what information you will want later and have it load e.g. the text, which seems to smear the logic all around the place.
  3. Catch the error and retry, but then you have to catch the right error at all the right places.

shepmaster avatar Oct 07 '12 19:10 shepmaster

no one has noticed it until now

In our case, we've noticed the problem for weeks and/or months. Retriggering our automated build usually causes the problem to go away, so we do that and move on. I'm sure lots of people have similar experiences.

shepmaster avatar Oct 07 '12 19:10 shepmaster

We already have all the relevant logic in place. If this is the same issue that I've found, and I think it is, then this should actually be fixed on master. It also shouldn't be hard to fix for 1.1.x at all.

What's happening is that when an Element is initialized, we send in whatever selector was used to find that element. We can then use that selector to reload the Element at a later time, in case it has gone stale. Check out the implementation of first in Capybara 1.1.2:

      def first(*args)
        options = extract_normalized_options(args)
        found_elements = []

        selector = Capybara::Selector.normalize(*args)
        selector.xpaths.each do |path|
          find_in_base(selector, path).each do |node|
            if matches_options(node, options)
              found_elements << node
              return found_elements.last if not Capybara.prefer_visible_elements or node.visible?
            end
          end
        end
        found_elements.first
      end

The first three lines are where the bug occurs. We first extract the options from the arguments, this will actually remove them from the args array. Then we call Capybara::Selector.normalize, sending in all arguments, except we aren't because we just removed all the options. So effectively we are sending in the same selector, but without any options. Now #first itself will still work as intended, because we never actually use the options from the selector here. They only become useful when we try to reload the node. Which is why this appears as a race-condition/random failure, because if #first succeeds on the first try, everything is fine.

jnicklas avatar Oct 07 '12 20:10 jnicklas

I'm trying to understand more, so just let me know when I'm too annoying and I'll stop asking questions. :-)

If the problem is because the selector doesn't have the right options, then why is a StaleElementReferenceError exception thrown? Wouldn't it just be an error where the node is incorrectly found or not found? At which point is the node reloaded? I've only looked at all, but I think the same behavior would occur in first if you added a sleep between find_in_base and matches_options. That would then throw StaleElementReferenceError, which would need to be handled by wait_until, right?

shepmaster avatar Oct 09 '12 12:10 shepmaster

Hmm, that's a good point. The only scenario where this would throw a StaleElementReferenceError would be if the lack of options would cause the reload to fail, which would only occur if the lack of options would cause there to be less results. AFAIK the only option which increases the number of nodes found would be visible: false if Capybara.ignore_hidden_elements is set to true. I don't think that is the case here. I will investigate this further. Let me know if you come up with any further insights.

jnicklas avatar Oct 09 '12 20:10 jnicklas

What about this idea.

from Capybara::Node::Element#reload

reloaded = parent.reload.first(@selector.name, @selector.locator, @selector.options)
@base = reloaded.base if reloaded

What is the expected code flow when the element appears (so @base is originally set), then we reload waiting for the element to disappear? If the element disappears, reloaded would be nil, so it wouldn't replace @base, which still points to the old element. Then we eventually run out of retry time and fail.

shepmaster avatar Oct 19 '12 21:10 shepmaster

I finally had some time to look at this problem, and I think I understand what's happening now. Your description of the error seems spot on to me. I ran RSpec in a loop and the problem only manifested after 20 or so successful attempts, so it seems the race condition is quite rare, and that's to be expected, considering it would only occur if the element is deleted between when it is found and Capybara checks the text content.

When #text is called, it tries to reload the element it is being called on, for a period of time. Unfortunately this doesn't help us in this case, since the Element is gone, and not coming back, so #text tries in vain to reload it. In this case we would have been satisfied with the element being gone, and we could have simply returned a negative match.

We could change the behaviour of #text to return nil if it can't reload the element, but I'm not sure I like the implications of that. What is the content of an element that no longer exists? Is it an empty string, nil? An exception seems like the most sane response to asking for the text of an element that doesn't exist. This would also throw us into a loop of waiting for the answer until we can get a valid element, which we never will.

I'm thinking we should have some way of bypassing synchronization entirely. I don't know exactly how that would work. Maybe have a method on the session which takes a block and call it something like without_synchronizing or something. Then we could wrap the text comparison in this bypass block. If it would fail, it would simply return nil.

The semantics of this are pretty weird, so I'm not really sure how to make this understandable.

jnicklas avatar Oct 26 '12 12:10 jnicklas

I'm surprised that you saw it reproduce so infrequently. The testcase I created has large sleeps that should make it very easy to trigger - I saw it reproduce 100%. In the wild it would certainly be harder to reproduce.

I agree that #text shouldn't be changed to return nil. That would confuse the semantics too much. This statement made me think though:

What is the content of an element that no longer exists?

Existence is a first-class state of an element. Perhaps Capybara::Node::Element (or wherever appropriate) needs to have an #exists? method added. Then we can just check if the element exists. If the element doesn't exist inside #has_selector, then that would be a fast failure. Inside #has_no_selector it could be a fast success, equivalent to the current results.empty test.

shepmaster avatar Oct 26 '12 17:10 shepmaster

Not a bad idea, but that would still leave us open to race conditions, what if it still exists when we call exists? and then ceases to exist just before we call #text.

jnicklas avatar Oct 26 '12 22:10 jnicklas

This is a simplified version of the example app, in a single file, way easier to work with. https://gist.github.com/d5a497aa4a5ff52b2a8b

jnicklas avatar Oct 30 '12 09:10 jnicklas

I couldn't come up with any way of testing this, short of running a loop until it fails, which isn't an awesome test case. So no tests for this, sorry.

jnicklas avatar Oct 30 '12 10:10 jnicklas

Also, still working on fixing this on 1.1_stable, and we'll do a new gem release on that branch.

jnicklas avatar Oct 30 '12 10:10 jnicklas

(forgot to change the git name on the machine I was working in, I authored that commit, not @ramhoj ;))

jnicklas avatar Oct 30 '12 10:10 jnicklas

I get the same behaviour consistently using expect(page).to have_css('.foo', count: 4)

wmadden avatar Dec 01 '12 12:12 wmadden

In fact it occurs while generating the expectation failure message:

Selenium::WebDriver::Error::StaleElementReferenceError: Element not found in the cache - perhaps the page has changed since it was looked up
[remote server] resource://fxdriver/modules/web_element_cache.js:7281:in `unknown'
[remote server] file:///var/folders/r4/3w9pk18923vfxq_l5c2brbfw0000gn/T/webdriver-profile20121201-83055-nhcx5m/extensions/[email protected]/components/command_processor.js:6903:in `unknown'
[remote server] file:///var/folders/r4/3w9pk18923vfxq_l5c2brbfw0000gn/T/webdriver-profile20121201-83055-nhcx5m/extensions/[email protected]/components/command_processor.js:9793:in `unknown'
[remote server] file:///var/folders/r4/3w9pk18923vfxq_l5c2brbfw0000gn/T/webdriver-profile20121201-83055-nhcx5m/extensions/[email protected]/components/command_processor.js:10337:in `unknown'
[remote server] file:///var/folders/r4/3w9pk18923vfxq_l5c2brbfw0000gn/T/webdriver-profile20121201-83055-nhcx5m/extensions/[email protected]/components/command_processor.js:10342:in `unknown'
[remote server] file:///var/folders/r4/3w9pk18923vfxq_l5c2brbfw0000gn/T/webdriver-profile20121201-83055-nhcx5m/extensions/[email protected]/components/command_processor.js:10282:in `unknown'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/response.rb:52:in `assert_ok'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/response.rb:15:in `initialize'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/http/common.rb:59:in `new'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/http/common.rb:59:in `create_response'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/http/default.rb:66:in `request'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/http/common.rb:40:in `call'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/bridge.rb:598:in `raw_execute'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/bridge.rb:576:in `execute'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/remote/bridge.rb:487:in `getElementText'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/selenium-webdriver-2.26.0/lib/selenium/webdriver/common/element.rb:108:in `text'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/selenium/node.rb:4:in `text'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/node/element.rb:48:in `block in text'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/node/base.rb:77:in `synchronize'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/node/element.rb:48:in `text'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/result.rb:47:in `map'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/result.rb:47:in `failure_message'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/node/matchers.rb:86:in `block in assert_selector'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/node/base.rb:77:in `synchronize'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/node/matchers.rb:84:in `assert_selector'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/session.rb:338:in `block (2 levels) in <class:Session>'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/capybara-2.0.1/lib/capybara/rspec/matchers.rb:9:in `matches?'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/rspec-expectations-2.12.0/lib/rspec/expectations/handler.rb:23:in `handle_matcher'
/Users/will/.rvm/gems/ruby-1.9.3-p194@education/gems/rspec-expectations-2.12.0/lib/rspec/expectations/expectation_target.rb:34:in `to'

wmadden avatar Dec 01 '12 12:12 wmadden

I have the same problem using expect(element).to have_text "foo" inside synchronize method. And btw this exception appears regularly (I mean every time)

ffess avatar Feb 05 '13 13:02 ffess

@ffess That's one reason you should be careful of using synchronize. It's a powerful methods, but it's semantics are very subtle. You will probably have to strategically call unsychronized, to fix these race conditions.

jnicklas avatar Feb 05 '13 16:02 jnicklas

Hi jnicklas, I've asked on google groups how to use the synchronize method exactly, but no one answered me (I'm new to capybara and I use it about 2 months at all and lot of investigating didn't help me to learn how to use the method, but I really need it)

I found that while implementing the yield provided with synchronize method it should rescue the StaleElementReferenceError but it's not:(

ffess avatar Feb 05 '13 16:02 ffess