reclaimable 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.
Files changed (85) hide show
  1. checksums.yaml +7 -0
  2. data/.claude/launch.json +11 -0
  3. data/.gitignore +11 -0
  4. data/.gitlab-ci.yml +16 -0
  5. data/AGENTS.md +88 -0
  6. data/CLAUDE.md +1 -0
  7. data/Gemfile +3 -0
  8. data/LICENSE +674 -0
  9. data/README.md +160 -0
  10. data/Rakefile +28 -0
  11. data/ai-skill/reclaimable/SKILL.md +94 -0
  12. data/benchmark/README.md +59 -0
  13. data/benchmark/experiments/lstat_scanner.rb +11 -0
  14. data/benchmark/experiments/ractor_scanner.rb +92 -0
  15. data/benchmark/experiments/verify_bulk_list.rb +34 -0
  16. data/benchmark/lib/fixture.rb +104 -0
  17. data/benchmark/lib/results.rb +62 -0
  18. data/benchmark/reports/00-baseline.md +75 -0
  19. data/benchmark/reports/01-jit.md +70 -0
  20. data/benchmark/reports/02-ractor.md +58 -0
  21. data/benchmark/reports/03-getattrlistbulk.md +84 -0
  22. data/benchmark/reports/04-others.md +52 -0
  23. data/benchmark/reports/05-outside-root.md +56 -0
  24. data/benchmark/reports/06-round2-discussion.md +374 -0
  25. data/benchmark/reports/06-round2.md +194 -0
  26. data/benchmark/reports/README.md +46 -0
  27. data/benchmark/results/baseline.yml +126 -0
  28. data/benchmark/results/bulk-list.yml +126 -0
  29. data/benchmark/results/final-yjit.yml +126 -0
  30. data/benchmark/results/final.yml +126 -0
  31. data/benchmark/results/ractor-exp.yml +38 -0
  32. data/benchmark/results/round2-after.yml +126 -0
  33. data/benchmark/results/round2-before.yml +126 -0
  34. data/benchmark/results/src-baseline.yml +32 -0
  35. data/benchmark/results/src-bulk-list.yml +32 -0
  36. data/benchmark/results/src-pair-none1.yml +38 -0
  37. data/benchmark/results/src-pair-none2.yml +38 -0
  38. data/benchmark/results/src-pair-yjit1.yml +38 -0
  39. data/benchmark/results/src-pair-yjit2.yml +38 -0
  40. data/benchmark/results/src-ractor-exp.yml +32 -0
  41. data/benchmark/results/src-round2-after1.yml +52 -0
  42. data/benchmark/results/src-round2-after2.yml +52 -0
  43. data/benchmark/results/src-round2-before1.yml +52 -0
  44. data/benchmark/results/src-round2-before2.yml +52 -0
  45. data/benchmark/results/yjit.yml +126 -0
  46. data/benchmark/results/zjit.yml +126 -0
  47. data/benchmark/run.rb +149 -0
  48. data/bin/reclaimable +10 -0
  49. data/doc/performance.md +179 -0
  50. data/lib/reclaimable/ai_skill.rb +138 -0
  51. data/lib/reclaimable/bulk_list.rb +91 -0
  52. data/lib/reclaimable/cache_dump.rb +125 -0
  53. data/lib/reclaimable/cli.rb +168 -0
  54. data/lib/reclaimable/cloud_files.rb +33 -0
  55. data/lib/reclaimable/config.rb +100 -0
  56. data/lib/reclaimable/i18n.rb +24 -0
  57. data/lib/reclaimable/locations.rb +89 -0
  58. data/lib/reclaimable/output.rb +154 -0
  59. data/lib/reclaimable/paths.rb +36 -0
  60. data/lib/reclaimable/report.rb +504 -0
  61. data/lib/reclaimable/ruby_abi.rb +69 -0
  62. data/lib/reclaimable/scan_cache.rb +97 -0
  63. data/lib/reclaimable/scanner.rb +440 -0
  64. data/lib/reclaimable/util.rb +34 -0
  65. data/lib/reclaimable.rb +42 -0
  66. data/locale/ja/LC_MESSAGES/reclaimable.mo +0 -0
  67. data/man/reclaimable.1.ronn +302 -0
  68. data/man/reclaimable.en.1 +234 -0
  69. data/man/reclaimable.ja.1 +452 -0
  70. data/po/ja/reclaimable-docs.po +668 -0
  71. data/po/ja/reclaimable.po +510 -0
  72. data/rakelib/benchmark.rake +22 -0
  73. data/rakelib/docs/japanese.rb +132 -0
  74. data/rakelib/docs/man_page.rb +73 -0
  75. data/rakelib/docs/site.rb +187 -0
  76. data/rakelib/docs/sources.rb +94 -0
  77. data/rakelib/docs/translation.rb +157 -0
  78. data/rakelib/docs.rake +62 -0
  79. data/rakelib/gettext.rake +30 -0
  80. data/rakelib/i18n.rake +199 -0
  81. data/reclaimable.gemspec +56 -0
  82. data/site/index.md +142 -0
  83. data/site/layout.html.erb +60 -0
  84. data/site/style.css +82 -0
  85. metadata +231 -0
