autotuner 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3224324bc9bd16905431bdb2e97bc121eb6902945e3b8fcdc4d65037d8805670
4
+ data.tar.gz: 064b353800288f8b2342926a01b8bcc1bbfdfa58624b317c1b3deca3e9092629
5
+ SHA512:
6
+ metadata.gz: 6d3ece545d282a2bebe07e35fc4ef280d4f262a0976a0ab92ec852abd2a1e7d0e9cf9ea0ef517372df69d4930e0ef40a00925665765cbc5c92db962df8beba70
7
+ data.tar.gz: 1d30e3154fa03d204b9c89e61ff079046519559f0c5ffa1b50451b915199217a03e0180cd66fcc1b57d17b4f0e57bd1ba7ec6bf465e640542599cf3540793b9a
data/.rubocop.yml ADDED
@@ -0,0 +1,20 @@
1
+ inherit_gem:
2
+ rubocop-shopify: rubocop.yml
3
+
4
+ require: rubocop-minitest
5
+
6
+ AllCops:
7
+ NewCops: enable
8
+ SuggestExtensions: false
9
+ TargetRubyVersion: 2.6
10
+
11
+ Style/StringLiterals:
12
+ Enabled: true
13
+ EnforcedStyle: double_quotes
14
+
15
+ Style/StringLiteralsInInterpolation:
16
+ Enabled: true
17
+ EnforcedStyle: double_quotes
18
+
19
+ Layout/LineLength:
20
+ Max: 120
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in gc_tuner.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "minitest", "~> 5.0"
11
+
12
+ gem "rubocop", "~> 1.21"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Peter Zhu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # GcTuner
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/gc_tuner`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/gc_tuner.
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: [:test, :rubocop]
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ module Configuration
5
+ attr_reader :sample_ratio
6
+ attr_writer :enabled
7
+
8
+ def enabled?
9
+ @enabled
10
+ end
11
+
12
+ def sample_ratio=(ratio)
13
+ raise ArgumentError, "ratio must be between 0 and 1.0" unless (0..1.0).include?(ratio)
14
+
15
+ @sample_ratio = ratio
16
+
17
+ self.enabled = rand < ratio
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ module DataStructure
5
+ class DataPoints
6
+ STABLE_RATIO = 0.5
7
+
8
+ attr_reader :samples, :length, :compression_ratio
9
+
10
+ def initialize(capacity)
11
+ raise "Capacity must be even" if capacity.odd?
12
+
13
+ @samples = Array.new(capacity)
14
+
15
+ @temp_sample = 0
16
+ @temp_sample_count = 0
17
+
18
+ @length = 0
19
+ @compression_ratio = 1
20
+ end
21
+
22
+ def insert(value)
23
+ compress if @length == @samples.length
24
+
25
+ @temp_sample += value
26
+ @temp_sample_count += 1
27
+
28
+ return unless @temp_sample_count == @compression_ratio
29
+
30
+ @samples[@length] = @temp_sample / @temp_sample_count
31
+
32
+ @length += 1
33
+ @temp_sample = 0
34
+ @temp_sample_count = 0
35
+ end
36
+
37
+ def stable_region_slope
38
+ # Find line of best fit for the last 50%
39
+ range = (@length * STABLE_RATIO).to_i...@length
40
+
41
+ slope(range)
42
+ end
43
+
44
+ def plateaued?(delta = 0.1)
45
+ # Not enough data until filled
46
+ return false if @compression_ratio == 1
47
+
48
+ stable_region_slope.abs <= delta
49
+ end
50
+
51
+ def correlation(y)
52
+ raise "Length not equal" unless length == y.length
53
+ raise "Compression ratio not equal" unless compression_ratio == y.compression_ratio
54
+
55
+ # Find the correlation between this and y
56
+ # https://www.mathsisfun.com/data/correlation.html
57
+ sum_x = 0
58
+ sum_y = 0
59
+ sum_x_2 = 0
60
+ sum_y_2 = 0
61
+ sum_x_y = 0
62
+ length.times do |i|
63
+ x_val = @samples[i]
64
+ y_val = y.samples[i]
65
+
66
+ sum_x += x_val
67
+ sum_y += y_val
68
+ sum_x_2 += x_val**2
69
+ sum_y_2 += y_val**2
70
+ sum_x_y += x_val * y_val
71
+ end
72
+
73
+ ((length * sum_x_y) - (sum_x * sum_y)).to_f / \
74
+ (Math.sqrt((length * sum_x_2) - (sum_x**2)) * Math.sqrt((length * sum_y_2) - (sum_y**2)))
75
+ end
76
+
77
+ def to_s
78
+ inspect
79
+ end
80
+
81
+ private
82
+
83
+ def compress
84
+ (@length / 2).times do |i|
85
+ @samples[i] = (@samples[i * 2] + @samples[i * 2 + 1]) / 2.0
86
+ end
87
+
88
+ @length /= 2
89
+ @compression_ratio *= 2
90
+ end
91
+
92
+ def slope(range)
93
+ # Find the slope for the area in range using least squares
94
+ # https://www.mathsisfun.com/data/least-squares-regression.html
95
+ sum_x = 0
96
+ sum_y = 0
97
+ sum_x_2 = 0
98
+ sum_x_y = 0
99
+ range.each do |i|
100
+ sum_x += i
101
+ sum_y += @samples[i]
102
+ sum_x_2 += i**2
103
+ sum_x_y += i * @samples[i]
104
+ end
105
+
106
+ (range.size * sum_x_y - (sum_x * sum_y)).to_f / (range.size * sum_x_2 - (sum_x**2))
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ class GCContext
5
+ attr_reader :stat, :stat_heap
6
+
7
+ def initialize
8
+ @stat = GC.stat
9
+ @stat_heap = GC.stat_heap
10
+ end
11
+
12
+ def update
13
+ GC.stat(@stat)
14
+ GC.stat_heap(nil, @stat_heap)
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ module Heuristic
5
+ class Base
6
+ class << self
7
+ def enabled?
8
+ supported? && !@disabled
9
+ end
10
+
11
+ def disable!
12
+ @disabled = true
13
+ end
14
+
15
+ private
16
+
17
+ def supported?
18
+ raise NotImplementedError
19
+ end
20
+ end
21
+
22
+ def call(request_time, before_gc_context, after_gc_context)
23
+ raise NotImplementedError
24
+ end
25
+
26
+ def tuning_message
27
+ raise NotImplementedError
28
+ end
29
+
30
+ def debug_message
31
+ raise NotImplementedError
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ module Heuristic
5
+ class SizePoolWarmup < Base
6
+ DATA_POINTS_COUNT = 1_000
7
+ SIZE_POOL_CONFIGURATION_DELTA_RATIO = 0.01
8
+ SIZE_POOL_CONFIGURATION_DELTA = 1
9
+
10
+ class << self
11
+ private
12
+
13
+ def supported?
14
+ # Ruby 3.3.0 and later have support RUBY_GC_HEAP_INIT_SIZE_%d_SLOTS
15
+ # RUBY_VERSION >= "3.3.0"
16
+ # TODO: use the check above
17
+ true
18
+ end
19
+ end
20
+
21
+ def initialize
22
+ super
23
+
24
+ @request_time_data = DataStructure::DataPoints.new(DATA_POINTS_COUNT)
25
+
26
+ @size_pool_count = GC::INTERNAL_CONSTANTS[:SIZE_POOL_COUNT]
27
+ @size_pools_data = Array.new(@size_pool_count)
28
+ @size_pools_tuning_configuration = Array.new(@size_pool_count)
29
+ @size_pool_count.times do |i|
30
+ @size_pools_data[i] = DataStructure::DataPoints.new(DATA_POINTS_COUNT)
31
+ @size_pools_tuning_configuration[i] = ENV[env_name_for_size_pool(i)].to_i
32
+ end
33
+
34
+ @plateaued = false
35
+ end
36
+
37
+ def call(request_time, _before_gc_context, after_gc_context)
38
+ # We only want to collect data at boot until the request time plateaus
39
+ return if @plateaued
40
+
41
+ insert_data(request_time, after_gc_context)
42
+
43
+ return unless @request_time_data.plateaued?
44
+
45
+ @plateaued = true
46
+ end
47
+
48
+ def tuning_message
49
+ msg = nil
50
+
51
+ if @plateaued
52
+ size_pool_messages = @size_pool_count.times.map do |i|
53
+ tuning_message_for_size_pool(i)
54
+ end.compact
55
+
56
+ unless size_pool_messages.empty?
57
+ msg = <<~MSG
58
+ Here are the recommended tuning values for size pools and the confidence scores.
59
+ Confidence scores are between 0 and 1.0 and represent the correlation between
60
+ the tuning value and the response time.
61
+
62
+ MSG
63
+
64
+ msg += size_pool_messages.join
65
+ end
66
+ else
67
+ msg = <<~MSG.chomp
68
+ There is not enough data and/or response times have not plateaued.
69
+ MSG
70
+ end
71
+
72
+ msg
73
+ end
74
+
75
+ def debug_message
76
+ msg = <<~MSG
77
+ plateaued: #{@plateaued}
78
+ request_time_data: #{@request_time_data}
79
+ MSG
80
+
81
+ @size_pools_data.each_with_index do |data, i|
82
+ msg += "size_pools_data[#{i}]: #{data}\n"
83
+ end
84
+
85
+ if @plateaued
86
+ msg += @size_pool_count.times.map do |i|
87
+ tuning_message_for_size_pool(i, debug: true)
88
+ end.join
89
+ end
90
+
91
+ msg
92
+ end
93
+
94
+ private
95
+
96
+ def insert_data(request_time, after_gc_context)
97
+ @request_time_data.insert(request_time)
98
+
99
+ @size_pools_data.each_with_index do |data, i|
100
+ data.insert(after_gc_context.stat_heap[i][:heap_eden_pages])
101
+ end
102
+ end
103
+
104
+ def env_name_for_size_pool(size_pool)
105
+ slot_size = GC::INTERNAL_CONSTANTS[:BASE_SLOT_SIZE] * (2**size_pool)
106
+
107
+ "RUBY_GC_HEAP_INIT_SIZE_#{slot_size}_SLOTS"
108
+ end
109
+
110
+ def tuning_message_for_size_pool(size_pool, debug: false)
111
+ configured_value = @size_pools_tuning_configuration[size_pool]
112
+
113
+ data = @size_pools_data[size_pool]
114
+ suggested_value = data.samples[data.length - 1].to_i
115
+
116
+ diff = (configured_value - suggested_value).abs
117
+ if debug ||
118
+ (diff > configured_value * SIZE_POOL_CONFIGURATION_DELTA_RATIO && diff > SIZE_POOL_CONFIGURATION_DELTA)
119
+ confidence = @request_time_data.correlation(data).abs
120
+
121
+ msg = ""
122
+ msg += "#{env_name_for_size_pool(size_pool)}=#{suggested_value} (confidence: #{format("%.2f", confidence)}"
123
+ msg += ", tuned value: #{configured_value}" if configured_value > 0
124
+ msg += ")\n"
125
+
126
+ msg
127
+ end
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ module Heuristics
5
+ HEURISTICS = [
6
+ Heuristic::SizePoolWarmup,
7
+ ].freeze
8
+
9
+ def heuristics
10
+ @heuristics ||= enabled_heuristics.map(&:new)
11
+ end
12
+
13
+ def tuning_messages
14
+ heuristics.map(&:tuning_message)
15
+ end
16
+
17
+ def debug_messages
18
+ heuristics.map(&:debug_message)
19
+ end
20
+
21
+ private
22
+
23
+ def enabled_heuristics
24
+ HEURISTICS.dup.keep_if(&:enabled?)
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ class RackPlugin
5
+ def initialize(app)
6
+ @app = app
7
+ @request_collector = RequestCollector.new
8
+ end
9
+
10
+ def call(env)
11
+ if GCTuner.enabled?
12
+ @request_collector.request do
13
+ @app.call(env)
14
+ end
15
+ else
16
+ @app.call(env)
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ class RequestCollector
5
+ def initialize
6
+ @before_gc_context = GCContext.new
7
+ @after_gc_context = GCContext.new
8
+
9
+ @start_time_ms = 0.0
10
+ end
11
+
12
+ def request
13
+ before_request
14
+
15
+ yield
16
+ ensure
17
+ after_request
18
+ end
19
+
20
+ private
21
+
22
+ def before_request
23
+ @before_gc_context.update
24
+ @start_time_ms = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond)
25
+ end
26
+
27
+ def after_request
28
+ request_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_millisecond) - @start_time_ms
29
+ @after_gc_context.update
30
+
31
+ GCTuner.heuristics.each do |heuristic|
32
+ heuristic.call(request_time, @before_gc_context, @after_gc_context)
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GCTuner
4
+ VERSION = "0.1.0"
5
+ end
data/lib/gc_tuner.rb ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "gc_tuner/data_structure/data_points"
4
+
5
+ require_relative "gc_tuner/heuristic/base"
6
+ require_relative "gc_tuner/heuristic/size_pool_warmup"
7
+
8
+ require_relative "gc_tuner/configuration"
9
+ require_relative "gc_tuner/gc_context"
10
+ require_relative "gc_tuner/heuristics"
11
+ require_relative "gc_tuner/rack_plugin"
12
+ require_relative "gc_tuner/request_collector"
13
+ require_relative "gc_tuner/version"
14
+
15
+ module GCTuner
16
+ extend Configuration
17
+ extend Heuristics
18
+ end
metadata ADDED
@@ -0,0 +1,102 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: autotuner
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Peter Zhu
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-06-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: mocha
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rubocop-minitest
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rubocop-shopify
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description:
56
+ email:
57
+ - peter@peterzhu.ca
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rubocop.yml"
63
+ - Gemfile
64
+ - LICENSE.txt
65
+ - README.md
66
+ - Rakefile
67
+ - lib/gc_tuner.rb
68
+ - lib/gc_tuner/configuration.rb
69
+ - lib/gc_tuner/data_structure/data_points.rb
70
+ - lib/gc_tuner/gc_context.rb
71
+ - lib/gc_tuner/heuristic/base.rb
72
+ - lib/gc_tuner/heuristic/size_pool_warmup.rb
73
+ - lib/gc_tuner/heuristics.rb
74
+ - lib/gc_tuner/rack_plugin.rb
75
+ - lib/gc_tuner/request_collector.rb
76
+ - lib/gc_tuner/version.rb
77
+ homepage: https://github.com/Shopify/gc_tuner
78
+ licenses:
79
+ - MIT
80
+ metadata:
81
+ homepage_uri: https://github.com/Shopify/gc_tuner
82
+ source_code_uri: https://github.com/Shopify/gc_tuner
83
+ post_install_message:
84
+ rdoc_options: []
85
+ require_paths:
86
+ - lib
87
+ required_ruby_version: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: 2.6.0
92
+ required_rubygems_version: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ requirements: []
98
+ rubygems_version: 3.4.10
99
+ signing_key:
100
+ specification_version: 4
101
+ summary: Get suggestions to tune Ruby's garbage collector
102
+ test_files: []