Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

drop millions of allocations by using a linked list #1188

Merged
merged 1 commit into from Mar 13, 2015

Conversation

@tenderlove
Copy link
Contributor

@tenderlove tenderlove commented Mar 13, 2015

I'm sending a PR because the reduction in allocations is so surprising to me that I'm afraid it's wrong. All tests pass on my machine, and I think it's backwards compatible, but I need review. /cc @evanphx @drbrain

Use a linked list to drop array allocations. The previous
implementation would dup arrays on every call to traverse. This patch
uses a linked list so that any block that is interested in keeping a
reference to trail can just keep the trail node around (the trail node
points at it's parents).

This approach reduces allocations from 11173668, to 2940.

Here is the test I used:

require 'stackprof'
require 'allocation_tracer'
require 'rubygems/test_case'
require 'rubygems/ext'
require 'rubygems/specification'
require 'benchmark'

class TestGemSpecification < Gem::TestCase
  def test_runtime
    make_gems do
      StackProf.run(mode: :wall, out: '/tmp/out.dump') do
        assert_raises(LoadError) { require 'no_such_file_foo' }
      end
    end
  end

  def test_alone
    make_gems do
      tms = Benchmark.measure {
        assert_raises(LoadError) { require 'no_such_file_foo' }
      }
      p tms.total
      assert_operator tms.total, :<=, 10
    end
  end

  def test_memory
    make_gems do
      ObjectSpace::AllocationTracer.setup(%i{path line type})
      r = ObjectSpace::AllocationTracer.trace do
        assert_raises(LoadError) { require 'no_such_file_foo' }
      end

      r.sort_by { |k,v| v.first }.each do |k,v|
        p k => v
      end
      p hash_alloc: ObjectSpace::AllocationTracer.allocated_count_table[:T_HASH]
      p array_alloc: ObjectSpace::AllocationTracer.allocated_count_table[:T_ARRAY]
      p :TOTAL => ObjectSpace::AllocationTracer.allocated_count_table.values.inject(:+)
    end
  end

  def make_gems
    save_loaded_features do
      num_of_pkg = 7
      num_of_version_per_pkg = 3
      packages = (0..num_of_pkg).map do |pkgi|
        (0..num_of_version_per_pkg).map do |pkg_version|
          deps = Hash[(pkgi..num_of_pkg).map { |deppkgi| ["pkg#{deppkgi}", ">= 0"] }]
          new_spec "pkg#{pkgi}", pkg_version.to_s, deps
        end
      end
      base = new_spec "pkg_base", "1", {"pkg0" => ">= 0"}

      Gem::Specification.reset
      install_specs base,*packages.flatten
      base.activate

      yield
    end
  end
end

Before:

{:TOTAL=>11173668}

After:

{:TOTAL=>2940}

@tenderlove
Copy link
Contributor Author

@tenderlove tenderlove commented Mar 13, 2015

I think this will fix #1169 and #1167

@tenderlove
Copy link
Contributor Author

@tenderlove tenderlove commented Mar 13, 2015

Also the runtime test:

master:

[aaron@TC rubygems (master)]$ ruby -I lib:test test.rb -n test_runtime 
Run options: -n test_runtime --seed 52721

# Running tests:

.

Finished tests in 34.727601s, 0.0288 tests/s, 0.0288 assertions/s.

1 tests, 1 assertions, 0 failures, 0 errors, 0 skips

This branch:

[aaron@TC rubygems (omg)]$ ruby -I lib:test test.rb -n test_runtime 
Run options: -n test_runtime --seed 7522

# Running tests:

.

Finished tests in 0.050260s, 19.8965 tests/s, 19.8965 assertions/s.

1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
@kuldeepaggarwal
Copy link

@kuldeepaggarwal kuldeepaggarwal commented Mar 13, 2015

@tenderlove: Awesome.. 👍

@jcutrell
Copy link

@jcutrell jcutrell commented Mar 13, 2015

This is one of the coolest merge requests I've seen for so many reasons.

@AnatoliiD
Copy link

@AnatoliiD AnatoliiD commented Mar 13, 2015

Yeah! Really awesome! 👍 👍 👍

@evanphx
Copy link
Member

@evanphx evanphx commented Mar 13, 2015

I'd believe it. But look at the linked list that resolver uses for exactly the same reasons, maybe we can use it here too.

@tenderlove
Copy link
Contributor Author

@tenderlove tenderlove commented Mar 13, 2015

@evanphx where can I find it? I don't know the resolver code very well.

@tomciopp
Copy link

@tomciopp tomciopp commented Mar 13, 2015

@tenderlove tenderlove force-pushed the tenderlove:omg branch from 3b957bb to b674a65 Mar 13, 2015
@tenderlove
Copy link
Contributor Author

@tenderlove tenderlove commented Mar 13, 2015

@tomciopp thanks!

I've updated the PR to use the built-in linked list class. I think we can implement the current instance method traverse in terms of the class method I've introduced (though ultimately I'd like to deprecate the instance method), but I will do that if this PR is acceptable for merging.

stack = Gem::List.new(dep_spec, trail)
block[dep_spec, stack]
spec_name = dep_spec.name
traverse(dep_spec, stack, &block) unless

This comment has been minimized.

@skunkworker

skunkworker Mar 13, 2015

I may be wrong but shouldn't this be _traverse instead?

This comment has been minimized.

@libo

libo Mar 13, 2015

Adding a?

private_class_method :_traverse
@libo
Copy link

@libo libo commented Mar 13, 2015

👍

1 similar comment
@chus
Copy link

@chus chus commented Mar 13, 2015

👍

@@ -2,6 +2,8 @@ module Gem
List = Struct.new(:value, :tail)

class List
include Enumerable

This comment has been minimized.

@byroot

byroot Mar 13, 2015
Contributor

If you include Enumerable you don't need the explicit find implementation anymore. The to_a implementation could go too if Struct didn't have a default one.

This comment has been minimized.

@tenderlove

tenderlove Mar 13, 2015
Author Contributor

I'd rather do that in a different commit. 😨

This comment has been minimized.

@ms-ati

ms-ati Mar 19, 2015
Contributor

@byroot This isn't quote true. You have to remove Struct (which has its own Enumerable inclusion and meaning), and reverse the to_a. See PR #1200 ;)

@pawitk
Copy link

@pawitk pawitk commented Mar 13, 2015

👍

@tenderlove tenderlove force-pushed the tenderlove:omg branch from b674a65 to 6ba868a Mar 13, 2015
@tenderlove tenderlove closed this Mar 13, 2015
@tenderlove tenderlove reopened this Mar 13, 2015
@libo
Copy link

@libo libo commented Mar 13, 2015

Is the merge button you have to click @tenderlove,

@tenderlove
Copy link
Contributor Author

@tenderlove tenderlove commented Mar 13, 2015

@libo hah, I closed and reopened to get travis to build again.

@libo
Copy link

@libo libo commented Mar 13, 2015

:-) eheh

By this PR was a hell of a #fridayhug thanks @tenderlove !

@canweriotnow
Copy link

@canweriotnow canweriotnow commented Mar 13, 2015

tumblr_inline_mzmuzndcac1qi4qb3

@draffauf
Copy link

@draffauf draffauf commented Mar 13, 2015

Mind blown. Great job.

Use a linked list to drop array allocations.  The previous
implementation would dup arrays on every call to `traverse`.  This patch
uses a linked list so that any block that is interested in keeping a
reference to `trail` can just keep the trail node around (the trail node
points at it's parents).

This approach reduces allocations from 11173668, to 2940.

Here is the test I used:

```ruby
require 'stackprof'
require 'allocation_tracer'
require 'rubygems/test_case'
require 'rubygems/ext'
require 'rubygems/specification'
require 'benchmark'

class TestGemSpecification < Gem::TestCase
  def test_runtime
    make_gems do
      StackProf.run(mode: :wall, out: '/tmp/out.dump') do
        assert_raises(LoadError) { require 'no_such_file_foo' }
      end
    end
  end

  def test_alone
    make_gems do
      tms = Benchmark.measure {
        assert_raises(LoadError) { require 'no_such_file_foo' }
      }
      p tms.total
      assert_operator tms.total, :<=, 10
    end
  end

  def test_memory
    make_gems do
      ObjectSpace::AllocationTracer.setup(%i{path line type})
      r = ObjectSpace::AllocationTracer.trace do
        assert_raises(LoadError) { require 'no_such_file_foo' }
      end

      r.sort_by { |k,v| v.first }.each do |k,v|
        p k => v
      end
      p hash_alloc: ObjectSpace::AllocationTracer.allocated_count_table[:T_HASH]
      p array_alloc: ObjectSpace::AllocationTracer.allocated_count_table[:T_ARRAY]
      p :TOTAL => ObjectSpace::AllocationTracer.allocated_count_table.values.inject(:+)
    end
  end

  def make_gems
    save_loaded_features do
      num_of_pkg = 7
      num_of_version_per_pkg = 3
      packages = (0..num_of_pkg).map do |pkgi|
        (0..num_of_version_per_pkg).map do |pkg_version|
          deps = Hash[(pkgi..num_of_pkg).map { |deppkgi| ["pkg#{deppkgi}", ">= 0"] }]
          new_spec "pkg#{pkgi}", pkg_version.to_s, deps
        end
      end
      base = new_spec "pkg_base", "1", {"pkg0" => ">= 0"}

      Gem::Specification.reset
      install_specs base,*packages.flatten
      base.activate

      yield
    end
  end
end
```

Before:

{:TOTAL=>11173668}

After:

{:TOTAL=>2940}
@tenderlove tenderlove force-pushed the tenderlove:omg branch from 6ba868a to b19051c Mar 13, 2015
@sstelfox
Copy link

@sstelfox sstelfox commented Mar 13, 2015

Wow awesome. Nice find!

@renatomoya
Copy link

@renatomoya renatomoya commented Mar 13, 2015

Way to go @tenderlove

@vcavallo
Copy link

@vcavallo vcavallo commented Mar 13, 2015

8 O

@amaltson
Copy link

@amaltson amaltson commented Mar 13, 2015

Awesome work @tenderlove, can't wait for this to be released 😄

@gbxl
Copy link

@gbxl gbxl commented Mar 13, 2015

Dude that's awesome! Good job.

@zeeraw
Copy link

@zeeraw zeeraw commented Mar 13, 2015

@tenderlove No matter what people on the internet say, what you're doing is fantastic. Please don't get discouraged. Thank you for spotting and optimising this! #FridayHug

stack = Gem::List.new(dep_spec, trail)
block[dep_spec, stack]
spec_name = dep_spec.name
_traverse(dep_spec, stack, &block) unless

This comment has been minimized.

@seandmccarthy

seandmccarthy Mar 13, 2015

I may have missed something, but I think this should be traverse rather than _traverse as the former is the only one (I can see) with a 3 element signature.

This comment has been minimized.

@cheald

cheald Mar 13, 2015

I think you have that backwards; traverse takes 1 param + block, _traverse takes 2 + block. And in any case the Gem::List is generated prior to the invocation, so traverse wouldn't be appropriate anyhow.

This comment has been minimized.

@seandmccarthy

seandmccarthy Mar 13, 2015

Yeah sorry, scratch that. I was looking at an earlier version and the call is correct now.

@cheald
Copy link

@cheald cheald commented Mar 13, 2015

👍

tenderlove added a commit that referenced this pull request Mar 13, 2015
drop millions of allocations by using a linked list
@tenderlove tenderlove merged commit 7d314e3 into rubygems:master Mar 13, 2015
1 check passed
1 check passed
continuous-integration/travis-ci/pr The Travis CI build passed
Details
@mfazekas

This comment has been minimized.

Copy link
Contributor

@mfazekas mfazekas commented on b19051c Mar 13, 2015

Hm.. i'm pretty sure some cheating is going on here. I don't see the trick, but you decreased the number of allocations because you fixed the exponential algorithm.

I see it:

stack = Gem::List.new(dep_spec, trail)
spec_name = dep_spec.name
unless stack.any? { |s| s.name == spec_name }

stack contains spec_name so we'll never recurse. You need to check trail.any?

so you need to change

unless stack.any? { |s| s.name == spec_name }

to

unless trail.any? { |s| s.name == spec_name }
@ghost
Copy link

@ghost ghost commented Mar 13, 2015

👍

@tenderlove
Copy link
Contributor Author

@tenderlove tenderlove commented Mar 13, 2015

@mfazekas you are totally right. Think we should revert?

@mfazekas
Copy link
Contributor

@mfazekas mfazekas commented Mar 16, 2015

@tenderlove i think it have to be reverted, and we need to add some test that fails with that implementation.

@tenderlove
Copy link
Contributor Author

@tenderlove tenderlove commented Mar 16, 2015

@mfazekas do you have any idea how to make a test that fails with this implementation? I don't want to revert until we can prove it's wrong (no doubt it is wrong, just need to make a test).

@mfazekas
Copy link
Contributor

@mfazekas mfazekas commented Mar 16, 2015

i'll try to came up with a testcase sometime later today

mfazekas added a commit to mfazekas/rubygems that referenced this pull request Mar 17, 2015
@mfazekas
Copy link
Contributor

@mfazekas mfazekas commented Mar 17, 2015

#1191 shows is a testcase, demonstrating the issue with your optimization. But it also shows that the original one despite all the multiple reverse's and exponential algorithm will prefer earlier and not later versions.

So we use find_in_unresolved_tree in case we cannot find a required file in any of the activated gems. The idea is that we check indirect dependencies of the activated gems and try to select a gem that contains the file, but doesn't cause a conflict. And from all of the possibilities we should prefer latest gem versions.

Current implementation is has many issues as its exponential, might select conflicting gems (#1169) and might not use the latest versions of the possibilities (#1191).

@twelve17
Copy link

@twelve17 twelve17 commented Mar 19, 2015

Some 👏 for @mfazekas too!

@sachinprasad-kiwi
Copy link

@sachinprasad-kiwi sachinprasad-kiwi commented Mar 19, 2015

A valid reason to learn linked lists 👍

@ms-ati
Copy link
Contributor

@ms-ati ms-ati commented Mar 19, 2015

Hi @tenderlove, very cool.

After seeing this commit on Ruby Weekly News, I took a look at this code for the first time. I just submitted a PR to hopefully improve the linked list implementation used here (#1200).

Specifically, in the #to_a code path that is frequently called, Array#unshift was called for every list element. I believe this is quadratic performance, since unshift is linear. Is that right?

@007lva
Copy link

@007lva 007lva commented Apr 18, 2015

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Linked issues

Successfully merging this pull request may close these issues.

None yet