Repository navigation
Conversation
This was referenced Nov 14, 2026
certik
marked this pull request as ready for review
November 14, 2026 18:28
certik
force-pushed
the
recoverable-errors
branch
from
November 14, 2026 21:22
55bbddf to
9371c51
Compare
Member
Author
|
I am reworking this. We should get rid of most of the error statuses, since most of them are various argument checking and calling order, but those we should just error stop, as that's a bug in the user's code. Only for truly runtime errors we should return error state to the user, which will greatly simplify the API. |
certik
marked this pull request as draft
November 14, 2026 21:45
Below the plotting API, a call that breaks a documented precondition is a bug in the caller: drawing before open_canvas, a nonfinite coordinate, an alpha outside [0,1], an unknown fill rule, an unmatched end_group, bytes before close_canvas. fplotlib_render_checks holds these checks, and contract_error stops the program with a message naming the broken rule. Only a failure that a correct program can still meet is returned: an output file that cannot be opened, written or closed. fplotlib_io's write_bytes reports it through a required status_t from fplotlib_status. savefig and save_animation stop with that message instead of printing a warning and carrying on. renderer_t is the drawing contract alone; encoded_renderer_t extends it with bytes for the SVG, PNG, PDF and EPS backends. The FAMILY_* selector is gone, since every backend drew the one built-in sans regardless. Every test picture is byte-identical to main.
certik
force-pushed
the
recoverable-errors
branch
from
November 14, 2026 21:57
9371c51 to
688e10b
Compare
certik
marked this pull request as ready for review
November 21, 2026 17:36
renderer_t's public methods are now non_overridable: each checks the call, keeps the canvas state (open, finished, group depth) and then calls the backend's deferred *_impl method. The backends no longer repeat the checks, so they cannot disagree about them: an end_group without a begin_group now stops on every backend, not only SVG. The checks move into fplotlib_render and fplotlib_render_checks goes away; contract_error moves to fplotlib_status, next to status_t. The PDF backend's image and transparency tables grow instead of silently dropping everything past 16 images or 64 alpha values. savefig and save_animation take an optional status for a file that cannot be written, and stop without one. Their argument errors, and those of the other plotting procedures, stop through contract_error, so every stop has the same form. Font sizes may be zero everywhere; text_layout, math_layout and the glyph run checks agree on finite and nonnegative. The I/O message no longer repeats the file name when the compiler's message already has it, and file_ext reuses lower, now in fplotlib_style.
A NaN or an infinity in plotted data is missing data to matplotlib, but only plot dropped it before drawing, so bar, errorbar, boxplot, contourf, axvline, text and most other plot types handed it to a renderer, which now stops on a nonfinite coordinate. Every renderer call of the plotting layer now goes through put_path, put_rect, put_circle, put_markers, put_glyphs and put_image in fplotlib_artist, which leave out what is missing as matplotlib's path handling does: a path is broken where a vertex is missing, and a shape, marker, label or image placed at a missing point is not drawn. A call with nothing missing reaches the renderer unchanged, so every existing picture is byte for byte the same. hist2d and hexbin skip points with a missing coordinate and streamplot ends a line where the field is missing; all three crashed on NaN before. xlim, ylim and zlim stop on a nonfinite limit, as matplotlib raises, and widen a range too narrow to tell its ends apart instead of dividing by it. tests/test_missing.f90 renders 44 plot types with NaN and infinite values in all four formats and checks that none stops and that no NaN or infinity reaches the SVG or EPS. The README gets an Errors section with the policy and an example of savefig's status.
pie treats a missing value as an empty wedge; on main a NaN value gave the wedge a NaN angle, from which it took an undefined number of segments and wrote past its arrays (gfortran -O3 crashed in the new missing-data test). The 3D limits and scatter3d's depth shading skip missing values, and a range made of nothing but missing data has no ticks, where the tick loop used to run on undefined bounds. tests/test_contract.f90 checks that twelve broken calls stop with the rule they broke. A program cannot catch error stop, so test_plots runs itself again once per case, as "test_plots contract k", and checks the exit status and standard error of each run. The missing-data test gains four plots of nothing but missing data.
The second review found that the plotting API left its own argument checks to whatever part of the drawing tripped over a bad value first: plot(alpha=1.5) stopped only in savefig, naming the paint, while markersize=NaN or subplots_adjust(left=NaN) silently drew nothing, since the missing-data layer cannot tell a NaN parameter from missing data. Every public plotting procedure now checks its alpha (in [0,1]) and its widths and sizes (finite, nonnegative) on entry, naming itself in the message. figure, rc, add_axes, subplots_adjust, set_aspect, margins, colorbar, set_fontsize, tight_layout, savefig and hist check their own layout arguments; pie stops on a negative value, as matplotlib raises. tight_layout on a figure too small for its decorations used to give the axes a negative size, which now reaches the renderer and stops; it keeps the old layout instead, with matplotlib's warning. An axes or a colorbar the layout leaves no room for is not drawn. Also from the review: - put_path no longer closes a contour whose first point was missing. - hist skips missing values instead of taking its range from them. - show takes an optional status and only reports a failure without it. - A file that cannot be written stops with exit code 2, apart from the 1 of a broken precondition. - fplotlib re-exports status_t, STATUS_OK and ERROR_IO. - io_message looks for the quoted file name, so a short name cannot match by accident. - A tiny fps and data near the largest double no longer overflow. - put_path's helpers are private, and the renderer documents that the *_impl bindings are for backends only.
The third review found real arguments the scripted checks did not know about, each of which silently drew nothing when NaN: scatter's s, quiver's scale and width, bar's width, add_circle's radius, text's and tick_params' rotation, linthresh, zorder and others. tools/gen_arg_checks.py now classifies every real argument of every public procedure in one table (alpha, width or size, positive, finite, margin, or data that may be missing) and writes the checks; it fails on an argument it does not classify, and a new CI job fails when src/fplotlib.f90 is out of date with it. Values matplotlib takes stay valid: negative bar widths, rectangle sizes, subplot spacing and text box pads. Every stop message now names its call. text with a negative bbox_pad stopped in the renderer; the box now shrinks as in matplotlib and is not drawn once it is smaller than nothing. Crashes the review found that main has too: - The PNG rasterizer converted unbounded pixel positions to integers, so a bar far above ylim, a fill reaching far outside the view or a huge line width segfaulted. A subpath reaching further than 1e8 px is now clipped to the canvas before it is scanned (Sutherland and Hodgman, which keeps every pixel's winding), and the remaining conversions are clamped. Nothing within 1e8 px changes. - hist2d overflowed on data spanning more than the largest double. - The free functions secondary_xaxis and secondary_yaxis passed cur_i as the parent, which add_secondary then moved to the new axes, making it its own parent and the layout recurse until the stack ran out. A PNG renderer kept as pixels now encodes them on request instead of stopping in bytes, and savefig and add_frame check the pixel count themselves. test_contract checks for exit code 1 exactly and four more broken calls; test_missing checks the PDF page too and adds seven plots.
The fourth review found that finite data far outside the view still broke output. Numbers past about 1e17 overflowed the F24.6 field into asterisks in SVG, PDF and EPS, so plot([0,1],[0,1e30]) under a ylim, a common sight with fill values, wrote files no reader takes; and the PNG backend cut a dashed line into dashes along its whole length before any clipping, so a dashed line to 1e7 under a ylim ran out of memory. Both are on main too. - The plotting layer's put_* routines now clip geometry reaching outside a box ten canvases wide around the canvas: filled contours as polygons (Sutherland and Hodgman), strokes segment by segment (Liang and Barsky), rectangles by intersection; a circle reaching out becomes a fine polygon, markers and text out of the box are dropped and a marker larger than the box is drawn as its path. Geometry inside the box is untouched. - Crossings are found from the end of a segment nearer the box, and a segment with both ends far is halved until one is near, so even a line from -1e300 to 1e300 is drawn exactly where it crosses the view. - PNG dashing walks only the visible piece of each segment and moves the pattern along over the rest. - fmt_num clamps to 1e15, so no value can ever be written as asterisks. The only output that changes is hist_orient's log-scale bars, 129507 pt tall, which SVG, PDF and EPS now cut at the box; the picture is the same. The argument table: the generator's cleanup removed the size check inside check_dashes_arg, so NaN dashes stopped with a paint message; it now matches only generated calls. Array arguments must be classified too, as data or otherwise. Error bars must not be negative, as matplotlib requires, though a missing one is still left out. zorder and the set_fontsize sizes are per procedure; eventplot's linelength and spy's precision may be negative. savefig checks pad_inches and stops when a negative pad leaves nothing of the figure. test_missing fails on asterisks in any vector output and adds nine far-off plots; test_contract adds three broken calls.
The fifth review found: - Dashed PNG lines lost their join at a corner next to a segment that leaves the canvas, because the dash under way was ended at both ends of such a segment even where the clip did not cut it. - A closed outline with a far corner lost the join at its start, its closing edge turned into a separate line. - put_image was not clipped, so an image reaching far past the view was misplaced in the vector formats by the 1e15 clamp in fmt_num. - The tests could not tell whether anything was clipped at all. The renderer contract now bounds every coordinate, size and width by MAX_COORD, 1e15 points, the most a plain decimal in any of the formats holds; beyond it a call stops like any other broken precondition. The plotting layer clips long before: images are cut to the columns and rows in the clip box, each partly covered one drawn on its own so that nothing in view moves; line widths and dashes are capped at 1e12 points, where they still cover everything; text is dropped only when it is anchored outside the box or a trillion points large, so large text draws. Curves crossing the box are flattened adaptively, to a twentieth of a point. A closed stroked contour that is cut starts at a cut, so the stroke runs on through its own start; PNG dashing ends a dash only where the clip cuts it. Splitting far edges keeps only the points that matter, which took a 20000-point fill of alternating 1e300 values from 620 MB to almost nothing. A dash pattern shorter than half a pixel is stroked solid rather than walked forever. savefig with a negative pad_inches past the middle of the drawing keeps a point of it instead of stopping, since the caller cannot know the drawn extent beforehand. A file that cannot be written now names the call in its message. The tick code and the Adler-32 checksum no longer overflow default integers (both flagged by UBSan). test_missing renders every case into a renderer that records how far out anything is drawn and fails past 1e5 points; with the clipping disabled it stops. Four more cases: a far image, a far closed outline, a pad cropping past the middle and text larger than the canvas.
The sixth review found: - With a stroke wider than about twice the clip margin, the edges that clipping adds to a filled and stroked shape came into view: a pie wedge with a 20000 pt edge, zoomed in, turned solid black where main drew it right. The clip box is now widened by what the stroke reaches past its line (half its width, more at a mitred corner), and a far path is filled and stroked apart, the fill clipped as a polygon and the stroke as lines. - A figure of 1e13 inches, or pad_inches of 1e14 or -1e307, pushed the canvas or the clip box past MAX_COORD, so far data stopped. figsize and pad_inches are now at most 1e9 inches, checked where they come in, and the clip box is capped. - A closed stroked contour that clipping did not cut at all, only flatten, lost its CLOSE; it now keeps it. Also from the review: a dashed line cut by the clip carries its pattern on across the cut, each piece drawn with the dash offset where it begins along the whole line, and the PNG backend honours dash_offset; a butt-cap pattern too fine to walk is drawn at its share of cover instead of solid; streamplot's density is at most 100, beyond which its cell grid runs to gigabytes. tools/gen_arg_checks.py now classifies integer arguments too: a count of bins, columns, ticks or grid cells is at least 1, and decimals and mincnt are not negative, as matplotlib requires. hist(bins=0) and the like stop instead of drawing nothing. test_missing's extent check scales with the canvas and the stroke, and adds three cases (a stroke wider than the margin, a hundred-million-inch figure, a dashed line leaving the view); test_contract adds three.
The seventh review found: - A dashed line far wider than the canvas walked every dash across the stroke-widened clip box: plot to 1e300 with lw=1e6 and 0.3 pt dashes took 18 s in PNG, lw=1e8 never finished. For a pen wider than the canvas, dashes are now walked only where their place along the line falls within the canvas's span along it, a cap's length beyond; nowhere else can one touch the canvas. Round or square ends that close every gap draw the line solid. Every width now takes a fifth of a second, and a 1500 pt dashed pen is byte for byte main's picture. - With bbox_inches="tight", decorations placed absurdly far out (labelpad=1e20) took the canvas past MAX_COORD and stopped in the renderer. The tight window now keeps to a billion inches about the figure, and a PNG whose cropped canvas has too many pixels stops in savefig's name. Also from the review: - tools/gen_arg_checks.py checks the methods of type(axes) too, under the name of the call they stand for: ax%secondary_xaxis(scale=nan) stopped only in its free form. Generated blocks now start with a marker line, and only marked blocks are ever rewritten. - Counts are at most a million, the side of a 2D grid of cells (hexbin's gridsize, hist2d's bins) at most a thousand, and decimals at most 17, where larger values ran out of memory or wrote asterisks; spy's m and n are counts; streamplot's density is at most 10. - PNG honours a negative dash_offset, taken modulo the pattern in points so that equal phases give identical pictures. - test_missing's extent bound follows the clip box closely instead of allowing 1e5 points of slack; test_contract checks a method and decimals.
The eighth review found that two of the last commit's PNG dash shortcuts changed what can be seen: - Narrowing a wide pen's dash walk to the canvas's span along the line dropped the join at a vertex just off the canvas, which a pen wider than the canvas still reaches into: a dashed stroke whose one dash covered the whole path drew half the ink of the solid stroke. The walk stays narrowed, but wherever the pattern is on at a vertex it skips past, a capless stub a millionth of a pixel long on either side carries the join there. That stroke is now pixel for pixel the solid one, and plot(..., linestyle="--", lw=2000) is main's picture to within 1 in eight channel values. - Round ends were taken to close every gap, as square ends do, so dots came out as a bar. Only square ends now make a dashed line solid outright; round ends only once their scallops are shallower than a twentieth of a pixel. - From an earlier commit: the box a dash must reach into ignored the spike of a mitred corner. It now reaches miter_limit half widths. stroke_run takes optional bare ends, so that a run stopped by the walk rather than by its dash gets no cap. test_missing checks both shortcuts against the strokes they stand for, and fails without the join stubs. Also: a grid of more than 10000 axes stops in subplots before m*n can overflow, and subplot compares i with m*n in reals; spy's m and n only set axis limits and accept any value; fplotlib_status.md says the PNG pixel limit stops savefig whatever its status.
The ninth review found three ways the PNG dash shortcuts still changed what is drawn: - The square- and round-end shortcut, which drew a dashed line solid when its ends closed the gaps, is not exact where a line starts or ends in a gap, or where a gap straddles a corner. It is gone. For a pen wider than the canvas the walk keeps to the canvas's span along the line, and with round or square ends takes in one whole pattern more on each side: of the dashes beyond, only the nearest can reach in, its end covering all a further one could. A run that begins where the walk does, mid dash, gets no cap there. - Widening the box a dash must reach into by the mitre limit brought the hang back for a large miter_limit (33 s and 20 GB at 1e10 on a straight line). The box is the canvas widened by the pen and a square end's corner; joins and mitre spikes come from the stubs at every point the walk passes with a dash on, wherever that point is. - The join stub, a fixed millionth of a pixel, vanished where a double's step is coarser, from about 1.7e10 pixels out, so a huge dashed pen lost its join. Its length now grows with the coordinate. The one shortcut left is a pattern finer than half a pixel, drawn at the cover it gives. test_missing now draws every end, join and dash offset twice, on a canvas narrower than the pen, where the shortcuts apply, and on a larger one over the same place, where they do not, and the two must agree pixel for pixel; and a trillion-point pen round a corner forty billion points off must draw its solid stroke. Without the window's extension, or with the fixed stub, the test fails. Also: subplot and subplots each stop in their own name on a grid of more than 10000 axes, and figure's num is at most 100000, since every number up to it gets a slot.
The tenth review found that for a pen wider than the canvas with round or square ends, a segment ending more than a pattern short of the canvas lost its last dash: the window took in one pattern beyond the canvas's span, but the canvas lay past the segment's end, so the window was empty while the last dash's end reached a pen's width into the canvas, which stayed blank. The extra pattern is now counted from the canvas or from the segment's own end, whichever is nearer. Sweeping the test over where a line ends or turns away found one more difference: a join stub was added at a vertex where a dash only starts, which draws a mitre the full walk does not. A stub is added only where a dash runs through the vertex, as the walk itself decides. test_missing sweeps every end over nine places where a line ends or turns away, from just short of the canvas to past a pen's reach, and compares each with the full walk; with the old window it fails. fplotlib_status.md lists every upper bound in one table: the renderer's MAX_COORD, figsize and pad_inches, figure numbers, axes in a grid, counts, grid sides, decimals, streamplot density, dash lengths and PNG pixels.
The eleventh review compared 20000 random strokes against a build with every shortcut off and found: - A dash of no length at the start of a segment the walk resumes in was skipped: dash_advance(0) stepped past it. Moving nowhere now changes nothing, so round-capped dots of no length stay. - The argument that only the nearest dash beyond the canvas can reach in holds for the union of the shapes, but the rasterizer sums coverage, so where round or square ends overlap, dashes left out changed the edge pixels they share. The walk is now narrowed to the canvas's span only for butt ends, whose dashes never overlap; round and square ends are walked in full within the box around the canvas. Only where that would take more than two million dashes, a pen some hundred thousand pixels across with gaps a ten-thousandth of it, is the solid band their ends make drawn instead. - plot kept four dash lengths though the check and the documentation allow MAX_DASH, eight; a series now keeps all of them. Two rasterizer bugs that main has too, found by the same comparison: - The walk stepped to t0 + (tb - t0), which can round short of tb and add a point a rounding step on, in no particular direction, drawing a stray join. It now lands on tb. - acc_edge clamped the two ends of a piece of edge crossing the left or right side of the canvas, tilting it and spreading its coverage along the row, so that what lay outside the canvas changed pixels inside. The piece is now cut at the side. No test picture changes. fplotlib_raster has a full_walk switch for tests, which walks every dash in full. test_missing draws 400 strokes made up from a fixed seed, every end and join, mitre limits, dashes of no length, offsets, pens up to nine canvases wide and corners seven canvases off, both ways, and they must agree; and a line of dots of no length. Run at 20000 strokes, none differs. The test fails without the zero-advance fix, and with round and square ends narrowed. Also: subplots_adjust's fractions and colorbar's fraction, pad and shrink are at most 1000 in size, and colorbar's aspect is from 0.001 to 1000, where larger ones stopped in the renderer; the limits table lists them.
The twelfth review found that walking round and square dash ends in full was right but unbounded, and that the solid band standing in for it past two million dashes was not right: - The band put a cap where a line ends in a gap, and a mitre where a corner falls in one: half a 100 pixel canvas painted that the full walk leaves white. - A pen 1.8 million pixels wide with half-pixel dashes took 9 s and 6.4 GB on one segment, and ran out of memory on ten. Dashes with round or square ends overlap one another, and the rasterizer sums overlapping coverage, so none of those reaching the canvas can be left out; only their number can be bounded. The renderer contract now takes a pen with round or square dash ends at most MAX_PEN_PER_DASH, 100, times its dash pattern, which keeps the dashes within the box to a few hundred more than the canvas holds; past it, a call stops. The band is gone, and the walk is exact for every stroke but a pattern finer than half a pixel. The plotting layer never draws such a pen: its dashes have butt ends. Following the rule that a failure the caller cannot foresee is returned, not stopped on: a PNG cropped with bbox_inches="tight" takes its size from the drawing, so one with more pixels than the encoder can count is now returned by savefig as the new ERROR_SIZE, or stops with exit code 2 without a status, as an unwritable file does. figure_window computes the cropped window for savefig and render_figure alike. test_missing keeps its random strokes within the limit, and checks that a label a million points off makes savefig return ERROR_SIZE; test_contract checks the pen limit. The limits table and the status documentation say both.
The thirteenth review found: - render_png with bbox_inches="tight" still stopped with exit code 1 on a crop too large, the run-time failure savefig had just learned to return, and its caller had no way to check first. render_svg, render_pdf, render_eps and render_png now take an optional status: render_png returns ERROR_SIZE with an empty result, or without a status stops with exit code 2; the vector formats are always ok. savefig passes its status through instead of working out the crop first, so the window is found once and a constrained layout's warning printed once. - dash_plan took a pattern of an odd number of lengths for half its real length, which repeats only after going round twice, and drew a 0.36 point pattern solid where it is 0.72 points long and walked. Also from the review: the PNG size limit is now MAX_PNG_PIXELS, a hundred million pixels, some 4 GB as rasterized, rather than what the encoder can count, which a crop under it could still exhaust memory with; the status documentation lists the sub-pixel dash approximation, the one thing the PNG backend draws approximately, says that MAX_PEN_PER_DASH binds every format, and names ERROR_SIZE among the re-exports. test_contract checks each case's exit status, now 2 for a tight PNG too large without a status; test_missing checks render_png's status and the single-length pattern, and fails without the doubling.
The fourteenth review found the size of a PNG checked three ways that rounded differently, in savefig's precondition, in render_figure and in the backend, so the same figure near the limit stopped with exit 1, came back as ERROR_SIZE or stopped with exit 2 depending on the call: a whole figure too large came back from render_png as a "cropped figure" too large, and a figure just under the limit in savefig could stop in the backend with a message naming no call. png_pixels in fplotlib_backend_png now counts the pixels as open_canvas sizes the canvas, rounding included, and every check uses it. render_figure returns ERROR_SIZE only for a tight crop; a whole figure too large, which its size and dpi tell beforehand, stops in the call's name. Also from the review: - The cover of a dash pattern finer than half a pixel counted half the ends for an odd number of lengths. - The random stroke test now asks for exact agreement with the full walk, as it found. - fplotlib re-exports MAX_COORD, MAX_DASH, MAX_PEN_PER_DASH and MAX_PNG_PIXELS, the limits the documentation tells callers to keep to. - render_png takes an optional dpi, so it need not rely on the figure's. - The README says render_* return a status too. test_contract checks render_png on a whole figure too large; test_missing checks that png_pixels counts the canvases open_canvas makes.
The fifteenth review found: - savefig still checked the whole figure's pixels before a tight crop, so a crop that fits stopped with exit 1 where render_png saved it, and one that did not stopped where render_png returned ERROR_SIZE. savefig now checks the whole figure only when it is not cropped, and leaves a crop to render_png. - multiple_ticks counted multiples of the base in default integers, so Unix times in half-second steps overflowed and the ticks vanished. The count is now kept in reals. The same review turned up more of the same kind on main, fixed here: the comma and percent formatters, which wrote garbage past two billion; the date ticks, which took the floor of a date over a step in an integer; and the calendar, now kept within a billion days. An animation reel counted its bytes in default integers and crashed past two gigabytes; add_frame now stops in its name at MAX_REEL_BYTES, a billion. Also: fplotlib re-exports only the limits a plotting call can reach (MAX_DASH, MAX_PNG_PIXELS, MAX_REEL_BYTES), the renderer's own staying in fplotlib_render; render_png takes dpi before status; and the documentation says that the PNG dash shortcuts agree with the full walk up to the rounding of the pattern's place along a very long segment. test_missing checks the far ticks and formatters, which main gets wrong, and that a tight crop of a figure too large for a whole PNG saves.
The sixteenth review found: - Clamping the day number in num_date left the time of day worked out from the value unclamped, which overflowed: a date axis past a billion days drew every label as **:**, and dates main labelled right, up to 2.1 billion days, came out bunched and wrong. The time of day now comes from the fraction of the value, and the day is clamped at 2.1 billion, where the calendar's integer arithmetic stops, as main's range was. - MAX_REEL_BYTES, a billion, did not keep the APNG encoder within its output buffer, which grows to 2**30 bytes, since deflate with fixed Huffman codes can grow data by 9/8. It is now 8e8. Also: the comma and percent formatters with fixed decimals write exponent form where the field would overflow into asterisks; multiple_ticks stops where the next multiple of the base rounds to the same number; status_t's message is a fixed-length string, blank when the status is ok, as in stdlib's state_type, so it is always defined; the dash checks in test_missing ask for exact agreement, as their comment says; the dpi comment sits on render_png. test_missing checks the date fraction two billion days out and past the calendar, and a formatter's fixed decimals past its field.
The seventeenth review found that MAX_REEL_BYTES, counted on the frames' raw bytes, still let save_animation overflow the encoder's buffer: a PNG adds a filter byte a row and each frame its own chunks, so 37037 frames a pixel wide and 7200 high, under 8e8 raw bytes, encoded past 2**30 and the buffer's doubling overflowed a default integer. add_frame now counts each frame as it encodes at worst, h(3w + 1)*9/8 + 1024 bytes: a filter byte and three of colour a row, deflated with fixed Huffman codes into at most nine bits a byte, and the frame's own chunks; a GIF, at a palette index a pixel packed into codes of at most twelve bits and a palette a frame, takes less. The frames together stay within MAX_REEL_BYTES, now 1e9, below 2**30, so no buffer grows past what a default integer counts. The review's probe at the bound, 29918 such frames of noise, saves an 898 MB APNG; one frame more stops in add_frame's name, saying how many frames of that size fit. status_t loses its public set binding: the module procedure set_status records a failure, and fplotlib does not export it, so that the type a caller sees only reads. MESSAGE_LEN, the length of status%message, is exported and documented.
The eighteenth review found: - hexbin stopped on finite data: its margins overflowed into xlim, which stopped in xlim's name, and data spanning more than the largest double binned through nint(NaN). hexbin now works out what would overflow from half values, and its grid, hexagons and margins stop at the largest double. - add_circle passed twice its radius to add_ellipse, which stopped in its own name on a radius the table accepts. Both now share one polygon routine that takes the semi-axes. The review noted that plots of finite data spanning more than the largest double drew empty axes. The axis transform and the autoscale margin now work out such a range from half values, and the limits stop at the largest double, so a line, a mesh or a hexbin across the whole range of a double draws; pcolormesh's outer cell edges stop there too. Each change applies only where the old arithmetic overflowed, so every other picture is unchanged to the byte. A shape whose own place on the canvas lies past the largest double still cannot be placed, and is left out as missing data is; the documentation says so. pad_inches is checked, finite and at most 1e9 inches, in the name of savefig and of each render_* function, cropped or not: a new generator kind, pad, and its helper check_pad_arg. figure_window no longer checks it in savefig's name for every caller. test_missing draws hexbin, pcolormesh and plot across the whole range, and the circle, 79 cases; test_contract checks render_svg's pad_inches, 34 cases.
The nineteenth review found that GCC's -fsanitize=undefined leaves out float-cast-overflow, which is where the undefined behaviour left in the library was. Under it, the tests, the review's 80 probe cases and the 40-case sweep across the whole range of a double reported eight sites; all are fixed, and the same runs now report none: - The tick locator took floor of the log of a range past the largest double, which fe586d4 had made reachable from ordinary autoscaled plots. linear_ticks now takes the ticks of half such a range, doubled, and scale_range, tick_decimals and tick_offset take the log of a span through log10_span, which works from half values; scale_range's mean is halved before it is added. - hexbin with every point at the lowest double stepped below it, to -Inf, and binned through nint(NaN). step_apart moves the ends apart inward. - contour_levels took floor(zmin/step) in a default integer, so contourf of data near 1e9 in steps of 0.1 drew nothing and labelled its colorbar -214748364.8, as main does; the floor is now kept in reals. level_step took the log of an infinite step, and every contour took its levels from minval and maxval of data with infinities in it: the levels now come from the finite values, through data_levels, and a range past the largest double is stepped from half of it. - fill_factor took ceiling of a missing or huge extent; it is bounded first. - The EPS BoundingBox overflowed a default integer for a figure wider than 2**31 points, within the documented figsize limit; it is written in 64-bit integers. - An aspect ratio over limits further apart than the largest double made the axes box NaN, and the axes vanished; the spans are halved together and grow_about_centre stops at the largest double. A new CI job, Sanitizers (GFortran), runs the tests under AddressSanitizer and UndefinedBehaviorSanitizer with float-cast-overflow, stopping at the first report. test_missing draws hexbin at the lowest double, an image across the whole range and contours of offset data, 82 cases; checks that the EPS BoundingBox of every case is a box; and checks contour levels of data near 1e9, which main gets wrong. The pad_inches row of the limits table names render_*, and figure_window's comment is back above it.
The twentieth review found: - contour_levels clamped each level but not the lowest round one, which past -huge was -Inf, so contours over the whole range of a double, or of data near -huge, came out as -huge and NaN levels. Each level is now its own count of steps from zero there, clamped. - On a log axis the autoscale margin of data up to 1e300 went to +Inf, and the ticks took floor(log10(Inf)): an empty plot, as on main. A margin past the largest double now stops at it, and on a log axis the low end stays positive. The log minor ticks skip an infinite end. - A text rotation past 1e15 stopped in the renderer's name, not the call's. put_glyphs takes an angle of more than a turn modulo 360. Pictures the same review turned up as wrong, also on main: - log_ticks ticked every decade up to MAX_TICKS, so a log axis of 300 decades had all its labels in a heap at the bottom. Past MAX_TICKS decades it now ticks about nine, on multiples of a stride, as matplotlib's LogLocator does, and draws no minors; an axis of fewer decades is ticked as before. - A colorbar over limits further apart than the largest double put its ticks in a heap: lin_frac now works out the place of a value from half values there, for the colorbar, the norms, scatter colours and tripcolor. - A tick label past F20.4, as on a colorbar of 3e20, was asterisks. It, and the comma and percent formatters' fallbacks, are now written by sci_str, as 1.2e308: Fortran's ES form drops the E of a three-digit exponent. test_missing adds the log axis to 1e300, contourf over the whole range and near -huge with colorbars, text turned 1e16 degrees and a colorbar of 3e20 (87 cases), and checks log_ticks over 300 decades and an exponent label directly. The tests, the review's probes and the earlier sweeps report no undefined behaviour under float-cast-overflow.
The twenty-first review found that format_tick_to trimmed the trailing zeros of a label after sci_str had written it, taking them off the exponent: 2.5e20 was labelled 2.5e2 and 1.2e300 1.2e3, wrong numbers where main had shown asterisks. The exponent form is now returned as sci_str writes it, and test_missing reads back the labels of six far values, exponents ending in zero among them, as the values they label. Also from the review: the log minor ticks counted decades one way and log_ticks another, so an axis of 31.5 decades had thinned majors and every minor. Both now ask log_stride. log_ticks stops at a decade past the largest double instead of returning it as an infinite tick.
The twenty-second review found: - tick_locator with data near the lowest double: vmin/base overflowed, so the only tick was -Inf and tick_offset took floor(log10(Inf)). multiple_ticks now gives no ticks for data past the largest double in steps of base, and tick_offset skips an infinite one. - scale_range took any range narrower than 1e-12 of its size as ticked in steps of one, so nanosecond times, 1e6 wide at 1.7e18, had MAX_TICKS labels in a heap at the low end of the axis (on main, two garbage end ticks from an overflowing floor). As in matplotlib, only a range a few ulps wide is widened, by 1e-13 of its size, as nonsingular does, and every other range is ticked across. - A percentage past the largest double was labelled 0%: sci_str wrote the infinity as 0. Such a percentage is now worked out in logs by sci_ratio, which shares its form with sci_str through sci_join. Also from the review: the rules of a formula turned by the raw angle while its glyphs turned by the reduced one; the angle is now reduced once where the text comes in. A log axis raised its low end to the least normal double, past subnormal data; it now keeps the data's own end. A log tick below 1e-30 was labelled 0, as on main; it is a decade like any other, and is labelled as one. test_missing draws the three cases (90 in all) and checks the ticks of the narrow range, the overflowing percentage and a log tick of 1e-69 directly.
The twenty-third review found that 9088613's subnormal change did nothing: scale_fwd clamped every value to the least normal double before taking its log, so the data's own low end never reached expand_limits, subnormal points were drawn on the bottom spine, and a decade below 1e-308 was labelled 0, since 10**expn with an integer exponent there underflows to zero. scale_fwd now takes the log of any positive value, subnormal included, and clamps only non-positive ones, where they always were; is_decade tests a decade below the least normal double against 10**expn taken in reals, to within its own spacing, as a subnormal has fewer digits. Every other picture is unchanged. sci_ratio takes its sign from the signs of its arguments rather than from their product, which can underflow to zero. test_missing draws subnormal data on a log axis (91 cases) and checks the labels of decades from 1e-309 to 1e-323.
The twenty-fourth review found that 2f90c59's subnormal log axis broke more than it mended. Positive subnormals took their own log while zero and negative values stayed at the least normal double, above them, so bars and fills on a subnormal axis hung upside down from 2.2e-308. And is_decade allowed two spacing()s, but spacing() of any value below about 2e-292 is tiny itself, so every value below 1e-307 passed as a decade, and 3e-308 was labelled 10^-308. A log axis ends again where main ends it, at the least normal double: every value below it, subnormal, zero or negative, is drawn there, and autoscaling, the margin and log_ticks stop there too. The documentation says so. is_decade allows twice the subnormal spacing, tiny*epsilon, rather than spacing(). Also from the review: a constant series at or above 1.8e307 on a log axis took a decade up past the largest double, an infinite limit; it takes a decade down instead. test_missing draws subnormal bars on a log axis and the constant series (93 cases), checks that values near and below the least normal double that are no decade are not labelled as one, and that the constant series has finite limits.
The twenty-fifth review found: - xlim, ylim and zlim widened equal limits by 5% when they were set, so equal limits above 1.71e308 were stored as +Inf: no ticks, and get_ylim returned an infinity that ylim then refused. - The same rule took limits below 1e6*tiny as -0.05 to 0.05 whatever the scale, so ylim(1e-303, 1e-302) on a log axis gave an axis from tiny to 0.05; main stored them as given. - symlog took log10(a/linthresh), which overflows for a small linthresh, and linthresh*linscale could overflow too: empty plots and infinite limits (main segfaulted). The limits are now stored as given and widened when the figure is drawn, by nonsingular_limits, under the scale the axis has then, as matplotlib's locators widen them: on a linear axis as before, stopping at the largest double; on a log axis, equal limits a decade each way. symlog takes the difference of the logs where the ratio overflows, and the argument table bounds linthresh to 1e-300..1e300 and linscale to at most 1e6, new kinds thresh and linscale, so that its linear part is normal and its transformed axis finite; the limits table says so. expand_limits measured "nothing" in absolute units, which on a symlog axis of linthresh 1e-200 made a margin of the whole range of a double; it now scales that by linthresh. linear_ticks drops a tick a step past the largest double, which its end filter, itself overflowing, let through. test_missing draws the four cases (97 in all) and checks that equal huge limits stay finite, that hand-set log limits near tiny are kept, and the symlog margin; test_contract checks the linthresh bound (35).
The twenty-sixth review found that a48d101 made symlog's forward map safe but not its inverse: scale_inv took linthresh*10**(|u|/linthresh - adj), and the power overflows wherever a value over linthresh is past the largest double, which the new linthresh bound allows. Data from 1 to 1e10 with linthresh 1e-300 autoscaled up to 1.8e308, as did the new test's case, whose check looked only at the low end. Where the power overflows, the product is now taken in logs; the test checks both ends. Also from the review: - A constant series on a symlog axis got a margin of one transformed unit, which shrinks with linthresh: limits of +-1.8e308 at linthresh 1e-10, and none at all below about 5e-294, where the threshold that stood for nothing underflowed (on main, infinities). A symlog axis now widens such data in data space before its margin, as matplotlib's locators do, by nonsingular_limits; a constant 5 gets 4.73 to 5.28 whatever linthresh is. Linear and log axes are unchanged. - linscale had no lower bound, so a linscale of 1e-320 made the linear part of the axis subnormal. It is now bounded to 1e-6..1e6. - nonsingular_limits on a log axis could turn equal subnormal limits backwards; the upper one is now a decade above both. - make_scale's own checks, which the generated ones made unreachable, are gone; the comment on user_limits and the PR description are brought up to date. test_missing checks a constant series on a symlog axis at four thresholds, from 1e-300 to 1.
The twenty-seventh review found that 7bb8061 widened only symlog data exactly constant, or within 1e-15 of it: a series a few ulps apart, which the transform rounds to one value, still took a margin of one transformed unit, which is 1/linthresh decades, and autoscaled to +-1.8e308 (1 to 1+5 ulps at linthresh 1e-10; 1e300 to 1e300*(1+5e-14) at 1e-3). The absolute threshold that stood for nothing also underflowed below a linthresh of about 5e-294. On a symlog axis a span is now nothing when it is within eight ulps of its own ends in transformed units; such data is widened in data space by widen_apart, 5% of its size each way, sticky ends staying, and the margin is taken on that. Linear and log axes keep main's arithmetic, and every picture is unchanged. test_missing checks four near-constant series, from exactly constant to 5e-14 apart at 1e300, at four thresholds from 1e-300 to 1.
The twenty-eighth review found that 3064298's eight-ulp test used spacing(), which the standard has return tiny for any value below about 2e-292, where the true ulp would be subnormal: gfortran and flang do, LFortran does not. On a symlog axis of linthresh up to about 1e-295 every transformed value is that small, so the test became an absolute one, and data the axis could resolve, 1e-7 apart at 1e300 at linthresh 1e-300, was widened into a flat line on gfortran but not on LFortran. The test, now unresolved(), takes eight epsilons of the larger of the two places, which is relative all the way down and the same on every compiler. One rule now serves symlog everywhere: autoscaling applies it before the margin, so margins(0) and axis("tight") widen too, and nonsingular_limits applies it to hand-set limits, in place of the linear 1e-15 rule. Linear and log axes are unchanged. test_missing checks that data the axis can resolve at linthresh 1e-300 is not widened, that hand-set symlog limits it cannot part are, and a constant series on symlog with no margin.
The twenty-ninth review found that unresolved() took eight epsilons of the transformed places, which is eight roundings only while those are normal: once they are subnormal a rounding is the least subnormal, and data a few such steps apart, as [1, 2, 3, 4, 5]*5e-324 on a symlog axis, counted as resolved, was not widened, and was drawn bent where the transform rounds it to whole steps. The test now has a floor of epsilon*tiny, the least subnormal on every compiler. Also from the review: the test of a symlog axis with no margin used a constant series, which the commit before already widened; it now uses a near-constant one at 1e300, the case 83ad4b0 newly handles. The comments of the symlog tests are back with their tests, and the comment on user_limits says that the limits are stored as given and widened when drawn. test_missing checks that subnormal data on symlog is widened.
The thirtieth review, which found no blockers, suggested documenting next to the affine limit that log and symlog axes resolve data to about epsilon times the transformed value, not the value: near-constant data past a few roundings is drawn as finely as those roundings allow.
This was referenced Nov 22, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Second of three stacked PRs that take the API refactoring out of #68. #82 is merged; this PR is based on
main.math_context_t(merged)status_tThere are now two kinds of failure.
A call that breaks a documented precondition stops the program. Examples are
plot(alpha=1.5),figure(figsize=[nan, 2.0_dp]), drawing beforeopen_canvas, a nonfinite coordinate reaching a renderer, an alpha outside [0,1], an unknown fill rule, cap or join, a path whose verbs need more points than it has, anend_groupwithout abegin_group,bytesbeforeclose_canvas,savefigof an unknown format andxlimwith an infinite limit. Each of these is a bug in the calling code, and no caller could do anything with an error except stop.contract_errorinfplotlib_statuswritesfplotlib: <rule>to stderr and stops with exit code 1. Every stop in the plotting API goes through it. The plotting procedures check their own arguments on entry, so the message names the call that was given the bad value, such asfplotlib: plot: alpha must be in [0, 1], got 1.5, rather than whatever part of the drawing first tripped over it.tools/gen_arg_checks.pyclassifies every real and integer argument of every public procedure andtype(axes)method in one table, and writes the checks:linthreshfrom 1e-300 to 1e300, andlinscalefrom 1e-6 to 1e6;The script fails on an argument it doesn't know, and a new CI job fails if
src/fplotlib.f90is out of date with it. Values matplotlib takes stay valid: negative bar widths, rectangle sizes, subplot spacing and text box pads. A negative line width, marker size or font size, which matplotlib quietly accepts, now stops. That is a deliberate choice.A failure that a correct program can still meet is returned. Here that means an output file that cannot be opened, written or closed (
ERROR_IO), or a PNG cropped withbbox_inches="tight"to more pixels than the encoder can count (ERROR_SIZE); the caller can't know the cropped size beforehand. A whole figure too large for a PNG is known beforehand from its size and dpi, so it stops. One function,png_pixels, counts a PNG's pixels for every check, rounding included.fplotlib_io:write_bytes(filename, data, status)returns it through a requiredstatus_tfromfplotlib_status.savefig,save_animation,showand therender_*functions take an optionalstatus, andfplotlibre-exportsstatus_t. Itsmessageis a string ofMESSAGE_LENcharacters, blank when nothing failed, as in stdlib'sstate_type; a caller only reads it, sinceset_statusis internal. With astatus, the failure is returned. Without one,savefigandsave_animationstop with the message and exit code 2, as the exception does in matplotlib, andshowonly reports it. Layout failures will use the same mechanism when the typesetter comes.Missing data is not a broken precondition. A NaN or an infinity in plotted data is left out of the picture, as in matplotlib. Every renderer call of the plotting layer goes through
put_path,put_rect,put_circle,put_markers,put_glyphsandput_imageinfplotlib_artist: a path is broken where a vertex is missing, and a shape, marker, label or image placed at a missing point is not drawn. On main most plot types passed NaN straight to the backends, which wrotenaninto SVG, PDF and EPS and sometimes crashed in PNG.The renderer contract
The checks live in
renderer_t, once for every backend. Its public methods (open_canvas,draw_path, ...,end_group, andbytesonencoded_renderer_t) arenon_overridable: each checks the call, keeps the canvas state (open, finished, group depth) and then calls the backend's deferred*_implmethod. A backend implements only the*_implmethods and may assume every call is valid, so no two backends can disagree about a check. Every coordinate, size and width must be finite and withinMAX_COORD(1e15 points), the most a plain decimal in any of the formats holds. A call that draws nothing (a path without verbs, markers at no points, an empty glyph run) returns before reaching the backend.Other changes:
renderer_tis the drawing contract alone.encoded_renderer_textends it withbytesfor SVG, PNG, PDF and EPS, so a target that only draws doesn't need to invent a file format.FAMILY_*is gone. Every backend drew the one built-in sans regardless of the family.draw_imagetakesrgba(:, :, :), so that its shape can be checked.The PDF backend's image and transparency tables grow. On main it silently dropped every image after the 16th and every alpha value after the 64th.
hist2dandhexbinskip points with a missing coordinate,streamplotends a line where the field is missing, andpiedraws a missing value as an empty wedge. All four crashed on NaN on main;piewrote past its arrays.The 3D limits and
scatter3d's depth shading skip missing values, and a range made of nothing but missing data, such as the colorbar of an all-NaN image, has no ticks.tight_layouton a figure too small for its decorations keeps the old layout, with matplotlib's warning, instead of giving the axes a negative size. An axes or a colorbar that the layout leaves no room for is not drawn.histskips missing values instead of taking its range from them.piestops on a negative value, as matplotlib raises.Data far outside the view. Two problems, both on main too:
ylim, a fill reaching far outside the view, a long dashed line or a huge line width segfaulted or ran out of memory.****.The
put_*routines now clip geometry to a box ten canvases wide around the canvas, widened by what a stroke reaches past its line:PNG dashing walks only the visible part of each segment. For butt ends on a pen wider than the canvas, it walks only the part within the canvas's span along the line. Butt dashes never overlap, so leaving the others out changes no pixel, and a capless stub carries the join at every vertex skipped while a dash is on. Round and square ends overlap, and this rasterizer sums overlapping coverage, so they are walked in full within the box around the canvas. The renderer contract bounds that work: a pen with round or square dash ends may be at most
MAX_PEN_PER_DASH(100) times its dash pattern. The plotting layer's dashes have butt ends. The one approximation is a pattern finer than half a pixel, where no dash can be told apart.fplotlib_rasterhas a test-onlyfull_walkswitch. The test draws 400 strokes from a fixed seed both ways, and they must agree. Run at 20,000 strokes, none differs.The rasterizer also no longer adds a stray join where the walk rounds short of a segment's end, and it cuts an edge at the canvas side instead of clamping its ends. Both bugs are on main too; no test picture changes.
The free functions
secondary_xaxisandsecondary_yaxismade the new axes its own parent and recursed until the stack ran out, on main too.hist2doverflowed on data spanning more than the largest double.A PNG renderer kept as pixels for an animation now encodes them when asked for
bytes.Every upper bound is listed in one table in the
fplotlib_statusdocs.figsizeandpad_inchesare at most 1e9 inches, the tight window keeps to a billion inches about the figure, andstreamplot's density is at most 10, which keeps the canvas and the work bounded.Tick positions, the comma and percent formatters and date ticks no longer overflow a default integer for values past two billion, such as Unix times; they did on main. An animation stops in
add_frameonce its frames, each counted as it encodes at worst, would passMAX_REEL_BYTES(1e9, below the encoders' 2^30-byte buffers), instead of crashing.Limits too narrow to tell their ends apart, set by
xlim,ylimorzlim, are widened when the figure is drawn, by the scale the axis then has, as matplotlib'snonsingulardoes, instead of being divided by. On a symlog axis, whose units shrink withlinthresh, autoscaled data the axis cannot tell apart is widened the same way, margin or none.add_framestops when a frame's size differs from the first. Before, it printed a warning and dropped the frame.save_animationwith no frames or an unknown format also stops now instead of printing and returning.Font sizes must be finite and nonnegative everywhere. Size zero sets text with no extent.
file_extandwrite_bytesmove from the facade tofplotlib_io, andlowermoves tofplotlib_style.No other signature changes.
text_width,math_widthandmath_layoutstay as they are on main.Tests
Every test picture is byte-identical to
main, with one exception. Inhist_orient, the log-scale bars are 129,507 pt tall; the SVG, PDF and EPS now cut them at the clip box, and the picture is unchanged. Tests pass with gfortran, gfortran-O3 -march=native, flang 22, flang 22-O3 -march=nativeand LFortran 0.66, and with gfortran under AddressSanitizer and UBSan withfloat-cast-overflow, which GCC's-fsanitize=undefinedleaves out. A new CI job, Sanitizers (GFortran), runs the tests that way and fails on the first report.tests/test_missing.f90renders 97 plots with NaN, infinite or far-off values in all four formats, and also into a renderer that records how far out anything is drawn, failing past the clip box. With the clipping disabled, it stops. Four of them contain nothing but missing data, and two have layouts that leave no room for the axes. It checks that none of them stops, that no NaN, infinity or overflowed number reaches the SVG, the EPS or the PDF page, and that the EPS BoundingBox is a box.tests/test_contract.f90checks 35 broken calls, across all four backends and the plotting API. A program can't catcherror stop, sotest_plotsruns itself again once per case, astest_plots contract k, and checks that each run exits with code 1 and the expected message on stderr.An automated
ERROR_IOtest is left out. LFortran 0.66, the version inpixi.toml, returnsiostat=0when it opens a file in a missing directory or a directory itself. That test will come with the separate PR that moves pixi and CI to LFortran 0.69.