lowlevel-toolkit 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 05352e9b9bcf1c5e9edd57e688fc408ce72897baa33aaeb193a951be63729509
4
+ data.tar.gz: 379bd52a3d6a5d4f4fe85a907db67b4bcc32dffe758594031caf28b6eb3befe3
5
+ SHA512:
6
+ metadata.gz: 1126decf4abb9208ac5da0c32aad2be86dbd8cbf017f7074087f7066dbe9e22330ccd0b7400e7add3a40ce5f9c896b640e55d2a08a53da2cf58ea3d5ada62a73
7
+ data.tar.gz: 90bf7dbbe6e8d22a0c608c1a371b0861add4d57e8ecd7804706c6c7ad340fb9580966f94f88ac300223adbbb488065c047ca50222e31b3c9e30f99179564569a
@@ -0,0 +1,134 @@
1
+
2
+ = Contributor Covenant Code of Conduct
3
+
4
+ == Our Pledge
5
+
6
+ We as members, contributors, and leaders pledge to make participation in our
7
+ community a harassment-free experience for everyone, regardless of age, body
8
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
9
+ identity and expression, level of experience, education, socio-economic status,
10
+ nationality, personal appearance, race, caste, color, religion, or sexual
11
+ identity and orientation.
12
+
13
+ We pledge to act and interact in ways that contribute to an open, welcoming,
14
+ diverse, inclusive, and healthy community.
15
+
16
+ == Our Standards
17
+
18
+ Examples of behavior that contributes to a positive environment for our
19
+ community include:
20
+
21
+ * Demonstrating empathy and kindness toward other people
22
+ * Being respectful of differing opinions, viewpoints, and experiences
23
+ * Giving and gracefully accepting constructive feedback
24
+ * Accepting responsibility and apologizing to those affected by our mistakes,
25
+ and learning from the experience
26
+ * Focusing on what is best not just for us as individuals, but for the overall
27
+ community
28
+
29
+ Examples of unacceptable behavior include:
30
+
31
+ * The use of sexualized language or imagery, and sexual attention or advances of
32
+ any kind
33
+ * Trolling, insulting or derogatory comments, and personal or political attacks
34
+ * Public or private harassment
35
+ * Publishing others' private information, such as a physical or email address,
36
+ without their explicit permission
37
+ * Other conduct which could reasonably be considered inappropriate in a
38
+ professional setting
39
+
40
+ == Enforcement Responsibilities
41
+
42
+ Community leaders are responsible for clarifying and enforcing our standards of
43
+ acceptable behavior and will take appropriate and fair corrective action in
44
+ response to any behavior that they deem inappropriate, threatening, offensive,
45
+ or harmful.
46
+
47
+ Community leaders have the right and responsibility to remove, edit, or reject
48
+ comments, commits, code, wiki edits, issues, and other contributions that are
49
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
50
+ decisions when appropriate.
51
+
52
+ == Scope
53
+
54
+ This Code of Conduct applies within all community spaces, and also applies when
55
+ an individual is officially representing the community in public spaces.
56
+ Examples of representing our community include using an official e-mail address,
57
+ posting via an official social media account, or acting as an appointed
58
+ representative at an online or offline event.
59
+
60
+ == Enforcement
61
+
62
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
63
+ reported to the community leaders responsible for enforcement at
64
+ ivo@ivoanjo.me.
65
+ All complaints will be reviewed and investigated promptly and fairly.
66
+
67
+ All community leaders are obligated to respect the privacy and security of the
68
+ reporter of any incident.
69
+
70
+ == Enforcement Guidelines
71
+
72
+ Community leaders will follow these Community Impact Guidelines in determining
73
+ the consequences for any action they deem in violation of this Code of Conduct:
74
+
75
+ === 1. Correction
76
+
77
+ **Community Impact**: Use of inappropriate language or other behavior deemed
78
+ unprofessional or unwelcome in the community.
79
+
80
+ **Consequence**: A private, written warning from community leaders, providing
81
+ clarity around the nature of the violation and an explanation of why the
82
+ behavior was inappropriate. A public apology may be requested.
83
+
84
+ === 2. Warning
85
+
86
+ **Community Impact**: A violation through a single incident or series of
87
+ actions.
88
+
89
+ **Consequence**: A warning with consequences for continued behavior. No
90
+ interaction with the people involved, including unsolicited interaction with
91
+ those enforcing the Code of Conduct, for a specified period of time. This
92
+ includes avoiding interactions in community spaces as well as external channels
93
+ like social media. Violating these terms may lead to a temporary or permanent
94
+ ban.
95
+
96
+ === 3. Temporary Ban
97
+
98
+ **Community Impact**: A serious violation of community standards, including
99
+ sustained inappropriate behavior.
100
+
101
+ **Consequence**: A temporary ban from any sort of interaction or public
102
+ communication with the community for a specified period of time. No public or
103
+ private interaction with the people involved, including unsolicited interaction
104
+ with those enforcing the Code of Conduct, is allowed during this period.
105
+ Violating these terms may lead to a permanent ban.
106
+
107
+ === 4. Permanent Ban
108
+
109
+ **Community Impact**: Demonstrating a pattern of violation of community
110
+ standards, including sustained inappropriate behavior, harassment of an
111
+ individual, or aggression toward or disparagement of classes of individuals.
112
+
113
+ **Consequence**: A permanent ban from any sort of public interaction within the
114
+ community.
115
+
116
+ == Attribution
117
+
118
+ This Code of Conduct is adapted from the Contributor Covenant,
119
+ version 2.1, available at
120
+ https://www.contributor-covenant.org/version/2/1/code_of_conduct.html.
121
+
122
+ Community Impact Guidelines were inspired by
123
+ Mozilla's code of conduct enforcement ladder.
124
+
125
+ For answers to common questions about this code of conduct, see the FAQ at
126
+ https://www.contributor-covenant.org/faq. Translations are available at
127
+ https://www.contributor-covenant.org/translations.
128
+
129
+
130
+
131
+
132
+
133
+
134
+
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ivo Anjo
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.adoc ADDED
@@ -0,0 +1,86 @@
1
+ = `lowlevel-toolkit`
2
+ :toc:
3
+ :toc-placement: macro
4
+ :toclevels: 4
5
+ :toc-title:
6
+
7
+ A Ruby gem that provides access to low-level observability APIs for Ruby applications, allowing you to track and analyze various aspects of your Ruby program's behavior.
8
+
9
+ More than the individual APIs provided, the objective of this gem is to be a repository of examples on **how to use these APIs for doing analysis**. It's expected to be a starting point when building tools.
10
+
11
+ == Quickest start
12
+
13
+ Here's a simple example of tracking GVL (Global VM Lock) usage in your application:
14
+
15
+ [source,ruby]
16
+ ----
17
+ require 'lowlevel-toolkit'
18
+
19
+ def counter_loop(counter = 0) = (counter += 1 while counter < 150_000_000)
20
+
21
+ pp(LowlevelToolkit.track_wants_gvl do
22
+ t1 = Thread.new { counter_loop }.tap { |it| it.name = 't1' }
23
+ t2 = Thread.new { counter_loop }.tap { |it| it.name = 't2' }
24
+
25
+ t1.join; t2.join
26
+ end.map { |thread, wants_gvl_ns| [thread, wants_gvl_ns / 1_000_000_000.0] })
27
+ ----
28
+
29
+ == Installation
30
+
31
+ Install the gem and add to the application's `Gemfile` or `gems.rb` file by executing:
32
+
33
+ [source,bash]
34
+ ----
35
+ $ bundle add lowlevel-toolkit
36
+ ----
37
+
38
+ If bundler is not being used to manage dependencies, install the gem by executing:
39
+
40
+ [source,bash]
41
+ ----
42
+ $ gem install lowlevel-toolkit
43
+ ----
44
+
45
+ == Usage
46
+
47
+ Use `require "lowlevel-toolkit"` to load the gem.
48
+
49
+ The gem provides several low-level observability features:
50
+
51
+ * `track_wants_gvl`: Track when threads want to acquire the Global VM Lock
52
+ * `track_objects_created`: Monitor object creation in your application
53
+ * `last_allocation_at`: Get information about the last object allocation
54
+ * `on_gc_finish`: Set up callbacks for when garbage collection finishes
55
+ * `who_called_me`: Track the call stack of method invocations
56
+ * `release_gvl_profiler`: Profile GVL release patterns
57
+
58
+ == Examples
59
+
60
+ The gem comes with several examples in the `examples/` directory:
61
+
62
+ * `track_wants_gvl.rb`: Shows how to track GVL usage across threads
63
+ * `track_objects_created.rb`: Demonstrates object creation tracking
64
+ * `last_allocation_at.rb`: Shows how to get information about the last allocation
65
+ * `on_gc_finish.rb`: Example of setting up GC finish callbacks
66
+ * `who_called_me.rb`: Demonstrates call stack tracking
67
+ * `print_gc_timing.rb`: Shows GC timing information
68
+ * `release_gvl_profiler.rb`: Example of GVL release profiling
69
+
70
+ == Requirements
71
+
72
+ This gem requires Ruby 3.3.0 or above. Patches welcome to extend support for older Rubies :)
73
+
74
+ == Development
75
+
76
+ 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 https://rubygems.org[rubygems.org]. To run specs, run `bundle exec rake spec`.
77
+
78
+ To run all actions (build the extension, check linting, and run specs), run `bundle exec rake`.
79
+
80
+ == Contributing
81
+
82
+ Bug reports and pull requests are welcome on GitHub at https://github.com/ivoanjo/lowlevel-toolkit. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the https://github.com/ivoanjo/lowlevel-toolkit/blob/master/CODE_OF_CONDUCT.adoc[code of conduct].
83
+
84
+ == Code of Conduct
85
+
86
+ Everyone interacting in the lowlevel-toolkit project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the https://github.com/ivoanjo/lowlevel-toolkit/blob/master/CODE_OF_CONDUCT.adoc[code of conduct].
@@ -0,0 +1,43 @@
1
+ # lowlevel-toolkit: Ruby gem for calling observability APIs
2
+ # Copyright (c) 2025 Ivo Anjo <ivo@ivoanjo.me>
3
+ #
4
+ # This file is part of lowlevel-toolkit.
5
+ #
6
+ # MIT License
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ if ["jruby", "truffleruby"].include?(RUBY_ENGINE)
27
+ raise \
28
+ "\n#{"-" * 80}\nSorry! This gem is unsupported on #{RUBY_ENGINE}. Since it relies on a lot of guts of MRI Ruby, " \
29
+ "it's impossible to make a direct port.\n" \
30
+ "Perhaps a #{RUBY_ENGINE} equivalent could be created -- help is welcome! :)\n#{"-" * 80}"
31
+ end
32
+
33
+ require "mkmf"
34
+
35
+ append_cflags("-Werror-implicit-function-declaration")
36
+ append_cflags("-Wunused-parameter")
37
+ append_cflags("-Wold-style-definition")
38
+ append_cflags("-Wall")
39
+ append_cflags("-Wextra")
40
+ append_cflags("-Werror") if ENV["ENABLE_WERROR"] == "true"
41
+
42
+ create_header
43
+ create_makefile "lowlevel_toolkit_native_extension"
@@ -0,0 +1,42 @@
1
+ #include <ruby/ruby.h>
2
+ #include <ruby/debug.h>
3
+
4
+ int rb_objspace_internal_object_p(VALUE obj);
5
+
6
+ #define MAX_DEPTH 1000
7
+ static VALUE stack = Qnil;
8
+
9
+ static void on_newobj_event(VALUE tpval, RB_UNUSED_VAR(void *_)) {
10
+ if (stack == Qnil ||
11
+ rb_objspace_internal_object_p(rb_tracearg_object(rb_tracearg_from_tracepoint(tpval)))) return;
12
+ VALUE buffer[MAX_DEPTH];
13
+ int depth = rb_profile_frames(0, MAX_DEPTH, buffer, NULL);
14
+ rb_ary_clear(stack);
15
+ for (int i = 0; i < depth; i++) rb_ary_push(stack, buffer[i]);
16
+ }
17
+
18
+ static VALUE track_last_allocation_at(RB_UNUSED_VAR(VALUE _)) {
19
+ stack = rb_ary_new_capa(MAX_DEPTH);
20
+ VALUE tp = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_NEWOBJ, on_newobj_event, NULL);
21
+ rb_tracepoint_enable(tp); rb_yield(Qnil); rb_tracepoint_disable(tp);
22
+ return Qnil;
23
+ }
24
+
25
+ static VALUE last_allocation_at(RB_UNUSED_VAR(VALUE _)) {
26
+ VALUE raw_stack = stack;
27
+ stack = Qnil; // Pause recording of stacks while we're doing the copying below
28
+ VALUE result = rb_ary_new();
29
+ for (int i = 0; i < RARRAY_LEN(raw_stack); i++) {
30
+ VALUE entry = rb_ary_entry(raw_stack, i);
31
+ VALUE file = rb_profile_frame_path(entry);
32
+ if (file != Qnil) rb_ary_push(result, rb_ary_new_from_args(2, file, rb_profile_frame_base_label(entry)));
33
+ }
34
+ stack = raw_stack; // Resume recording again
35
+ return result;
36
+ }
37
+
38
+ void init_last_allocation_at(VALUE lowlevel_toolkit_module) {
39
+ rb_global_variable(&stack);
40
+ rb_define_singleton_method(lowlevel_toolkit_module, "track_last_allocation_at", track_last_allocation_at, 0);
41
+ rb_define_singleton_method(lowlevel_toolkit_module, "last_allocation_at", last_allocation_at, 0);
42
+ }
@@ -0,0 +1,47 @@
1
+ // lowlevel-toolkit: Ruby gem for calling observability APIs
2
+ // Copyright (c) 2025 Ivo Anjo <ivo@ivoanjo.me>
3
+ //
4
+ // This file is part of lowlevel-toolkit.
5
+ //
6
+ // MIT License
7
+ //
8
+ // Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ // of this software and associated documentation files (the "Software"), to deal
10
+ // in the Software without restriction, including without limitation the rights
11
+ // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ // copies of the Software, and to permit persons to whom the Software is
13
+ // furnished to do so, subject to the following conditions:
14
+ //
15
+ // The above copyright notice and this permission notice shall be included in all
16
+ // copies or substantial portions of the Software.
17
+ //
18
+ // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ // SOFTWARE.
25
+
26
+ #include <ruby/ruby.h>
27
+ #include <ruby/debug.h>
28
+
29
+ void init_track_objects_created(VALUE lowlevel_toolkit_module);
30
+ void init_print_gc_timing(VALUE lowlevel_toolkit_module);
31
+ void init_on_gc_finish(VALUE lowlevel_toolkit_module);
32
+ void init_who_called_me(VALUE lowlevel_toolkit_module);
33
+ void init_last_allocation_at(VALUE lowlevel_toolkit_module);
34
+ void init_track_wants_gvl(VALUE lowlevel_toolkit_module);
35
+ void init_release_gvl_profiler(VALUE lowlevel_toolkit_module);
36
+
37
+ void Init_lowlevel_toolkit_native_extension(void) {
38
+ VALUE lowlevel_toolkit_module = rb_define_module("LowlevelToolkit");
39
+
40
+ init_track_objects_created(lowlevel_toolkit_module);
41
+ init_print_gc_timing(lowlevel_toolkit_module);
42
+ init_on_gc_finish(lowlevel_toolkit_module);
43
+ init_last_allocation_at(lowlevel_toolkit_module);
44
+ init_who_called_me(lowlevel_toolkit_module);
45
+ init_track_wants_gvl(lowlevel_toolkit_module);
46
+ init_release_gvl_profiler(lowlevel_toolkit_module);
47
+ }
@@ -0,0 +1,22 @@
1
+ #include <ruby/ruby.h>
2
+ #include <ruby/debug.h>
3
+
4
+ static VALUE callback = Qnil;
5
+ static rb_postponed_job_handle_t postponed_id = 0;
6
+
7
+ static void postponed(RB_UNUSED_VAR(void *data)) { rb_funcall(callback, rb_intern("call"), 0); }
8
+ static void on_gc_finish_event(RB_UNUSED_VAR(VALUE _), RB_UNUSED_VAR(void *__)) { rb_postponed_job_trigger(postponed_id); }
9
+
10
+ static VALUE on_gc_finish(RB_UNUSED_VAR(VALUE _), VALUE user_callback) {
11
+ callback = user_callback;
12
+ VALUE tp = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_GC_EXIT, on_gc_finish_event, NULL);
13
+ rb_tracepoint_enable(tp); rb_yield(Qnil); rb_tracepoint_disable(tp);
14
+ return Qnil;
15
+ }
16
+
17
+ void init_on_gc_finish(VALUE lowlevel_toolkit_module) {
18
+ postponed_id = rb_postponed_job_preregister(0, postponed, NULL);
19
+ if (postponed_id == POSTPONED_JOB_HANDLE_INVALID) rb_raise(rb_eRuntimeError, "Failed to register postponed job");
20
+ rb_global_variable(&callback);
21
+ rb_define_singleton_method(lowlevel_toolkit_module, "on_gc_finish", on_gc_finish, 1);
22
+ }
@@ -0,0 +1,29 @@
1
+ #include <ruby/ruby.h>
2
+ #include <ruby/debug.h>
3
+
4
+ static uint64_t get_monotonic_time_ns(void) {
5
+ struct timespec ts;
6
+ clock_gettime(CLOCK_MONOTONIC, &ts);
7
+ return (uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec;
8
+ }
9
+
10
+ static void on_gc_event(VALUE tpval, RB_UNUSED_VAR(void *_)) {
11
+ static uint64_t gc_start_time = 0;
12
+ rb_event_flag_t event = rb_tracearg_event_flag(rb_tracearg_from_tracepoint(tpval));
13
+
14
+ if (event == RUBY_INTERNAL_EVENT_GC_ENTER) {
15
+ gc_start_time = get_monotonic_time_ns();
16
+ } else if (event == RUBY_INTERNAL_EVENT_GC_EXIT) {
17
+ fprintf(stdout, "GC worked for %.2f ms\n", ((get_monotonic_time_ns() - gc_start_time) / 1000000.0));
18
+ }
19
+ }
20
+
21
+ static VALUE print_gc_timing(RB_UNUSED_VAR(VALUE _)) {
22
+ VALUE tp = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_GC_ENTER | RUBY_INTERNAL_EVENT_GC_EXIT, on_gc_event, NULL);
23
+ rb_tracepoint_enable(tp); rb_yield(Qnil); rb_tracepoint_disable(tp);
24
+ return Qnil;
25
+ }
26
+
27
+ void init_print_gc_timing(VALUE lowlevel_toolkit_module) {
28
+ rb_define_singleton_method(lowlevel_toolkit_module, "print_gc_timing", print_gc_timing, 0);
29
+ }
@@ -0,0 +1,108 @@
1
+ #include <ruby/ruby.h>
2
+ #include <ruby/thread.h>
3
+ #include <ruby/debug.h>
4
+ #include <time.h>
5
+
6
+ int ruby_thread_has_gvl_p(void);
7
+
8
+ #define MAX_STACK_DEPTH 1000
9
+ static int release_gvl_at_key;
10
+
11
+ static uint64_t get_monotonic_time_ns(void) {
12
+ struct timespec ts;
13
+ clock_gettime(CLOCK_MONOTONIC, &ts);
14
+ return (uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec;
15
+ }
16
+
17
+ static void on_thread_event(rb_event_flag_t event_id, const rb_internal_thread_event_data_t *event_data, void *data) {
18
+ VALUE thread = event_data->thread;
19
+
20
+ if (event_id == RUBY_INTERNAL_THREAD_EVENT_SUSPENDED && !ruby_thread_has_gvl_p()) {
21
+ rb_internal_thread_specific_set(thread, release_gvl_at_key, (void *) get_monotonic_time_ns());
22
+ } else if (event_id == RUBY_INTERNAL_THREAD_EVENT_RESUMED) {
23
+ uint64_t release_gvl_at = (uint64_t) rb_internal_thread_specific_get(thread, release_gvl_at_key);
24
+ if (release_gvl_at == 0) return;
25
+ rb_internal_thread_specific_set(thread, release_gvl_at_key, 0);
26
+
27
+ // If we wanted to delay processing the backtrace, we could switch to rb_profile_frames() here
28
+ VALUE frames = rb_make_backtrace();
29
+ VALUE result = (VALUE) data;
30
+
31
+ VALUE stats = rb_hash_aref(result, frames);
32
+ if (stats == Qnil) {
33
+ stats = rb_ary_new_from_args(2, INT2FIX(0), INT2FIX(0));
34
+ rb_hash_aset(result, frames, stats);
35
+ }
36
+
37
+ uint64_t time_spent = get_monotonic_time_ns() - release_gvl_at;
38
+ rb_ary_store(stats, 0, ULL2NUM(NUM2ULL(rb_ary_entry(stats, 0)) + time_spent));
39
+ rb_ary_store(stats, 1, ULL2NUM(NUM2ULL(rb_ary_entry(stats, 1)) + 1));
40
+ }
41
+ }
42
+
43
+ static void write_stacks(VALUE filename_prefix, VALUE result) {
44
+ VALUE time_filename = rb_str_concat(rb_str_dup(filename_prefix), rb_str_new_cstr("_time.folded"));
45
+ VALUE counts_filename = rb_str_concat(rb_str_dup(filename_prefix), rb_str_new_cstr("_counts.folded"));
46
+
47
+ VALUE clean_prefix = rb_hash_aref(rb_const_get(rb_const_get(rb_cObject, rb_intern("RbConfig")), rb_intern("CONFIG")), rb_str_new_cstr("rubylibdir"));
48
+ VALUE prefix_replacement = rb_str_new_cstr("ruby");
49
+
50
+ FILE *time_file = fopen(StringValueCStr(time_filename), "w");
51
+ FILE *counts_file = fopen(StringValueCStr(counts_filename), "w");
52
+
53
+ if (!time_file || !counts_file) {
54
+ if (time_file) fclose(time_file);
55
+ if (counts_file) fclose(counts_file);
56
+ rb_raise(rb_eIOError, "Failed to open output files");
57
+ }
58
+
59
+ VALUE keys = rb_funcall(result, rb_intern("keys"), 0);
60
+ long key_count = RARRAY_LEN(keys);
61
+ for (long i = 0; i < key_count; i++) {
62
+ VALUE frames = rb_ary_entry(keys, i);
63
+ VALUE stats = rb_hash_aref(result, frames);
64
+
65
+ long frame_count = RARRAY_LEN(frames);
66
+ for (long j = frame_count - 1; j >= 0; j--) {
67
+ if (j < frame_count - 1) {
68
+ fprintf(time_file, ";");
69
+ fprintf(counts_file, ";");
70
+ }
71
+
72
+ VALUE frame = rb_ary_entry(frames, j);
73
+ if (clean_prefix != Qnil) rb_funcall(frame, rb_intern("sub!"), 2, clean_prefix, prefix_replacement); // Make files in ruby stdlib a bit neater
74
+ fprintf(time_file, "%s", StringValueCStr(frame));
75
+ fprintf(counts_file, "%s", StringValueCStr(frame));
76
+ }
77
+
78
+ fprintf(time_file, " %llu\n", NUM2ULL(rb_ary_entry(stats, 0)));
79
+ fprintf(counts_file, " %llu\n", NUM2ULL(rb_ary_entry(stats, 1)));
80
+ }
81
+
82
+ fclose(time_file);
83
+ fclose(counts_file);
84
+ }
85
+
86
+ static VALUE release_gvl_profiler(int argc, VALUE *argv, RB_UNUSED_VAR(VALUE _)) {
87
+ VALUE options;
88
+ rb_scan_args(argc, argv, "0:", &options);
89
+ if (options == Qnil) options = rb_hash_new();
90
+ VALUE filename_prefix = rb_hash_fetch(options, ID2SYM(rb_intern("filename_prefix")));
91
+
92
+ VALUE result = rb_hash_new();
93
+ rb_internal_thread_event_hook_t *hook = rb_internal_thread_add_event_hook(
94
+ on_thread_event,
95
+ RUBY_INTERNAL_THREAD_EVENT_SUSPENDED | RUBY_INTERNAL_THREAD_EVENT_RESUMED,
96
+ (void *) result
97
+ );
98
+ rb_yield(Qnil);
99
+ rb_internal_thread_remove_event_hook(hook);
100
+
101
+ write_stacks(filename_prefix, result);
102
+ return result;
103
+ }
104
+
105
+ void init_release_gvl_profiler(VALUE lowlevel_toolkit_module) {
106
+ release_gvl_at_key = rb_internal_thread_specific_key_create();
107
+ rb_define_singleton_method(lowlevel_toolkit_module, "release_gvl_profiler", release_gvl_profiler, -1);
108
+ }
@@ -0,0 +1,26 @@
1
+ #include <ruby/ruby.h>
2
+ #include <ruby/debug.h>
3
+
4
+ int rb_objspace_internal_object_p(VALUE obj);
5
+
6
+ static void on_newobj_event(VALUE tpval, void *data) {
7
+ VALUE obj = rb_tracearg_object(rb_tracearg_from_tracepoint(tpval));
8
+ if (!rb_objspace_internal_object_p(obj)) rb_ary_push((VALUE) data, obj);
9
+ }
10
+
11
+ static VALUE filter_hidden_objects(VALUE result) {
12
+ for (int i = 0; i < RARRAY_LEN(result); i++)
13
+ if (!RBASIC_CLASS(rb_ary_entry(result, i))) rb_ary_store(result, i, Qnil);
14
+ return result;
15
+ }
16
+
17
+ static VALUE track_objects_created(RB_UNUSED_VAR(VALUE _)) {
18
+ VALUE result = rb_ary_new();
19
+ VALUE tp = rb_tracepoint_new(0, RUBY_INTERNAL_EVENT_NEWOBJ, on_newobj_event, (void *) result);
20
+ rb_tracepoint_enable(tp); rb_yield(Qnil); rb_tracepoint_disable(tp);
21
+ return filter_hidden_objects(result);
22
+ }
23
+
24
+ void init_track_objects_created(VALUE lowlevel_toolkit_module) {
25
+ rb_define_singleton_method(lowlevel_toolkit_module, "track_objects_created", track_objects_created, 0);
26
+ }
@@ -0,0 +1,48 @@
1
+ #include <ruby/ruby.h>
2
+ #include <ruby/debug.h>
3
+ #include <ruby/thread.h>
4
+
5
+ static uint64_t get_monotonic_time_ns(void) {
6
+ struct timespec ts;
7
+ clock_gettime(CLOCK_MONOTONIC, &ts);
8
+ return (uint64_t) ts.tv_sec * 1000000000ULL + (uint64_t) ts.tv_nsec;
9
+ }
10
+
11
+ static int wants_gvl_at_key;
12
+ static int total_wants_key;
13
+
14
+ static void on_thread_event(rb_event_flag_t event_id, const rb_internal_thread_event_data_t *event_data, void *data) {
15
+ VALUE thread = event_data->thread;
16
+ if (event_id == RUBY_INTERNAL_THREAD_EVENT_STARTED) {
17
+ rb_ary_push((VALUE) data, thread);
18
+ } else if (event_id == RUBY_INTERNAL_THREAD_EVENT_READY) {
19
+ rb_internal_thread_specific_set(thread, wants_gvl_at_key, (void *) get_monotonic_time_ns());
20
+ } else if (event_id == RUBY_INTERNAL_THREAD_EVENT_RESUMED) {
21
+ uint64_t wants_gvl_at = (uint64_t) rb_internal_thread_specific_get(thread, wants_gvl_at_key);
22
+ if (wants_gvl_at == 0) return;
23
+ uint64_t total_wants = (uint64_t) rb_internal_thread_specific_get(thread, total_wants_key);
24
+ rb_internal_thread_specific_set(
25
+ thread, total_wants_key, (void *) (total_wants + (get_monotonic_time_ns() - wants_gvl_at)));
26
+ }
27
+ }
28
+
29
+ VALUE track_wants_gvl(RB_UNUSED_VAR(VALUE _)) {
30
+ VALUE seen_threads = rb_ary_new();
31
+ rb_internal_thread_event_hook_t *hook =
32
+ rb_internal_thread_add_event_hook(
33
+ on_thread_event, RUBY_INTERNAL_THREAD_EVENT_STARTED | RUBY_INTERNAL_THREAD_EVENT_READY | RUBY_INTERNAL_THREAD_EVENT_RESUMED, (void *) seen_threads);
34
+ rb_yield(Qnil);
35
+ rb_internal_thread_remove_event_hook(hook);
36
+ VALUE result = rb_hash_new();
37
+ for (int i = 0; i < RARRAY_LEN(seen_threads); i++) {
38
+ VALUE thread = rb_ary_entry(seen_threads, i);
39
+ rb_hash_aset(result, thread, ULL2NUM((uint64_t) rb_internal_thread_specific_get(thread, total_wants_key)));
40
+ }
41
+ return result;
42
+ }
43
+
44
+ void init_track_wants_gvl(VALUE lowlevel_toolkit_module) {
45
+ wants_gvl_at_key = rb_internal_thread_specific_key_create();
46
+ total_wants_key = rb_internal_thread_specific_key_create();
47
+ rb_define_singleton_method(lowlevel_toolkit_module, "track_wants_gvl", track_wants_gvl, 0);
48
+ }
@@ -0,0 +1,17 @@
1
+ #include <ruby/ruby.h>
2
+ #include <ruby/debug.h>
3
+
4
+ static VALUE callback(const rb_debug_inspector_t *dbg_context, void *data) {
5
+ bool return_self = (data != NULL);
6
+ return return_self ?
7
+ // Depth: 0 -> us; 1 -> caller; 2 -> caller of caller
8
+ rb_debug_inspector_frame_self_get(dbg_context, 2) : rb_debug_inspector_frame_binding_get(dbg_context, 2);
9
+ }
10
+
11
+ static VALUE who_called_me(RB_UNUSED_VAR(VALUE _)) { return rb_debug_inspector_open(callback, (void *) !NULL); }
12
+ static VALUE who_called_me_binding(RB_UNUSED_VAR(VALUE _)) { return rb_debug_inspector_open(callback, NULL); }
13
+
14
+ void init_who_called_me(VALUE lowlevel_toolkit_module) {
15
+ rb_define_singleton_method(lowlevel_toolkit_module, "who_called_me", who_called_me, 0);
16
+ rb_define_singleton_method(lowlevel_toolkit_module, "who_called_me_binding", who_called_me_binding, 0);
17
+ }
@@ -0,0 +1,33 @@
1
+ # lowlevel-toolkit: Ruby gem for calling observability APIs
2
+ # Copyright (c) 2025 Ivo Anjo <ivo@ivoanjo.me>
3
+ #
4
+ # This file is part of lowlevel-toolkit.
5
+ #
6
+ # MIT License
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ # frozen_string_literal: true
27
+
28
+ require_relative "lowlevel_toolkit/version"
29
+
30
+ require "lowlevel_toolkit_native_extension"
31
+
32
+ module LowlevelToolkit
33
+ end
@@ -0,0 +1,30 @@
1
+ # lowlevel-toolkit: Ruby gem for calling observability APIs
2
+ # Copyright (c) 2025 Ivo Anjo <ivo@ivoanjo.me>
3
+ #
4
+ # This file is part of lowlevel-toolkit.
5
+ #
6
+ # MIT License
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ # frozen_string_literal: true
27
+
28
+ module LowlevelToolkit
29
+ VERSION = "0.1.0"
30
+ end
@@ -0,0 +1,51 @@
1
+ # lowlevel-toolkit: Ruby gem for calling observability APIs
2
+ # Copyright (c) 2025 Ivo Anjo <ivo@ivoanjo.me>
3
+ #
4
+ # This file is part of lowlevel-toolkit.
5
+ #
6
+ # MIT License
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ # frozen_string_literal: true
27
+
28
+ require_relative "lib/lowlevel_toolkit/version"
29
+
30
+ Gem::Specification.new do |spec|
31
+ spec.name = "lowlevel-toolkit"
32
+ spec.version = LowlevelToolkit::VERSION
33
+ spec.authors = ["Ivo Anjo"]
34
+ spec.email = ["ivo@ivoanjo.me"]
35
+
36
+ spec.summary = "Ruby gem for calling observability APIs"
37
+ spec.homepage = "https://github.com/ivoanjo/lowlevel-toolkit"
38
+ spec.license = "MIT"
39
+ spec.required_ruby_version = ">= 3.3.0"
40
+
41
+ # Specify which files should be added to the gem when it is released.
42
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
43
+ spec.files = Dir.chdir(__dir__) do
44
+ `git ls-files -z`.split("\x0").reject do |f|
45
+ (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features|examples)/|\.(?:git|travis|circleci)|appveyor)}) ||
46
+ [".editorconfig", ".ruby-version", ".standard.yml", "gems.rb", "Rakefile"].include?(f)
47
+ end
48
+ end
49
+ spec.require_paths = ["lib", "ext"]
50
+ spec.extensions = ["ext/lowlevel_toolkit_native_extension/extconf.rb"]
51
+ end
metadata ADDED
@@ -0,0 +1,56 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: lowlevel-toolkit
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ivo Anjo
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2025-04-08 00:00:00.000000000 Z
11
+ dependencies: []
12
+ email:
13
+ - ivo@ivoanjo.me
14
+ executables: []
15
+ extensions:
16
+ - ext/lowlevel_toolkit_native_extension/extconf.rb
17
+ extra_rdoc_files: []
18
+ files:
19
+ - CODE_OF_CONDUCT.adoc
20
+ - LICENSE
21
+ - README.adoc
22
+ - ext/lowlevel_toolkit_native_extension/extconf.rb
23
+ - ext/lowlevel_toolkit_native_extension/last_allocation_at.c
24
+ - ext/lowlevel_toolkit_native_extension/lowlevel_toolkit.c
25
+ - ext/lowlevel_toolkit_native_extension/on_gc_finish.c
26
+ - ext/lowlevel_toolkit_native_extension/print_gc_timing.c
27
+ - ext/lowlevel_toolkit_native_extension/release_gvl_profiler.c
28
+ - ext/lowlevel_toolkit_native_extension/track_objects_created.c
29
+ - ext/lowlevel_toolkit_native_extension/track_wants_gvl.c
30
+ - ext/lowlevel_toolkit_native_extension/who_called_me.c
31
+ - lib/lowlevel-toolkit.rb
32
+ - lib/lowlevel_toolkit/version.rb
33
+ - lowlevel-toolkit.gemspec
34
+ homepage: https://github.com/ivoanjo/lowlevel-toolkit
35
+ licenses:
36
+ - MIT
37
+ metadata: {}
38
+ rdoc_options: []
39
+ require_paths:
40
+ - lib
41
+ - ext
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: 3.3.0
47
+ required_rubygems_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ requirements: []
53
+ rubygems_version: 3.6.2
54
+ specification_version: 4
55
+ summary: Ruby gem for calling observability APIs
56
+ test_files: []