-
Notifications
You must be signed in to change notification settings - Fork 247
chore: Add memory reservation debug logging and visualization #2521
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
base: main
Are you sure you want to change the base?
Changes from 27 commits
7252605
d084cfa
4837935
ad9c9b8
f3bb412
13f14d3
78f5b4f
5a39d3b
dc11515
d2a1ab1
31cdbc6
ffb1f71
322b4c5
89e10ac
3b191fd
7c24836
405f5b7
522238d
36565ca
21189a6
dfa2c67
d9817ce
acba7bc
4051d29
df69875
ad891a0
8756256
7eb1bc1
21bd386
ec823c2
a66fa65
12db37f
2fb336e
706f5e7
4faf881
d91abda
f6128b5
7d40ac2
c495897
06814b7
e51751f
75e727f
e844287
2884ed3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| #!/usr/bin/python | ||
| ############################################################################## | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. | ||
| ############################################################################## | ||
|
|
||
| import argparse | ||
| from pathlib import Path | ||
| import pandas as pd | ||
| import matplotlib.pyplot as plt | ||
|
|
||
| def main(): | ||
| ap = argparse.ArgumentParser() | ||
| ap.add_argument("csv", help="CSV with columns: name,size") | ||
| ap.add_argument("--instant", action="store_true", | ||
| help="Plot per-step stacked values (not cumulative totals).") | ||
| ap.add_argument("--bar", action="store_true", | ||
| help="Use stacked bars instead of stacked area.") | ||
| ap.add_argument("--title", default=None, help="Optional plot title.") | ||
| args = ap.parse_args() | ||
|
|
||
| path = Path(args.csv) | ||
| df = pd.read_csv(path) | ||
|
|
||
| # Validate + clean | ||
| need = {"name", "size"} | ||
| if not need.issubset(set(df.columns)): | ||
| raise SystemExit("CSV must have columns: name,size") | ||
|
|
||
| df["size"] = pd.to_numeric(df["size"], errors="coerce").fillna(0) | ||
|
|
||
| # Treat each row as the next time step: t = 1..N | ||
| df = df.reset_index(drop=True).assign(t=lambda d: d.index + 1) | ||
|
|
||
| # Build wide matrix: one column per name, one row per time step | ||
| # If multiple entries exist for the same (t, name), they’ll be summed. | ||
| wide = ( | ||
| df.groupby(["t", "name"], as_index=False)["size"].sum() | ||
| .pivot(index="t", columns="name", values="size") | ||
| .fillna(0.0) | ||
| .sort_index() | ||
| ) | ||
|
|
||
| # Running totals unless --instant specified | ||
| plot_data = wide if args.instant else wide.cumsum(axis=0) | ||
|
|
||
| # Plot | ||
| if args.bar: | ||
| ax = plot_data.plot(kind="bar", stacked=True, figsize=(12, 6), width=1.0) | ||
| else: | ||
| ax = plot_data.plot.area(stacked=True, figsize=(12, 6)) | ||
|
|
||
| ax.set_xlabel("step") | ||
| ax.set_ylabel("size" if args.instant else "cumulative size") | ||
| ax.set_title(args.title or ("Stacked running totals by name" if not args.instant | ||
| else "Stacked per-step values by name")) | ||
| ax.legend(title="name", bbox_to_anchor=(1.02, 1), loc="upper left") | ||
| plt.tight_layout() | ||
|
|
||
| out = path.with_suffix(".stacked.png" if args.instant else ".stacked_cumulative.png") | ||
| plt.savefig(out, dpi=150) | ||
| print(f"Saved plot to {out}") | ||
| plt.show() | ||
|
|
||
| if __name__ == "__main__": | ||
| main() |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| #!/usr/bin/python | ||
| ############################################################################## | ||
| # Licensed to the Apache Software Foundation (ASF) under one | ||
| # or more contributor license agreements. See the NOTICE file | ||
| # distributed with this work for additional information | ||
| # regarding copyright ownership. The ASF licenses this file | ||
| # to you under the Apache License, Version 2.0 (the | ||
| # "License"); you may not use this file except in compliance | ||
| # with the License. You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, | ||
| # software distributed under the License is distributed on an | ||
| # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| # KIND, either express or implied. See the License for the | ||
| # specific language governing permissions and limitations | ||
| # under the License. | ||
| ############################################################################## | ||
|
|
||
| import argparse | ||
| import re | ||
| import sys | ||
|
|
||
| def main(file, task_filter): | ||
| # keep track of running total allocation per consumer | ||
| alloc = {} | ||
|
|
||
| # open file | ||
| with open(file) as f: | ||
| # iterate over lines in file | ||
| print("name,size") | ||
| for line in f: | ||
| # print(line, file=sys.stderr) | ||
|
|
||
| # example line: [Task 486] MemoryPool[HashJoinInput[6]].shrink(1000) | ||
| # parse consumer name | ||
| re_match = re.search('\[Task (.*)\] MemoryPool\[(.*)\]\.(.*)\((.*)\)', line, re.IGNORECASE) | ||
| if re_match: | ||
| try: | ||
| task = int(re_match.group(1)) | ||
| if task != task_filter: | ||
| continue | ||
|
|
||
| consumer = re_match.group(2) | ||
| method = re_match.group(3) | ||
| size = int(re_match.group(4)) | ||
| if method == "try_grow": | ||
| if "Err" in line: | ||
| continue | ||
|
|
||
| if alloc.get(consumer) is None: | ||
| alloc[consumer] = size | ||
| else: | ||
| if method == "grow" or method == "try_grow": | ||
| alloc[consumer] = alloc[consumer] + size | ||
| elif method == "shrink": | ||
| alloc[consumer] = alloc[consumer] - size | ||
| print(consumer, ",", alloc[consumer]) | ||
| except: | ||
| print("error parsing", line, file=sys.stderr) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| ap = argparse.ArgumentParser(description="Generate CSV From memory debug output") | ||
| ap.add_argument("--task", default=None, help="Task ID.") | ||
| ap.add_argument("--file", default=None, help="Spark log containing memory debug output") | ||
| args = ap.parse_args() | ||
| main(args.file, int(args.task)) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,88 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| use datafusion::execution::memory_pool::{MemoryPool, MemoryReservation}; | ||
| use log::info; | ||
| use std::sync::Arc; | ||
|
|
||
| #[derive(Debug)] | ||
| pub(crate) struct LoggingPool { | ||
| task_attempt_id: u64, | ||
| pool: Arc<dyn MemoryPool>, | ||
| } | ||
|
|
||
| impl LoggingPool { | ||
| pub fn new(task_attempt_id: u64, pool: Arc<dyn MemoryPool>) -> Self { | ||
| Self { | ||
| task_attempt_id, | ||
| pool, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl MemoryPool for LoggingPool { | ||
| fn grow(&self, reservation: &MemoryReservation, additional: usize) { | ||
| info!( | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Would it be useful to add a debug! log message which has the backtrace of where this was requested from? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good idea. I updated There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I was thinking that we do this for every call (not just for the error) so we can trace the precise origins of the allocations. Probably should be a trace message (not a debug) though. This is merely a suggestion though, I'll leave it to you to decide if it is useful. |
||
| "[Task {}] MemoryPool[{}].grow({})", | ||
parthchandra marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self.task_attempt_id, | ||
| reservation.consumer().name(), | ||
| additional | ||
| ); | ||
| self.pool.grow(reservation, additional); | ||
| } | ||
|
|
||
| fn shrink(&self, reservation: &MemoryReservation, shrink: usize) { | ||
| info!( | ||
| "[Task {}] MemoryPool[{}].shrink({})", | ||
| self.task_attempt_id, | ||
| reservation.consumer().name(), | ||
| shrink | ||
| ); | ||
| self.pool.shrink(reservation, shrink); | ||
| } | ||
|
|
||
| fn try_grow( | ||
| &self, | ||
| reservation: &MemoryReservation, | ||
| additional: usize, | ||
| ) -> datafusion::common::Result<()> { | ||
| match self.pool.try_grow(reservation, additional) { | ||
| Ok(_) => { | ||
| info!( | ||
| "[Task {}] MemoryPool[{}].try_grow({}) returning Ok", | ||
| self.task_attempt_id, | ||
| reservation.consumer().name(), | ||
| additional | ||
| ); | ||
| Ok(()) | ||
| } | ||
| Err(e) => { | ||
| info!( | ||
| "[Task {}] MemoryPool[{}].try_grow({}) returning Err: {e:?}", | ||
| self.task_attempt_id, | ||
| reservation.consumer().name(), | ||
| additional | ||
| ); | ||
| Err(e) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn reserved(&self) -> usize { | ||
| self.pool.reserved() | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,6 +17,7 @@ | |
|
|
||
| mod config; | ||
| mod fair_pool; | ||
| pub mod logging_pool; | ||
| mod task_shared; | ||
| mod unified_pool; | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
rather than adding yet another flag to this API call, I am now using the already available spark config map in native code.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
+1. The config map should be the preferred method