data/README.md ADDED
@@ -0,0 +1,160 @@
1
+ # reclaimable
2
+
3
+ macOS のストレージの削除候補を洗い出して一覧表示する、Ruby 4.0 向けの読み取り専用ツール。
4
+ 何も削除しない。実行時に依存する gem は、メッセージの翻訳に使う gettext だけ。
5
+ メッセージとレポートは、ロケールが日本語なら日本語、それ以外なら英語で出す。
6
+
7
+ ## インストール
8
+
9
+ Ruby 4.0 に切り替えてから、gem としてビルドしてインストールする。
10
+ タスクは [rubygems-tasks](https://github.com/postmodern/rubygems-tasks) で定義している。
11
+
12
+ ```sh
13
+ bundle install # 依存(gettext と、開発用の rake・rubygems-tasks・ronn-ng・kramdown)を入れる
14
+ rake install # pkg/ に gem をビルドしてインストール
15
+ rake build # ビルドだけ(man page と訳の .mo が無いか古ければ先に作る)
16
+ rake check # 構文チェック(既定のタスク)
17
+ gem uninstall reclaimable
18
+ ```
19
+
20
+ RubyGems が作る実行ファイルは、インストールに使った ruby のパスを直接指すので、
21
+ 実行時に PATH 上の ruby が何であっても Ruby 4.0 で動く。
22
+ ただし、インストール先(chruby なら `~/.gem/ruby/<版>/bin`)が PATH に入っている必要がある。
23
+
24
+ インストールせずに試すとき:
25
+
26
+ ```sh
27
+ ruby -Ilib bin/reclaimable --help
28
+ LC_ALL=C ruby -Ilib bin/reclaimable --help # 英語で表示する
29
+ ```
30
+
31
+ 訳の .mo は git に入れていないので、日本語で表示するには先に `rake gettext` で作る。
32
+
33
+ ## 使い方
34
+
35
+ ```sh
36
+ reclaimable [-n 件数] [-s 最小MB] [-d 起点ディレクトリ] [-j スレッド数] [-o 保存先] [--no-save] [--fresh] [--config ファイル]
37
+ reclaimable --freeze ディレクトリ # 変わらない大きなフォルダーを 1 度だけ測り、以後の走査では読まない
38
+ reclaimable --unfreeze ディレクトリ # 固定を外す
39
+ reclaimable --dump-cache [text|json|yaml] # 走査結果のキャッシュ(Marshal)の中身を書き出す。-d で起点を選ぶ
40
+ reclaimable --man # man page を開く
41
+ reclaimable --ai-skill # AI エージェント向けのスキルの中身と、手で入れる手順を表示する
42
+ reclaimable --install-ai-skill # スキルをどこに入れるかを聞いて、インストールする
43
+ reclaimable --install-ai-skill=DIR # スキル置き場 DIR に、聞かずにインストールする(DIR/reclaimable/ にコピー)
44
+ ```
45
+
46
+ AI エージェント(Claude Code・Codex など)向けのスキルは、[Agent Skills](https://agentskills.io) の形式で
47
+ `ai-skill/reclaimable/` にあり、gem に入る。置き場所は仕様で決まっていないので、既定の置き場所は持たない。
48
+ 引数なしの `--install-ai-skill` は、今あるスキル置き場(`~/.claude/skills`・`~/.agents/skills`)から選ばせる。
49
+ 標準入力が端末でないときは、聞かずに書き方を案内してエラーで終わる。
50
+
51
+ 置き場所は、XDG の環境変数(`XDG_STATE_HOME`・`XDG_CACHE_HOME`・`XDG_CONFIG_HOME`)が設定されていれば
52
+ その下、無ければ macOS では `~/Library` の下、Linux などでは XDG の既定の場所(`lib/reclaimable/paths.rb`)。
53
+
54
+ | 種類 | macOS | Linux など |
55
+ | --- | --- | --- |
56
+ | レポートとログ(`<日時>.report.txt`・`.log`) | `~/Library/Logs/reclaimable/` | `~/.local/state/reclaimable/` |
57
+ | 走査結果のキャッシュ | `~/Library/Caches/reclaimable/` | `~/.cache/reclaimable/` |
58
+ | 設定ファイル(YAML。固定したフォルダー) | `~/Library/Application Support/reclaimable/config.yml` | `~/.config/reclaimable/config.yml` |
59
+
60
+ 詳しい説明は man page にある。gem に入っていて、`reclaimable --man` で開く
61
+ (ロケールが日本語なら日本語版、それ以外なら英語版)。[gem-man](https://rubygems.org/gems/gem-man) でも読める。
62
+
63
+ ```sh
64
+ reclaimable --man
65
+ gem install gem-man
66
+ gem man reclaimable # 英語版の reclaimable.en.1 と日本語版の reclaimable.ja.1 のどちらを開くか聞かれる
67
+ ```
68
+
69
+ ## ドキュメント
70
+
71
+ 原稿は英語の Markdown だけで、日本語版は `po/ja/reclaimable-docs.po` の訳から作る。
72
+
73
+ | 原稿 | 生成物 |
74
+ | --- | --- |
75
+ | `man/reclaimable.1.ronn` | man page(`man/reclaimable.en.1`・`man/reclaimable.ja.1`)と、サイトのマニュアルのページ |
76
+ | `site/index.md` | サイトの概要のページ |
77
+ | `rakelib/docs/sources.rb` の `STRINGS` | サイトのナビゲーションの文言、マニュアルのページの説明文など |
78
+ | `site/layout.html.erb`・`site/style.css` | サイトの全ページ共通の枠と見た目 |
79
+
80
+ ```sh
81
+ rake docs:po # 英語の原稿から訳の雛形を作り、po/ja/reclaimable-docs.po に新しい文を加える
82
+ rake man # man page(roff)を作る(原稿や訳が変わったときだけ)。生成物はコミットしない
83
+ rake site # GitLab Pages に置くサイトを public/ に作る
84
+ rake docs # man page とサイトの両方
85
+ SITE_URL=http://localhost:8000/ rake site && python3 -m http.server 8000 -d public # 手元で確かめる
86
+ ```
87
+
88
+ 訳は段落・見出し・箇条書きの 1 項目・定義リストの項目名・``` のコードブロック・front matter の値を
89
+ 1 項目にしている(段落は原稿の改行を空白にして 1 行にまとめる)。字下げしたコードブロック(コマンドの例)は訳さない。
90
+ 英語の原稿を変えたら `rake docs:po` を実行し、空の msgstr と `#, fuzzy` の項目を直す。
91
+ 訳がない・fuzzy のままの箇所は英語のまま出て、`rake man`・`rake site` が警告する。
92
+
93
+ サイトには、HTML のほかに各ページの Markdown 版・`llms.txt`・`sitemap.xml` も置く。
94
+ 既定のブランチに push すると、`.gitlab-ci.yml` の `pages` ジョブが公開する。
95
+ 変換の処理は `rakelib/docs/` にある。日本語の原稿は、文中の改行を取り除いてから変換し、
96
+ man page では長い行を一定の幅で折り返す(macOS の man は日本語の文を折り返せないため)。
97
+
98
+ ## 翻訳
99
+
100
+ 画面・レポート・ログの文言は [gettext](https://rubygems.org/gems/gettext) で翻訳する
101
+ (ドキュメントの訳は上の「ドキュメント」を参照)。
102
+ 原文は英語で、ソースの `_("...")`・`n_(...)`・`p_(...)` に書く(`lib/reclaimable/i18n.rb` を参照)。
103
+ 日本語訳は `po/ja/reclaimable.po` にある。
104
+
105
+ ```sh
106
+ rake gettext:po:update # ソースから文言を抜き出し、po/ja/reclaimable.po に新しい文言を加える
107
+ # (訳が空の msgstr を埋めてから次へ)
108
+ rake gettext # po から locale/ja/LC_MESSAGES/reclaimable.mo を作る。.mo はコミットしない
109
+ ```
110
+
111
+ 画面の文言とドキュメントの訳をまとめて更新するタスクもある(AI のエージェントはこちらを使う。`AGENTS.md` を参照)。
112
+
113
+ ```sh
114
+ bundle exec rake i18n:todo # po を更新し、訳が無い・fuzzy の項目を ID 付きで出す(tmp/i18n/todo.yml)
115
+ bundle exec rake "i18n:apply[tmp/i18n/ja.yml]" # 「ID: 訳」の YAML を書き込み、.po・.mo・man page を作り直す
116
+ ```
117
+
118
+ 言語は `LC_ALL`・`LC_MESSAGES`・`LANG` の順で決まる。文言を変えたら両方の言語で確かめる。
119
+
120
+ ## 構成
121
+
122
+ | ファイル | 役割 |
123
+ | --- | --- |
124
+ | `bin/reclaimable` | 実行ファイル。`Reclaimable::CLI` を呼ぶだけ |
125
+ | `lib/reclaimable/i18n.rb` | 文言の翻訳(gettext)の入り口。`_`・`n_`・`p_` を定義する |
126
+ | `lib/reclaimable/cli.rb` | 引数の解析と、出力先・レポートの組み立て |
127
+ | `lib/reclaimable/report.rb` | 走査と、節ごとのレポート出力 |
128
+ | `lib/reclaimable/scanner.rb` | ディレクトリツリーの並列走査(手の空いたスレッドに子フォルダーを渡す) |
129
+ | `lib/reclaimable/scan_cache.rb` | 走査結果のキャッシュ(フォルダーごとのノードをつないだ木)の読み書き |
130
+ | `lib/reclaimable/cache_dump.rb` | キャッシュを人向けの表・JSON・YAML で書き出す(`--dump-cache`) |
131
+ | `lib/reclaimable/paths.rb` | 設定ファイル・キャッシュ・レポートとログの置き場所(XDG の環境変数、macOS の規約、XDG の既定の順) |
132
+ | `lib/reclaimable/config.rb` | 設定ファイル(YAML。固定したフォルダー)の読み書き |
133
+ | `lib/reclaimable/bulk_list.rb` | フォルダーの直下をまとめて読む(Fiddle で `getattrlistbulk` を呼ぶ) |
134
+ | `lib/reclaimable/cloud_files.rb` | クラウド上にしか無いファイルをダウンロードさせない設定(Fiddle で `setiopolicy_np` を呼ぶ) |
135
+ | `lib/reclaimable/locations.rb` | 既知のキャッシュ置き場(gem のドキュメントを含む)・コンテナのデータ置き場・gem 置き場 |
136
+ | `lib/reclaimable/ruby_abi.rb` | インストール済み Ruby の ABI 版とフルの版、プロジェクトが使う Ruby の ABI 版 |
137
+ | `lib/reclaimable/output.rb` | 画面・レポート・ログへの書き出しと外部コマンドの実行(走査の前に裏で始めておける) |
138
+ | `lib/reclaimable/util.rb` | サイズやパスの表示の小道具 |
139
+
140
+ 版は gemspec に直接書いている。
141
+
142
+ ## 速さ
143
+
144
+ 高速化のために試した施策と、採用したか・しなかったかの理由は [doc/performance.md](doc/performance.md) に記録してある
145
+ (計測した環境も添えてある)。速さに手を入れる前に読む。
146
+ 変更の前後は、ベンチマーク([benchmark/README.md](benchmark/README.md))で比べる。
147
+
148
+ ## ライセンス
149
+
150
+ GPL-3.0-or-later。全文は `LICENSE` にある。
151
+
152
+ ## Ruby の切り替え
153
+
154
+ chruby を使う場合:
155
+
156
+ ```sh
157
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh # 未読み込みなら
158
+ chruby ruby-4.0 # `chruby 4.0` だと ruby-3.4.0 に一致しうる
159
+ ruby -v
160
+ ```
data/Rakefile ADDED
@@ -0,0 +1,28 @@
1
+ require "rake/clean"
2
+ require "rubygems/tasks"
3
+
4
+ # 日本語を含むファイル(ソースのコメント、ドキュメントの訳)を読むタスクがあるので、
5
+ # LANG が未設定(US-ASCII)の環境でも UTF-8 として読む
6
+ Encoding.default_external = Encoding::UTF_8
7
+
8
+ # build / install / release / console などのタスクを定義する
9
+ Gem::Tasks.new
10
+
11
+ # 既存のタスクへの依存の追加は、見通しがよいようにここにまとめる。
12
+ #
13
+ # パッケージ(pkg/ の .gem。tar・zip も作るようにすればそれも)には、git に入れていない生成物を入れる。
14
+ # 訳の .mo(rakelib/gettext.rake)と man page(rakelib/docs.rake)で、gemspec の files に載せてある。
15
+ # どの形式でも、install・release でも要るので、build:gem でなくパッケージの file タスクの前提にする。
16
+ # rubygems-tasks もパッケージの前提に gemspec の files を並べるが、その作りには頼らずに明示する
17
+ project = Gem::Tasks::Project.directories[Dir.pwd]
18
+ generated = project.gemspec.files.grep(%r{\A(?:locale|man)/})
19
+ project.builds.each_value { |packages| packages.each_value { file it => generated } }
20
+
21
+ CLOBBER.include(generated, "public")
22
+
23
+ desc "実行ファイルとライブラリーの構文を確かめる"
24
+ task :check do
25
+ FileList["bin/*", "lib/**/*.rb"].each { ruby "-wc", it }
26
+ end
27
+
28
+ task default: :check
@@ -0,0 +1,94 @@
1
+ ---
2
+ name: reclaimable
3
+ description: Find what is taking up disk space on a Mac and what can probably be reclaimed (caches, build artifacts, old Ruby gems, container disk images, large files), using the read-only reclaimable command. Use when the user is short on storage, asks what is eating their disk, or wants candidates for cleanup.
4
+ compatibility: Requires macOS and the reclaimable gem (Ruby 4.0 or later).
5
+ ---
6
+
7
+ # reclaimable
8
+
9
+ `reclaimable` lists what uses storage under the home directory and what can
10
+ probably be removed, sorted by size. It is read-only: it never deletes
11
+ anything and never needs `sudo`. Deciding what to remove is the user's job,
12
+ and so is this skill's first rule.
13
+
14
+ ## Rules
15
+
16
+ - Do not delete, move, or clean up anything on your own. Show the candidates,
17
+ explain what removing each one costs, and act only on what the user approves,
18
+ one item (or one clearly named group) at a time.
19
+ - Do not use `sudo`.
20
+ - Prefer each tool's own cleanup command (`brew cleanup`, `docker system prune`,
21
+ `xcrun simctl delete unavailable`, `gem uninstall`, and so on) over `rm -rf`.
22
+ Before proposing a command that removes things, say what it removes.
23
+ - Treat "usually regenerable" as "usually": a cache is rebuilt at the price of
24
+ time and network, and models or backups may be costly to get back.
25
+
26
+ ## Running it
27
+
28
+ Check that it is installed with `reclaimable --help`. If it is not, tell the
29
+ user to run `gem install reclaimable` (it needs Ruby 4.0 or later).
30
+
31
+ Your shell may not have the user's Ruby set up. A version manager (chruby,
32
+ rbenv, mise, asdf) usually sets `PATH` and `GEM_HOME` only in the user's own
33
+ login shell, so here `ruby` can be the old system Ruby (`/usr/bin/ruby` is 2.6
34
+ on macOS) and the gem looks missing or fails to start. Run `ruby -v` first. If
35
+ it is older than 4.0, switch to Ruby 4.0 in the same command before running
36
+ `reclaimable`, for example:
37
+
38
+ source /opt/homebrew/share/chruby/chruby.sh && chruby ruby-4.0 && reclaimable --help
39
+ eval "$(rbenv init -)" && RBENV_VERSION=4.0.0 reclaimable --help
40
+
41
+ (Use whichever manager is installed. With chruby, `chruby 4.0` can match
42
+ ruby-3.4.0, so spell `ruby-4.0`.) Check `ruby -v` again after switching. Do
43
+ not run `gem install` with the system Ruby, and do not tell the user the gem is
44
+ missing until you have tried a Ruby 4.0. If no Ruby 4.0 is installed, tell the
45
+ user and stop.
46
+
47
+ reclaimable
48
+
49
+ - A full scan of the home directory takes from tens of seconds to several
50
+ minutes. Run it with a long timeout or in the background, and do not start a
51
+ second scan while one is running.
52
+ - The report goes to standard output. It is also saved, with a log, as
53
+ `<YYYYmmdd-HHMMSS>.report.txt` and `.log` in `~/Library/Logs/reclaimable/`
54
+ (or `$XDG_STATE_HOME/reclaimable/`). Read the saved file instead of scanning
55
+ again when a recent one answers the question.
56
+ - The report is in Japanese when the locale is Japanese. Run
57
+ `LC_ALL=C reclaimable` to get English.
58
+ - Scan results are cached, so a second run is faster. `--fresh` ignores the cache.
59
+
60
+ Useful options:
61
+
62
+ reclaimable -n 50 -s 500 # 50 entries per ranking; files of 500 MB or more are "large"
63
+ reclaimable -d ~/src --no-save # scan one folder and save nothing
64
+ reclaimable --dump-cache json # the cached scan (folder sizes), without scanning
65
+
66
+ `reclaimable --help` lists every option. `reclaimable --man | col -b` prints
67
+ the full manual, including what each section of the report means.
68
+
69
+ ## Reading the report
70
+
71
+ Sections are headed `==== Title ====`. The ones that matter most for cleanup:
72
+
73
+ - **Usually regenerable**: known caches and downloads, each with a note on what
74
+ happens if it is removed. Usually the safest place to start.
75
+ - **Build artifacts and dependencies**: `node_modules`, `.venv`, `target`, and
76
+ the like, with the date each was last modified. Old dates point to projects
77
+ the user no longer touches.
78
+ - **Ruby gems**: gems left behind by Ruby versions that are no longer installed.
79
+ - **Containers**: Docker, Colima, OrbStack, and others. Sparse disk images look
80
+ larger than the space they really use; the report shows both.
81
+ - **Large files**: the user has to judge these one by one. Do not guess.
82
+ - **Unreadable locations**: folders missing from the totals. If Desktop,
83
+ Documents, or Downloads are here, the terminal app lacks Full Disk Access;
84
+ tell the user rather than working around it.
85
+
86
+ ## Reporting to the user
87
+
88
+ Summarize rather than paste the whole report: how full the disk is, then the
89
+ largest candidates grouped by how safe they are to remove, each with its size,
90
+ its path, and what removing it costs. Ask which ones to act on.
91
+
92
+ If a large folder never changes and slows every scan, suggest
93
+ `reclaimable --freeze <folder>`: it is measured once and skipped afterwards.
94
+ This writes the config file, so ask first.
@@ -0,0 +1,59 @@
1
+ # ベンチマーク
2
+
3
+ reclaimable の速さを測り、変更の前後で比べるためのもの。標準の benchmark ライブラリーを使う。
4
+
5
+ ## 測る
6
+
7
+ ```sh
8
+ bundle exec rake "benchmark[ラベル]"
9
+ ```
10
+
11
+ 結果を画面に出し、`benchmark/results/<ラベル>.yml` に保存する(ラベルを省くと `latest`)。
12
+ 何も削除せず、利用者のキャッシュ(`~/Library/Caches/reclaimable`)も書き換えない。
13
+
14
+ 既定では、作り物のフォルダーツリー(フィクスチャー)を `tmp/benchmark/fixture` に作って測る。
15
+ 乱数の種を固定してあるので毎回同じ形になり、同じ設定のものがあれば作り直さない(初回だけ 20 秒ほどかかる)。
16
+
17
+ | 環境変数 | 意味 | 既定 |
18
+ | --- | --- | --- |
19
+ | `JIT` | `yjit` か `zjit` を付けて測る(rake タスクが `RUBYOPT` に足す) | なし |
20
+ | `BENCH_ROOT` | フィクスチャーの代わりに測る実際のフォルダー(`~/src` など) | フィクスチャー |
21
+ | `BENCH_DIRS` | フィクスチャーのフォルダー数 | 30000 |
22
+ | `BENCH_REPS` | シナリオごとの繰り返しの回数 | 5 |
23
+ | `BENCH_JOBS` | 走査のスレッド数(`-j`) | CPU の数(最大 8) |
24
+ | `BENCH_ONLY` | 名前がこの正規表現に合うシナリオだけ測る(`scan` など) | 全部 |
25
+ | `BENCH_REQUIRE`・`BENCH_SCANNER` | 試作の走査に差し替える(読み込むファイルとクラス名) | `Reclaimable::Scanner` |
26
+
27
+ ## シナリオ
28
+
29
+ | 名前 | 測るもの |
30
+ | --- | --- |
31
+ | `scan (no cache)` | キャッシュ無しの走査(初回や `--fresh`) |
32
+ | `scan (cached)` | 前回の走査結果を使う走査(2 回目以降。ふだんはこれ) |
33
+ | `cache save`・`cache load` | 走査結果のキャッシュの書き込み・読み込み |
34
+ | `cache dump (json)` | `--dump-cache json` |
35
+ | `startup (--help)` | 起動してすぐ終わるまで(ライブラリーの読み込み) |
36
+
37
+ 測る前に 1 回走査して OS のファイルキャッシュを温める(ディスクの読み込み待ちでなく、プログラムの側の速さを比べるため)。
38
+ `user`・`system` は全スレッドの CPU 時間の合計なので、並列に動く走査では `real` より大きくなる。
39
+
40
+ ## 比べる
41
+
42
+ ```sh
43
+ bundle exec rake "benchmark:compare[baseline,新しいラベル]"
44
+ ```
45
+
46
+ 最初のラベルを基準に、各シナリオの `real` の最小値と、基準に対する比を並べる(1 未満なら速くなった)。
47
+ ラベルを省くと、保存してある結果を古い順に全部並べる。
48
+ 合計バイト数がラベルによって違うときは注意を出す(速さ以前に、走査結果が変わっていないかを確かめるため)。
49
+
50
+ 改善・改悪を見張るには、変更の前に `baseline` などのラベルで測っておき、変更のあとに別のラベルで測って比べる。
51
+ 時間は機械やそのときの負荷で変わるので、比べるのは同じ機械で続けて測ったものどうしにする。
52
+
53
+ ## 置いてあるもの
54
+
55
+ - `run.rb` — 計測の本体
56
+ - `lib/` — フィクスチャーの生成と、結果の保存・比較
57
+ - `results/` — 保存した結果
58
+ - `reports/` — 施策ごとのリポート
59
+ - `experiments/` — 試作(本体には入れていない実装)
@@ -0,0 +1,11 @@
1
+ # 比較用: フォルダーの一覧を getattrlistbulk でなく、名前ごとの lstat で読む走査(以前の読み方)。
2
+ #
3
+ # BENCH_REQUIRE=benchmark/experiments/lstat_scanner.rb BENCH_SCANNER=Reclaimable::LstatScanner \
4
+ # bundle exec rake "benchmark[lstat]"
5
+ module Reclaimable
6
+ class LstatScanner < Scanner
7
+ private
8
+
9
+ def read_dir(dir) = read_dir_by_lstat(dir)
10
+ end
11
+ end
@@ -0,0 +1,92 @@
1
+ # 試作: スレッドの代わりに Ractor でサブツリーを並列にたどる走査。
2
+ #
3
+ # BENCH_REQUIRE=benchmark/experiments/ractor_scanner.rb BENCH_SCANNER=Reclaimable::RactorScanner \
4
+ # bundle exec rake "benchmark[ractor]"
5
+ #
6
+ # スレッドは GVL(同時に Ruby のコードを実行できるのは 1 スレッドだけ)の制約を受けるが、Ractor どうしは
7
+ # 並列に Ruby のコードを実行できる。その代わり、Ractor の間では変更できるオブジェクトを共有できない。
8
+ #
9
+ # 作り:
10
+ # - 親(メインの Ractor)が深さ split_depth まで自分でたどり、その下のサブツリーをタスクとして集める。
11
+ # - ワーカーの Ractor が、手が空くたびに親へ自分の Port を送ってタスクを 1 つ受け取り、サブツリーを最後までたどる。
12
+ # - ワーカーは終わるときに、タスクごとの合計と集計結果(Collector)を Ractor#value で親に渡す。
13
+ #
14
+ # 本体の Scanner と違うところ(試作なので割り切っている):
15
+ # - ハードリンクの重複は Ractor ごとにしか除けない(同じ inode を別の Ractor が見ると二重に数える)。
16
+ # - 手の空いたワーカーへ、たどっている途中で子フォルダーを渡すことはしない(タスクは深さ split_depth の単位だけ)。
17
+ # - 進捗表示とタスクごとの所要時間の記録はしない。
18
+ # - 前回の走査結果(old_cache)は、Ractor の間で共有できるよう全体を凍結する(Ractor.make_shareable)。
19
+ #
20
+ # 注意: この試作は、計測したとき(コミット c85d143 の Scanner)の作りに合わせてある。
21
+ # その後 Scanner は走査結果を木で持つ形に変わった(old_cache → old_tree)ので、今のコードではそのままは動かない。
22
+ # 測り直すときは、c85d143 を取り出して動かすか、今の Scanner に合わせて書き直す
23
+ module Reclaimable
24
+ class RactorScanner < Scanner
25
+ # ワーカーの Ractor から読む定数は、共有できる(凍結されている)必要がある
26
+ Ractor.make_shareable(Scanner::ARTIFACT_NAMES)
27
+
28
+ # 手が空いて待っているスレッドは無い、と答えるだけのキュー(ワーカーの中で、子フォルダーを渡さないようにする)
29
+ class NoHandOff
30
+ def num_waiting = 0
31
+ end
32
+
33
+ def scan
34
+ root_st = File.stat(@root)
35
+ @root_dev = root_st.dev
36
+ @tasks = []
37
+ parent_col = Collector.empty
38
+ # 浅い階層は親がたどり、深さ split_depth のフォルダーをタスクとして集める(enqueue を参照)
39
+ tree = walk(@root, root_st, 0, false, false, parent_col, parent: true)
40
+
41
+ config = Ractor.make_shareable(
42
+ { root: @root, root_dev: @root_dev, big_threshold: @big_threshold, large: @large, watched: @watched,
43
+ record_depth: @record_depth, no_artifacts_in: @no_artifacts_in, old_cache: @old_cache, skip: @skip,
44
+ frozen: @frozen }
45
+ )
46
+ requests = Ractor::Port.new
47
+ workers = Array.new(@jobs) { Ractor.new(requests, config) { |requests, config| RactorScanner.work(requests, config) } }
48
+ @tasks.each_with_index do |task, i|
49
+ requests.receive << [i, task.path, task.depth, task.in_artifact, task.artifact]
50
+ end
51
+ @jobs.times { requests.receive << nil } # もうタスクは無い
52
+ cols = workers.map do |worker|
53
+ totals, col = worker.value
54
+ totals.each { |i, total| @tasks[i].result = total }
55
+ col
56
+ end
57
+
58
+ total = resolve(tree, parent_col)
59
+ @result = cols.reduce(parent_col) { |acc, col| acc.merge!(col) }
60
+ @old_cache = nil
61
+ total
62
+ end
63
+
64
+ # ワーカーの Ractor の本体。[[タスクの番号, 合計のバイト数], ...] と Collector を返す
65
+ def self.work(requests, config)
66
+ scanner = new(config[:root], **config.slice(:big_threshold, :large, :watched, :record_depth, :no_artifacts_in,
67
+ :old_cache, :skip, :frozen))
68
+ scanner.instance_variable_set(:@root_dev, config[:root_dev])
69
+ scanner.instance_variable_set(:@queue, NoHandOff.new)
70
+ col = Collector.empty
71
+ mine = Ractor::Port.new
72
+ totals = []
73
+ loop do
74
+ requests << mine
75
+ i, path, depth, in_artifact, artifact = mine.receive
76
+ break unless i
77
+
78
+ st = (File.lstat(path) rescue nil)
79
+ totals << [i, st ? scanner.send(:walk, path, st, depth, in_artifact, artifact, col, parent: false) : 0]
80
+ end
81
+ [totals, col]
82
+ end
83
+
84
+ private
85
+
86
+ # 親が積むタスクは、キューでなく配列に集める
87
+ def enqueue(task)
88
+ @tasks << task
89
+ task
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,34 @@
1
+ # getattrlistbulk での読み方が、lstat での読み方と同じ結果になるかを、実際のフォルダーで確かめる。
2
+ #
3
+ # bundle exec ruby benchmark/experiments/verify_bulk_list.rb ~/Library
4
+ #
5
+ # 両方の読み方で走査し、フォルダーごとの記録(小さいファイルの合計・子フォルダー名・大きいファイル名)を比べる。
6
+ # 走査の合間に中身が変わったフォルダーは食い違うので、動いているアプリのデータがある場所では少し出る
7
+ Encoding.default_external = Encoding::UTF_8
8
+ $LOAD_PATH.unshift(File.expand_path("../../lib", __dir__))
9
+ require "reclaimable"
10
+ require_relative "lstat_scanner"
11
+
12
+ root = File.expand_path(ARGV.fetch(0))
13
+ why = Reclaimable::CloudFiles.stop_downloads
14
+ skip = why ? Reclaimable::CloudFiles::DIRS : []
15
+ scan = lambda do |klass|
16
+ scanner = klass.new(root, big_threshold: 100 * Reclaimable::MB, large: 10 * Reclaimable::MB, jobs: 8, skip:)
17
+ total = scanner.scan
18
+ # 名前の並びは読み方によって違ってよい。更新時刻は、走査の合間の変化を見分けるのに使う
19
+ nodes = scanner.tree ? Reclaimable::ScanCache.flatten(scanner.tree, root) : {}
20
+ [total, nodes.transform_values { |stamp, small, big, links, kids| [stamp, small, big&.sort, links, kids&.keys&.sort] }]
21
+ end
22
+ lstat_total, lstat = scan.(Reclaimable::LstatScanner)
23
+ bulk_total, bulk = scan.(Reclaimable::Scanner)
24
+ puts "lstat: #{lstat.size} フォルダー、合計 #{lstat_total} バイト"
25
+ puts "bulk: #{bulk.size} フォルダー、合計 #{bulk_total} バイト"
26
+ paths = lstat.keys | bulk.keys
27
+ changed, differ = paths.reject { lstat[it] == bulk[it] }.partition { lstat[it]&.first != bulk[it]&.first }
28
+ puts "走査の合間に変わった(更新時刻が違う・片方にしか無い)フォルダー: #{changed.size}"
29
+ puts "更新時刻が同じなのに記録が違うフォルダー: #{differ.size}"
30
+ differ.first(20).each do |path|
31
+ puts path
32
+ puts " lstat: #{lstat[path].inspect[0, 300]}"
33
+ puts " bulk: #{bulk[path].inspect[0, 300]}"
34
+ end
@@ -0,0 +1,104 @@
1
+ require "fileutils"
2
+
3
+ module ReclaimableBenchmark
4
+ # ベンチマーク用のフォルダーツリー。毎回同じ形になるよう、乱数の種を固定して作る。
5
+ # 実際のホームに似せて、次のものを混ぜる。
6
+ # - ファイルの多い深いツリー(node_modules のような、小さいファイルが大量にあるフォルダー)
7
+ # - ビルド成果物のフォルダー(node_modules・.venv・Cargo の target)と vendor/bundle/ruby/<ABI 版>
8
+ # - 大きいファイル(スパースファイルなので、ディスクはほとんど使わない)とハードリンク
9
+ # 作るのに時間がかかるので、同じ設定のものがあれば作り直さない
10
+ class Fixture
11
+ VERSION = 1
12
+ ARTIFACTS = %w[node_modules .venv].freeze
13
+
14
+ attr_reader :root, :dirs, :files
15
+
16
+ # dirs: 作るフォルダーのおおよその数
17
+ def initialize(root, dirs: 30_000, seed: 42)
18
+ @root = root
19
+ @target = dirs
20
+ @seed = seed
21
+ @stamp = File.join(File.dirname(root), "#{File.basename(root)}.stamp")
22
+ end
23
+
24
+ def signature = "v#{VERSION} dirs=#{@target} seed=#{@seed}"
25
+
26
+ def ensure!
27
+ return self if File.directory?(@root) && File.exist?(@stamp) && File.read(@stamp) == signature
28
+
29
+ warn "フィクスチャーを作ります: #{@root} (#{signature})"
30
+ FileUtils.rm_rf(@root)
31
+ FileUtils.rm_f(@stamp)
32
+ build
33
+ File.write(@stamp, signature)
34
+ warn " #{@dirs} フォルダー、#{@files} ファイル"
35
+ self
36
+ end
37
+
38
+ private
39
+
40
+ def build
41
+ @rng = Random.new(@seed)
42
+ @dirs = 0
43
+ @files = 0
44
+ FileUtils.mkdir_p(@root)
45
+ # 深さ 3 までは枝分かれを多くして、並列化の単位(深さ 3 のフォルダー)が十分な数になるようにする
46
+ projects = 0
47
+ while @dirs < @target
48
+ projects += 1
49
+ project = File.join(@root, format("group%02d/project%03d", projects % 12, projects))
50
+ tree(project, 0)
51
+ special(project) if (projects % 3).zero?
52
+ end
53
+ end
54
+
55
+ # 普通のフォルダー。深くなるほど枝分かれを減らす
56
+ def tree(dir, depth)
57
+ mkdir(dir)
58
+ small_files(dir, @rng.rand(0..10))
59
+ return if depth >= 6
60
+
61
+ @rng.rand(depth < 2 ? 2..4 : 0..3).times { |i| tree(File.join(dir, "d#{i}"), depth + 1) }
62
+ end
63
+
64
+ # ビルド成果物・vendor/bundle・大きいファイル・ハードリンク
65
+ def special(project)
66
+ packages(File.join(project, ARTIFACTS.sample(random: @rng)), @rng.rand(20..60))
67
+ packages(File.join(project, "vendor/bundle/ruby/4.0.0/gems"), @rng.rand(5..20))
68
+ target = File.join(project, "target")
69
+ packages(target, 5)
70
+ File.write(File.join(target, "CACHEDIR.TAG"), "Signature: 8a477f597d28d172789f06886806bc55\n")
71
+ big = File.join(project, "disk.img")
72
+ File.open(big, "w") { it.truncate(@rng.rand(20..300) * 1024 * 1024) } # スパースファイル
73
+ File.link(big, File.join(project, "disk-link.img"))
74
+ @files += 3
75
+ end
76
+
77
+ # node_modules のような、パッケージごとのフォルダーが並ぶ置き場
78
+ def packages(dir, count)
79
+ FileUtils.mkdir_p(dir)
80
+ @dirs += 1
81
+ count.times do |i|
82
+ pkg = File.join(dir, "pkg#{i}")
83
+ mkdir(pkg)
84
+ small_files(pkg, @rng.rand(3..8))
85
+ %w[lib dist].each do |sub|
86
+ mkdir(File.join(pkg, sub))
87
+ small_files(File.join(pkg, sub), @rng.rand(5..25))
88
+ end
89
+ end
90
+ end
91
+
92
+ def mkdir(dir)
93
+ FileUtils.mkdir_p(dir)
94
+ @dirs += 1
95
+ end
96
+
97
+ def small_files(dir, count)
98
+ count.times do |i|
99
+ File.write(File.join(dir, "f#{i}.txt"), "x" * @rng.rand(0..2000))
100
+ end
101
+ @files += count
102
+ end
103
+ end
104
+ end
@@ -0,0 +1,62 @@
1
+ require "yaml"
2
+
3
+ module ReclaimableBenchmark
4
+ # 計測結果の保存と比較。結果はラベルごとに benchmark/results/<ラベル>.yml に書く。
5
+ # 比べるのは各シナリオの real(壁時計の時間)の最小値。繰り返しのうち、ほかのプロセスに
6
+ # 邪魔されなかった回がその処理の実力に近いので、平均でなく最小値を使う(中央値も並べて出す)
7
+ module Results
8
+ DIR = File.expand_path("../results", __dir__)
9
+
10
+ module_function
11
+
12
+ def path(label) = File.join(DIR, "#{label}.yml")
13
+
14
+ def save(label, data)
15
+ FileUtils.mkdir_p(DIR)
16
+ File.write(path(label), YAML.dump(data))
17
+ path(label)
18
+ end
19
+
20
+ def load(label)
21
+ file = File.file?(label) ? label : path(label)
22
+ abort "結果がありません: #{file}(先に rake \"benchmark[#{label}]\" で計測する)" unless File.file?(file)
23
+ YAML.safe_load_file(file)
24
+ end
25
+
26
+ def labels = Dir[File.join(DIR, "*.yml")].sort_by { File.mtime(it) }.map { File.basename(it, ".yml") }
27
+
28
+ def min(times) = times.min
29
+ def median(times) = times.sort[times.size / 2]
30
+
31
+ # 最初のラベルを基準に、各ラベルの real の最小値と、基準に対する比を並べる。
32
+ # 比は 1 未満なら速くなった、1 より大きければ遅くなった
33
+ def compare(labels, out = $stdout)
34
+ runs = labels.map { load(it) }
35
+ base = runs.first
36
+ names = runs.flat_map { it["scenarios"].keys }.uniq
37
+ width = names.map(&:size).max
38
+ out.puts format("%-#{width}s %s", "real(最小) 秒", labels.map { format("%22s", it[0, 22]) }.join)
39
+ names.each do |name|
40
+ base_time = base.dig("scenarios", name, "real")&.then { min(it) }
41
+ cells = runs.map do |run|
42
+ times = run.dig("scenarios", name, "real")
43
+ next format("%22s", "-") unless times
44
+
45
+ ratio = base_time ? format("(x%.2f)", min(times) / base_time) : ""
46
+ format("%13.3f %8s", min(times), ratio)
47
+ end
48
+ out.puts format("%-#{width}s %s", name, cells.join)
49
+ end
50
+ out.puts
51
+ runs.each_with_index do |run, i|
52
+ out.puts format("%s: %s / jit=%s / jobs=%s / %s フォルダー / 合計 %s バイト / %s", labels[i], run["ruby"], run["jit"],
53
+ run["jobs"], run["dirs"], run["total_bytes"], run["root"])
54
+ end
55
+ # 走査結果が違っていたら、速さ以前に結果が変わってしまっている。同じ場所を測ったものどうしだけ比べる
56
+ same_root = runs.select { it["root"] == base["root"] && it["measured_at"] }
57
+ return if same_root.map { it["total_bytes"] }.uniq.size <= 1
58
+
59
+ out.puts "注意: 合計バイト数がラベルによって違います(走査の合間に中身が変わったか、走査結果が変わった)"
60
+ end
61
+ end
62
+ end