Skip to content

Add to support number autofill with Ordinary Least Squares#85

Merged
hackerwins merged 4 commits into
mainfrom
feat-number-autofill
Mar 27, 2026
Merged

Add to support number autofill with Ordinary Least Squares#85
hackerwins merged 4 commits into
mainfrom
feat-number-autofill

Conversation

@ggyuchive

@ggyuchive ggyuchive commented Mar 26, 2026

Copy link
Copy Markdown
Member

Summary

Autofill number using Ordinary Least Squares(OLS) trend.

OLS result is formatted with toPrecision(15) (IEEE 754 double, matching Excel/Google
Sheets). To avoid intermediate float error (e.g. m * t + b where b = -7/3),
computeLinearTrend computes the result as a single fraction:

y(t) = (n * A * t + sumY * D - A * sumX) / (n * D)

e.g. Autofill with selecting 2x2 blocks below.

1	1
2	5
  |
  v
1	1
2	5
3	9
4	13
5	17
6	21
7	25
8	29

e.g. Autofill with selecting 3x2 blocks below.

1	1
2	5
5	10
  |
  v
1	1
2	5
5	10
6.66666666666667	14.3333333333333
8.66666666666667	18.8333333333333
10.6666666666667	23.3333333333333
12.6666666666667	27.8333333333333
14.6666666666667	32.3333333333333

Why

Previously, it just autofill number repeatedly like string.

e.g. Autofill with selecting 2x2 blocks below.

1	1
2	5
  |
  v
1	1
2	5
1	1
2	5
1	1
2	5
1	1
2	5

Linked Issues

Fixes #

Verification

CI automatically posts a verification summary comment on this PR with
per-lane results for both verify:self and verify:integration.

  • verify:self — CI comment shows ✅
  • verify:integration — CI comment shows ✅ (or explicit skip reason below)

Skip reason (if applicable):

Risk Assessment

  • User-facing risk:
  • Data/security risk:
  • Rollback plan:

Notes for Reviewers

  • UI changes (screenshots/gifs if applicable):
  • Follow-up work (if any):

Summary by CodeRabbit

  • New Features

    • Autofill now extrapolates numeric sequences using linear-trend prediction; mixed or non-numeric inputs still use the previous tiling behavior.
  • Bug Fixes / Precision

    • Improved numeric extrapolation rounding to deterministic 15-significant-digit results to reduce precision drift.
  • Tests

    • Added comprehensive tests for numeric extrapolation, fallbacks, and precision edge cases.
  • Refactor

    • Internal editor and rendering code cleaned up with no user-facing API changes.

@coderabbitai

coderabbitai Bot commented Mar 26, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 9727f9fa-6f52-4f32-b875-fafc133b00f9

📥 Commits

Reviewing files that changed from the base of the PR and between 4a39c42 and d5df1ee.

📒 Files selected for processing (9)
  • docs/tasks/active/20260326-number-autofill-ols-todo.md
  • packages/docs/src/view/doc-canvas.ts
  • packages/docs/src/view/text-editor.ts
  • packages/docs/src/view/word-boundary.ts
  • packages/docs/test/view/incremental-layout.test.ts
  • packages/docs/test/view/pagination.test.ts
  • packages/docs/test/view/peer-cursor.test.ts
  • packages/docs/test/view/visual-line.test.ts
  • packages/sheets/src/model/worksheet/clipboard.ts
✅ Files skipped from review due to trivial changes (2)
  • packages/docs/test/view/incremental-layout.test.ts
  • docs/tasks/active/20260326-number-autofill-ols-todo.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/sheets/src/model/worksheet/clipboard.ts

📝 Walkthrough

Walkthrough

Adds Google Sheets–style OLS linear-trend extrapolation for numeric autofill, helper utilities for numeric detection and regression, integrates predictions into Sheet.autofill() with tiling fallbacks, and introduces comprehensive tests and a spec document covering precision and implementation tasks.

Changes

Cohort / File(s) Summary
Specification
docs/tasks/active/20260326-number-autofill-ols-todo.md
New spec describing numeric autofill behavior: single-cell copy, OLS extrapolation for 2+ numeric cells, axis mapping, mixed-content fallback, deterministic 15-significant-digit formatting, and implementation checklist.
Regression Helpers
packages/sheets/src/model/worksheet/clipboard.ts
Added computeLinearTrend(xs, ys, targetX) implementing OLS via aggregated sums (returns mean when D===0, undefined for insufficient points) and isNumericValue(v) to detect finite numeric inputs; both exported.
Autofill Engine
packages/sheets/src/model/worksheet/sheet.ts
Sheet.autofill() now pre-scans lines using isNumericValue, builds per-line trend metadata, applies computeLinearTrend predictions (formatted with toPrecision(15)) to eligible destination cells while preserving style, and retains legacy tiling/formula relocation as fallback.
Tests
packages/sheets/test/sheet/autofill.test.ts
Updated vertical test expectations; added horizontal extrapolation, noisy-data OLS checks, mixed-content and formula fallback tests, precision regression test, and a dedicated computeLinearTrend test suite covering edge cases and exact/approximate behavior.
Docs View Adjustments
packages/docs/src/view/doc-canvas.ts
Removed unused lineX parameter from renderListMarker call and signature; simplified coordinate passing.
TextEditor ctor shape
packages/docs/src/view/text-editor.ts
Replaced constructor parameter properties with explicit private fields and assignments; no behavior changes.
Word-boundary runtime enum
packages/docs/src/view/word-boundary.ts
Replaced const enum with runtime as const object and derived union type; preserves API.
Test fixtures / cleanup
packages/docs/test/view/...
Multiple test updates: added explicit textIndent/marginLeft to mock styles, removed unused imports/type-only imports, and applied default block styles in visual-line tests.

Sequence Diagram

sequenceDiagram
    participant User
    participant Autofill as Autofill Service
    participant Scanner as isNumericValue()
    participant TrendBuilder as Trend Builder
    participant Extrapolator as computeLinearTrend()
    participant Sheet as Sheet Model

    User->>Autofill: request autofill(target)
    Autofill->>Scanner: scan source range for numeric cells
    Scanner-->>Autofill: numeric map per cell
    Autofill->>TrendBuilder: build per-line (col/row) trend metadata
    TrendBuilder-->>Autofill: eligible trend lines

    loop for each destination cell
        alt line eligible for OLS
            Autofill->>Extrapolator: computeLinearTrend(xs, ys, targetX)
            Extrapolator-->>Autofill: predicted value
            Autofill->>Sheet: format (toPrecision(15)) & write value, preserve style
        else fallback
            Autofill->>Sheet: apply legacy tiling / cloneCellForAutofill
        end
    end

    Autofill-->>User: complete
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 I nibble numbers, slope and seed,
I trace the line where values lead,
Two points whisper, many sing—
OLS hops in, predictions spring.
Precision trimmed to fifteen bright,
My spreadsheet carrots gleam just right.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main feature: implementing numeric autofill with Ordinary Least Squares (OLS). It directly captures the primary change across the changeset.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat-number-autofill

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Mar 26, 2026

Copy link
Copy Markdown
Contributor

Verification: verify:self

Result: ✅ PASS in 104.0s

Lane Status Duration
sheets:build ✅ pass 13.5s
docs:build ✅ pass 5.6s
verify:fast ✅ pass 48.0s
frontend:build ✅ pass 14.6s
verify:frontend:chunks ✅ pass 0.3s
backend:build ✅ pass 4.3s
cli:build ✅ pass 1.8s
verify:entropy ✅ pass 15.8s

Verification: verify:integration

Result: ✅ PASS

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
docs/tasks/active/20260326-number-autofill-ols-todo.md (1)

40-40: Clarify the status of the remaining precision drift investigation.

This task item is still unchecked. Is this a known remaining issue that needs follow-up, or can it be closed? If there are known precision drift scenarios, consider documenting them or opening a tracking issue.

Would you like me to help identify any remaining precision edge cases that might cause drift?

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@docs/tasks/active/20260326-number-autofill-ols-todo.md` at line 40, Update
the todo line "Investigate and fix remaining precision drift" to reflect the
current state: if the investigation is complete, remove the checkbox and replace
with a short resolution note; if unresolved, change to an actionable item that
references a tracking issue (create one) and list known edge-case scenarios
(e.g., float rounding in X/Y operations or conversion between units) in the task
description; ensure the updated text includes either a link to the tracking
issue or a short summary of remaining steps so the task is no longer ambiguous.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/tasks/active/20260326-number-autofill-ols-todo.md`:
- Around line 25-27: The fenced code block containing the formula "y(t) = (n * A
* t + sumY * D - A * sumX) / (n * D)" needs a language specifier to satisfy
markdownlint MD040; update the triple-backtick fence to include a language such
as text or math (e.g., ```text or ```math) so the block is properly annotated.

In `@packages/sheets/src/model/worksheet/clipboard.ts`:
- Around line 100-106: The computeLinearTrend function should validate that xs
and ys have the same length before proceeding: check that xs.length ===
ys.length (in addition to the existing n < 2 check) and handle mismatches by
returning undefined or throwing an Error per project convention; update the
function (computeLinearTrend) to early-return/throw when lengths differ so
subsequent indexing over xs/ys cannot read past the shorter array and produce
NaN results.

---

Nitpick comments:
In `@docs/tasks/active/20260326-number-autofill-ols-todo.md`:
- Line 40: Update the todo line "Investigate and fix remaining precision drift"
to reflect the current state: if the investigation is complete, remove the
checkbox and replace with a short resolution note; if unresolved, change to an
actionable item that references a tracking issue (create one) and list known
edge-case scenarios (e.g., float rounding in X/Y operations or conversion
between units) in the task description; ensure the updated text includes either
a link to the tracking issue or a short summary of remaining steps so the task
is no longer ambiguous.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4521470a-9ec5-4c60-b733-2d80d66902f6

📥 Commits

Reviewing files that changed from the base of the PR and between a9356f8 and 4a39c42.

📒 Files selected for processing (4)
  • docs/tasks/active/20260326-number-autofill-ols-todo.md
  • packages/sheets/src/model/worksheet/clipboard.ts
  • packages/sheets/src/model/worksheet/sheet.ts
  • packages/sheets/test/sheet/autofill.test.ts

Comment thread docs/tasks/active/20260326-number-autofill-ols-todo.md Outdated
Comment thread packages/sheets/src/model/worksheet/clipboard.ts Outdated
hackerwins and others added 3 commits March 27, 2026 09:50
- Add language specifier to fenced code block in task doc
- Add xs/ys length mismatch guard in computeLinearTrend

Co-Authored-By: Claude Opus 4.6 <[email protected]>
TypeScript parameter properties and const enums are not supported
in Node's --experimental-strip-types. Refactor TextEditor constructor
to use explicit field declarations and replace const enum with
an object literal.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Remove unused lineX parameter from renderListMarker, remove unused
imports, and add missing textIndent/marginLeft fields to BlockStyle
test fixtures.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@hackerwins
hackerwins merged commit 96613c4 into main Mar 27, 2026
3 checks passed
@hackerwins
hackerwins deleted the feat-number-autofill branch March 27, 2026 03:52
hackerwins added a commit that referenced this pull request Mar 27, 2026
Task completed and merged via PR #85. Move to archive and update
task indexes.

Co-Authored-By: Claude Opus 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants