This is an automated email from the ASF dual-hosted git repository.

SpriCoder pushed a commit to branch fs/inner-view
in repository https://gitbox.apache.org/repos/asf/iotdb.git

commit d9ed8046dd7559a778130ed3e28541dd17841ff1
Author: spricoder <[email protected]>
AuthorDate: Fri Nov 20 17:45:23 2026 +0800

    [FS] fold windows/reduce/gaps/sessions/extreme into stats modes
    
    Reuse the existing stats command for all analytic capabilities instead of 
separate
    commands: inline window grids (--origin/--width/--step/--unit/--timezone), 
reduction
    (delta/elapsed_ms/rate_per_ms aggregates, --group-by entity|pooled, 
--sort-by/--order),
    --gaps, --group-by session --gap-ms, and --aggregates argmin|argmax --by. 
The engines
    are unchanged; the parser maps stats parameters onto them and rejects the 
old command
    names. Update help, i18n, tests and the TQTS adapter/tool schema 
accordingly.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 benchmark/tqtsbench/README.md                      |  10 +
 benchmark/tqtsbench/fs-discovery-tools.mjs         |  45 ++--
 benchmark/tqtsbench/fs_tool_runner.py              | 188 ++++++++++------
 benchmark/tqtsbench/test_fs_pilot.py               |  55 +++--
 .../org/apache/iotdb/cli/i18n/FsHelpMessages.java  |   9 +-
 .../apache/iotdb/cli/i18n/FsWindowMessages.java    |   4 -
 .../org/apache/iotdb/cli/i18n/FsHelpMessages.java  |   9 +-
 .../apache/iotdb/cli/i18n/FsWindowMessages.java    |   4 -
 .../org/apache/iotdb/cli/fs/FilesystemShell.java   |   9 +-
 .../iotdb/cli/fs/command/FilesystemCommand.java    |   1 -
 .../cli/fs/command/FilesystemCommandHelp.java      |  54 +----
 .../cli/fs/command/FilesystemCommandParser.java    | 250 ++++++++++++++-------
 .../apache/iotdb/cli/fs/command/WindowGrid.java    |   1 -
 .../fs/command/FilesystemCommandParserTest.java    |  80 +++++--
 .../iotdb/cli/fs/provider/FsReductionTest.java     |  32 +--
 15 files changed, 459 insertions(+), 292 deletions(-)

diff --git a/benchmark/tqtsbench/README.md b/benchmark/tqtsbench/README.md
index 87c1e942305..23081cbf06d 100644
--- a/benchmark/tqtsbench/README.md
+++ b/benchmark/tqtsbench/README.md
@@ -261,6 +261,16 @@ active source. Window origins/timezones, entity/pooled 
reduction, ranking and
 endpoint differences remain supported. The independent `--final-table` 
evaluation
 option is retained; existing experiment results and scoring contracts are 
unchanged.
 
+Since 2026-11-20 the analytic capabilities are modes of the existing `stats` 
command
+instead of separate commands, following the rule of reusing existing 
Unix-style commands and
+extending parameters: `--origin/--width/--step/--unit/--timezone` expand a 
window grid inline;
+`--aggregates delta|elapsed_ms|rate_per_ms`, `--group-by entity|pooled` or 
`--sort-by` select
+reduction; `--gaps` selects gap analysis; `--group-by session --gap-ms` 
selects sessions; and
+`--aggregates argmin|argmax --by FIELD` selects the extreme row. The former 
`windows`, `reduce`,
+`gaps`, `sessions` and `extreme` command names are rejected. The adapter 
exposes the same modes
+as `stats` parameters under the unchanged feature gates. Historical runs keep 
their frozen CLI
+and adapter.
+
 Frame source is archived at 
`.tmp/fs-grid-reduce-rollback-20261119/pre-rollback-source.tar.gz`;
 [FS_FRAME_PROTOCOL.md](FS_FRAME_PROTOCOL.md) and its validation report 
describe the
 historical implementation, not the currently deployed command surface.
diff --git a/benchmark/tqtsbench/fs-discovery-tools.mjs 
b/benchmark/tqtsbench/fs-discovery-tools.mjs
index 2625c609334..ea94832c923 100644
--- a/benchmark/tqtsbench/fs-discovery-tools.mjs
+++ b/benchmark/tqtsbench/fs-discovery-tools.mjs
@@ -23,7 +23,10 @@ export async function apply(ctx, config) {
   const { defineTool } = await import(config.toolsModule);
   const features = new Set(config.features ?? []);
   const temporal = features.has('temporal'), extreme = 
features.has('extreme'), grid = features.has('grid'), reduce = 
features.has('reduce');
-  const commands = 
['help','ls','find','tree','schema','meta','stats','count','cat','head','tail','stat','file','grep','cut','paste','join','wc',
 ...(temporal ? ['gaps','sessions'] : []), ...(extreme ? ['extreme'] : []), 
...(grid ? ['windows'] : []), ...(reduce ? ['reduce'] : [])];
+  const commands = 
['help','ls','find','tree','schema','meta','stats','count','cat','head','tail','stat','file','grep','cut','paste','join','wc'];
+  const analytic = temporal || extreme || reduce;
+  const aggregates = 
['count','min','max','sum','avg','median','first','last','min_time','max_time','null_count',
 ...(reduce ? ['delta','elapsed_ms','rate_per_ms'] : []), ...(extreme ? 
['argmin','argmax'] : [])];
+  const groupings = [...(reduce ? ['entity','pooled'] : []), ...(temporal ? 
['session'] : [])];
   let calls = 0;
   for (const kind of ['context', 'fs']) {
     ctx.tools.register(defineTool({
@@ -33,32 +36,32 @@ export async function apply(ctx, config) {
         : 'Retrieve original benchmark public dataset documentation on demand. 
This contains field meanings, units, device mappings, time conventions and 
dialect notes, never questions or answers. Results are scalar entries with 
JSON-pointer paths. Start with query or pointer=/database; use a returned 
parent pointer to inspect a related record. query is a case-insensitive literal 
substring; empty query matches all. Follow next_offset with identical 
query/pointer.',
       parameters: kind === 'fs' ? {
         command: { type: 'string', enum: commands, required: true, 
description: 'Native read-only FS operation. Call help for the complete 
parameter and return contract.' },
-        ...((temporal || extreme || reduce) ? { field: { type: 'string', 
description: 'Required target measurement for enabled analysis commands. See 
help for entity, boundary and NULL semantics.' } } : {}),
-        ...(temporal ? { gap_ms: { type: 'integer', description: 'sessions 
only: positive threshold; split iff gap > threshold.' } } : {}),
-        ...(extreme ? { mode: { type: 'string', enum: ['min','max'], 
description: 'extreme only: direction, ties choose earliest time.' } } : {}),
+        ...(temporal ? {
+          gaps: { type: 'boolean', description: 'stats mode: true computes 
complete successive non-null observation gaps of the single measurement; see 
help.' },
+          gap_ms: { type: 'integer', description: 'stats with group_by=session 
only: positive threshold; split iff gap > threshold.' },
+        } : {}),
+        ...(groupings.length ? { group_by: { type: 'string', enum: groupings, 
description: 'stats mode: ' + [reduce ? 'entity (default) or pooled reduction 
grain' : '', temporal ? 'session segments by gap_ms' : 
''].filter(Boolean).join('; ') + '. See help.' } } : {}),
+        ...(extreme ? { by: { type: 'string', description: 'stats with 
aggregates [argmin] or [argmax] only: target measurement; ties choose earliest 
time.' } } : {}),
+        ...(reduce ? {
+          sort_by: { type: 'string', description: 'stats reduction mode: 
selected aggregate used for global ordering of result rows AFTER grouping, 
before paging.' },
+          order: { type: 'string', enum: ['asc','desc'], description: 'sort 
direction, default desc; requires sort_by; NULL last.' },
+        } : {}),
         ...(grid ? {
-          origin: { type: 'string', description: 'windows or reduce grid: 
epoch-ms string or ISO datetime, interpreted with explicit timezone for local 
time; required with width and start_ms/end_ms.' },
+          origin: { type: 'string', description: 'stats grid: epoch-ms string 
or ISO datetime, interpreted with explicit timezone for local time; required 
with width and start_ms/end_ms.' },
           width: { type: 'integer', description: 'Positive grid width in unit; 
explicit windows are mutually exclusive.' },
           step: { type: 'integer', description: 'Positive grid stride, 
defaults to width; supports overlapping or gapped windows.' },
           unit: { type: 'string', enum: ['ms','day','month'], description: 
'Fixed milliseconds vs origin-anchored calendar days/months. Default ms.' },
         } : {}),
-        ...((grid || reduce) ? { timezone: { type: 'string', description: 
'windows/reduce: IANA timezone default UTC. Labels epoch bounds; calendar grids 
use local arithmetic. Ambiguous/nonexistent boundaries rejected.' } } : {}),
-        ...(reduce ? {
-          metrics: { type: 'array', items: { type: 'string', enum: 
['count','sum','avg','min','max','first','last','delta','elapsed_ms','rate_per_ms']
 }, description: 'reduce only: default count,first,last,delta; first/last 
non-null endpoints, rate uses actual physical elapsed milliseconds.' },
-          group_by: { type: 'string', enum: ['entity','pooled'], description: 
'reduce only: default entity, separate device/window groups; pooled explicitly 
combines observations by window before aggregation.' },
-          rank_by: { type: 'string', description: 'reduce only: selected 
metric used for global ordering of result rows AFTER grouping.' },
-          order: { type: 'string', enum: ['asc','desc'], description: 'reduce 
rank direction, default desc; requires rank_by; NULL last.' },
-          top: { type: 'integer', description: 'reduce only: keep first 
1..65536 ranked rows before paging; requires rank_by.' },
-        } : {}),
-        path: { type: 'string', description: 'Not used for windows. Absolute 
virtual path inside assigned /root/database. Default assigned root. No local 
paths or .csv suffix for Tree model.' },
+        ...((grid || reduce) ? { timezone: { type: 'string', description: 
'stats: IANA timezone default UTC for grids; in reduction mode it also labels 
epoch bounds. Ambiguous/nonexistent boundaries rejected.' } } : {}),
+        path: { type: 'string', description: 'Absolute virtual path inside 
assigned /root/database. Default assigned root. No local paths or .csv suffix 
for Tree model.' },
         paths: { type: 'array', items: { type: 'string' }, description: 'For 
paste (2..8) or join (exactly 2) only; absolute virtual paths.' },
-        measurements: { type: 'array', items: { type: 'string' }, description: 
'Field identifiers, 1..64; schema/count/stats/cat/head' + (extreme ? '/extreme 
(associated fields)' : '') + '. Omit for native defaults.' },
-        start_ms: { type: 'integer', description: 'Inclusive epoch-ms lower 
bound; stats/cat/head' + (temporal || extreme ? ' and enabled analysis 
commands; see help.' : ' only.') },
-        end_ms: { type: 'integer', description: 'Inclusive epoch-ms upper 
bound; stats/cat/head' + (temporal || extreme ? ' and enabled analysis 
commands; see help.' : ' only.') },
-        limit: { type: 'integer', description: 'cat/head/tail page size 
1..2000; defaults 200/200/10.' + (temporal || extreme ? ' Also output-row page 
size for enabled analysis commands, default200.' : '') },
-        offset: { type: 'integer', description: 'cat/head row offset >=0; 
follow next_offset with identical filters.' + (temporal || extreme ? ' Also 
output-row offset for enabled analysis commands.' : '') },
-        aggregates: { type: 'array', items: { type: 'string', enum: 
['count','min','max','sum','avg','median','first','last','min_time','max_time','null_count']
 }, description: 'stats only; omit for all native statistics including 
first/last and timeline min_time/max_time.' },
-        windows: { type: 'array', items: { type: 'object', properties: { 
start_ms: { type: 'integer', required: true }, end_ms: { type: 'integer', 
required: true } }, additionalProperties: false }, description: 'stats' + 
(temporal ? '/gaps' : '') + (extreme ? '/extreme' : '') + (reduce ? '/reduce' : 
'') + ': 1..256 inclusive epoch-ms windows, mutually exclusive with top-level 
start_ms/end_ms. One scan per device; output includes window_index/start/end. 
Overlap and duplicates allowed.' },
+        measurements: { type: 'array', items: { type: 'string' }, description: 
'Field identifiers, 1..64; schema/count/stats/cat/head. Analytic stats modes 
take exactly one target here' + (extreme ? ' (argmin/argmax: associated fields 
instead)' : '') + '. Omit for native defaults.' },
+        start_ms: { type: 'integer', description: 'Inclusive epoch-ms lower 
bound; stats/cat/head only.' },
+        end_ms: { type: 'integer', description: 'Inclusive epoch-ms upper 
bound; stats/cat/head only.' },
+        limit: { type: 'integer', description: 'cat/head/tail page size 
1..2000; defaults 200/200/10.' + (analytic ? ' Also output-row page size for 
analytic stats modes, default 200.' : '') },
+        offset: { type: 'integer', description: 'cat/head row offset >=0; 
follow next_offset with identical filters.' + (analytic ? ' Also output-row 
offset for analytic stats modes.' : '') },
+        aggregates: { type: 'array', items: { type: 'string', enum: aggregates 
}, description: 'stats only; omit for all native statistics including 
first/last and timeline min_time/max_time.' + (analytic ? ' Some values select 
an analytic mode; see help.' : '') },
+        windows: { type: 'array', items: { type: 'object', properties: { 
start_ms: { type: 'integer', required: true }, end_ms: { type: 'integer', 
required: true } }, additionalProperties: false }, description: 'stats (all 
modes except group_by=session): 1..256 inclusive epoch-ms windows, mutually 
exclusive with top-level start_ms/end_ms. One scan per device; output includes 
window_index/start/end. Overlap and duplicates allowed.' },
         max_depth: { type: 'integer', description: 'find/tree recursion depth 
1..12, defaults 6/3.' },
         pattern: { type: 'string', description: 'find filename glob or grep 
regular expression; up to 256 chars, no command separators or quotes.' },
         type: { type: 'string', enum: ['f','d'], description: 'find object 
kind filter only.' },
diff --git a/benchmark/tqtsbench/fs_tool_runner.py 
b/benchmark/tqtsbench/fs_tool_runner.py
index 9cb5fac310b..6778cb9b6b4 100644
--- a/benchmark/tqtsbench/fs_tool_runner.py
+++ b/benchmark/tqtsbench/fs_tool_runner.py
@@ -33,14 +33,41 @@ from tool_runner import context_page
 COMMANDS = ("help", "ls", "find", "tree", "schema", "meta", "stats", "count", 
"cat", "head", "tail", "stat", "file", "grep", "cut", "paste", "join", "wc")
 AGGREGATES = ("count", "min", "max", "sum", "avg", "median", "first", "last", 
"min_time", "max_time", "null_count")
 READ = {"cat", "head"}
-TEMPORAL = {"gaps", "sessions", "extreme"}
-ANALYTIC = {"windows", "reduce"}
 METRICS = ("count", "sum", "avg", "min", "max", "first", "last", "delta", 
"elapsed_ms", "rate_per_ms")
+REDUCTION_ONLY = {"delta", "elapsed_ms", "rate_per_ms"}
+EXTREMA = ("argmin", "argmax")
 GRID_ARGS = {"origin", "width", "step", "unit", "timezone"}
-PAGED = READ | TEMPORAL | ANALYTIC
+# Analytic capabilities are modes of the native stats command, gated by 
feature.
+MODE_FEATURE = {"gaps": "temporal", "sessions": "temporal", "extreme": 
"extreme", "reduce": "reduce"}
+
 
 def enabled_commands(features):
-    return set(COMMANDS) | ({"gaps", "sessions"} if "temporal" in features 
else set()) | ({"extreme"} if "extreme" in features else set()) | ({"windows"} 
if "grid" in features else set()) | ({"reduce"} if "reduce" in features else 
set())
+    return set(COMMANDS)
+
+
+def stats_mode(args):
+    aggregates = args.get("aggregates")
+    aggregates = aggregates if isinstance(aggregates, list) else []
+    group = args.get("group_by")
+    if "gaps" in args and args["gaps"] is not True:
+        raise ValueError("gaps must be true when given")
+    modes = []
+    if args.get("gaps") is True:
+        modes.append("gaps")
+    if group == "session":
+        modes.append("sessions")
+    if any(a in EXTREMA for a in aggregates):
+        modes.append("extreme")
+    if (group is not None and group != "session") or "sort_by" in args or 
any(a in REDUCTION_ONLY for a in aggregates):
+        modes.append("reduce")
+    if len(modes) > 1:
+        raise ValueError("gaps, group_by=session, argmin/argmax and reduction 
parameters are exclusive")
+    return modes[0] if modes else "plain"
+
+
+def is_paged(args):
+    command = args.get("command")
+    return command in READ or (command == "stats" and stats_mode(args) != 
"plain")
 
 
 def integer(value, name, low, high):
@@ -87,19 +114,26 @@ def help_text(scope, features=()):
     }
 
 
-    result["commands"]["stats"] += " Statistics remain separate per 
object/entity and window; cross-entity ranking is not pooled averaging. 
Preserve object and window keys when combining results."
+    stats = result["commands"]["stats"]
+    stats += " Statistics remain separate per object/entity and window; 
cross-entity ranking is not pooled averaging. Preserve object and window keys 
when combining results."
+    modes = []
+    if "grid" in features:
+        stats += " Window grid: origin (epoch-ms string or ISO local/offset 
datetime) with positive width, optional step (default width), unit=ms|day|month 
(default ms) and timezone (IANA, default UTC) expands required inclusive 
start_ms/end_ms into explicit windows, at most 256; ms is fixed duration, 
day/month is calendar arithmetic anchored at origin; starts lie inside the 
range, the last end is clipped to end_ms, no left partial window. Excludes 
explicit windows."
+    if "reduce" in features:
+        modes.append("reduction")
+        stats += " Reduction mode (selected by any of aggregates 
delta/elapsed_ms/rate_per_ms, group_by=entity|pooled or sort_by): exactly one 
numeric measurement; aggregates subset of 
count,sum,avg,min,max,first,last,delta,elapsed_ms,rate_per_ms (default 
count,first,last,delta). group_by=entity (default) keeps device/window rows; 
pooled merges raw observations per window, sample-weighted mean, never mean of 
entity means. delta=last-first at non-null physical-time endpoints; 
elapsed_ms=l [...]
     if "temporal" in features:
-        result["commands"]["gaps"] = "Complete non-null successive gaps: 
required path and field; optional start_ms/end_ms OR windows, limit=1..2000 
(default200), offset>=0. Inclusive windows are assigned by LATER observation 
time; the actual preceding non-null observation may be outside the window. 
Return distinct first/last/min/max gap samples (earliest tied min/max), 
observed_at, previous_at, exact decimal gap_ms, selected_as; deduplicate by 
entity/window/observed_at. Full scan, never [...]
-        result["commands"]["sessions"] = "Complete sessionization: required 
path, numeric field and positive gap_ms. Consecutive non-null target 
observations split ONLY when their gap > gap_ms; equality stays in session. 
Optional inclusive start_ms/end_ms filters BEFORE segmentation (clipped 
sessions, indices restart at0); windows not allowed. Per-device 
session_index/start/end,count,avg,first,last. Never pool devices. limit/offset 
paginate output sessions with next_offset. Null target v [...]
+        modes.append("gaps/sessions")
+        stats += " gaps=true: exactly one measurement; complete non-null 
successive gaps, optional start_ms/end_ms OR windows; inclusive windows are 
assigned by LATER observation time and the real preceding observation may be 
outside the window. Returns distinct first/last/min/max gap samples (earliest 
tied min/max), observed_at, previous_at, exact decimal gap_ms, selected_as; 
full scan, never sampled; each device independent; empty/no-gap windows have no 
row."
+        stats += " group_by=session with positive gap_ms: exactly one numeric 
measurement; consecutive non-null observations split ONLY when their gap > 
gap_ms; optional inclusive start_ms/end_ms filter BEFORE segmentation (clipped 
sessions, indices restart at 0); windows not allowed. Per-device 
session_index/start/end,count,avg,first,last; never pools devices."
     if "extreme" in features:
-        result["commands"]["extreme"] = "Associated extreme row: required 
path, numeric field and mode=min|max; optional measurements of associated 
fields, inclusive start_ms/end_ms OR windows, limit/offset. Independently per 
device/window; ties choose earliest time. Skip null comparison values, retain 
null associated values, reject non-finite comparison values. Return object, 
group_scope=entity, field, window keys, observed_at, extreme_value and 
value.<field> (target always included). N [...]
-    if "grid" in features:
-        result["commands"]["windows"] = "Generate explicit window grid, no 
data read. Required inclusive start_ms/end_ms, origin (epoch-ms string or ISO 
local/offset datetime), positive width; step defaults to width; 
unit=ms|day|month default ms; timezone=IANA name default UTC. ms is fixed 
duration; day/month is calendar arithmetic anchored at origin. Select starts 
inside range, clip ends to end_ms; no left partial window from outside. Return 
nominal half-open bounds, effective inclusive [...]
+        modes.append("argmin/argmax")
+        stats += " aggregates=[argmin] or [argmax] with by=<numeric 
measurement>: the earliest row where that measurement is minimal/maximal, 
independently per device/window; optional measurements list associated fields 
(NULL retained); optional start_ms/end_ms OR windows. Returns observed_at, 
extreme_value and value.<field>; empty windows have no row; no pooling or 
global ranking."
+    if modes:
+        stats += " Only one mode per call (" + ", ".join(modes) + "); modes 
stream raw observations in the CLI and page OUTPUT rows with limit=1..2000 
(default 200) and offset, returning next_offset."
+    result["commands"]["stats"] = stats
     if "reduce" in features:
-        result["commands"]["reduce"] = "Native raw-observation reduction: 
explicit path and numeric field; metrics subset of 
count,sum,avg,min,max,first,last,delta,elapsed_ms,rate_per_ms (default 
count,first,last,delta). Optional inclusive start_ms/end_ms OR explicit 
windows. group_by=entity (default) keeps device/window rows; pooled merges raw 
observations per window, sample-weighted mean, never mean of entity means. NULL 
targets skipped, non-finite rejected, empty groups omitted. delta [...]
-        result["scope_note"] = "Only native read-only FS commands enumerated 
here are enabled. reduce explicitly selects entity vs pooled grain and can rank 
result rows; stats remains entity-local. No SQL/shell/local files/writes."
-        if "grid" in features:
-            result["commands"]["reduce"] += " Optional 
origin,width,step,unit,timezone generate the same grid as windows directly, 
requiring start_ms/end_ms and excluding explicit windows; no manual window 
array needed."
+        result["scope_note"] = "Only native read-only FS commands enumerated 
here are enabled. stats reduction mode explicitly selects entity vs pooled 
grain and can rank result rows. No SQL/shell/local files/writes."
     return result
 
 
@@ -109,31 +143,33 @@ def build_command(args, package, features=()):
     cmd = args.get("command")
     if cmd not in enabled_commands(features):
         raise ValueError("Unknown command; use help")
+    mode = stats_mode(args) if cmd == "stats" else None
+    if mode in MODE_FEATURE and MODE_FEATURE[mode] not in features:
+        raise ValueError("This stats mode is not enabled for this arm; use 
help")
+    paged = is_paged(args)
     allowed = {"command"}
-    if cmd not in {"help", "windows"}:
+    if cmd != "help":
         allowed.add("paths" if cmd in {"paste", "join"} else "path")
-    if cmd in READ | {"stats", "schema", "count", "extreme"}:
+    if cmd in READ | {"stats", "schema", "count"}:
         allowed.add("measurements")
-    if cmd in PAGED | {"stats"}:
+    if cmd in READ | {"stats"}:
         allowed |= {"start_ms", "end_ms"}
-    if cmd in PAGED | {"tail"}:
+    if paged or cmd == "tail":
         allowed.add("limit")
-    if cmd in PAGED:
+    if paged:
         allowed.add("offset")
     if cmd == "stats":
         allowed |= {"aggregates", "windows"}
-    if cmd in TEMPORAL | {"reduce"}:
-        allowed.add("field")
-    if cmd in {"gaps", "extreme", "reduce"}:
-        allowed.add("windows")
-    if cmd == "sessions":
-        allowed.add("gap_ms")
-    if cmd == "extreme":
-        allowed.add("mode")
-    if cmd == "windows" or (cmd == "reduce" and "grid" in features):
-        allowed |= GRID_ARGS
-    if cmd == "reduce":
-        allowed |= {"metrics", "group_by", "rank_by", "order", "top", 
"timezone"}
+        if "grid" in features:
+            allowed |= GRID_ARGS
+        if mode == "reduce":
+            allowed |= {"group_by", "sort_by", "order", "timezone"}
+        if mode == "gaps":
+            allowed.add("gaps")
+        if mode == "sessions":
+            allowed |= {"group_by", "gap_ms"}
+        if mode == "extreme":
+            allowed.add("by")
     if cmd in {"find", "grep"}:
         allowed.add("pattern")
     if cmd in {"tree", "find"}:
@@ -156,18 +192,48 @@ def build_command(args, package, features=()):
     else:
         paths = [path_arg(args.get("path", "/root/"+package), package)]
     parts = [cmd]
-    if cmd in TEMPORAL | {"reduce"}:
+    if mode not in (None, "plain"):
         if "path" not in args:
-            raise ValueError("Analysis commands require an explicit path")
-        field = args.get("field")
-        if not isinstance(field, str) or not 
re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", field):
-            raise ValueError("field must be a measurement identifier")
-        parts += ["--field", field]
-    if cmd in ANALYTIC:
-        has_grid = "origin" in args
-        if cmd == "windows" and not has_grid:
-            raise ValueError("windows requires origin, width and 
start_ms/end_ms")
-        if has_grid:
+            raise ValueError("Analysis modes require an explicit path")
+        names = args.get("measurements")
+        if mode == "extreme":
+            by = args.get("by")
+            if not isinstance(by, str) or not 
re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", by):
+                raise ValueError("by must be a measurement identifier")
+            if args.get("aggregates") not in (["argmin"], ["argmax"]):
+                raise ValueError("argmin/argmax must be the only aggregate")
+            parts += ["--by", by, "--aggregates", args["aggregates"][0]]
+        else:
+            if not isinstance(names, list) or len(names) != 1:
+                raise ValueError("This stats mode requires exactly one target 
measurement")
+            if mode == "gaps":
+                if "aggregates" in args:
+                    raise ValueError("gaps takes no aggregates")
+                parts += ["--gaps"]
+            if mode == "sessions":
+                if "windows" in args or "origin" in args:
+                    raise ValueError("sessions take start_ms/end_ms only, not 
windows")
+                if "aggregates" in args:
+                    raise ValueError("sessions take no aggregates")
+                parts += ["--group-by", "session", "--gap-ms", 
str(integer(args.get("gap_ms"), "gap_ms", 1, 2**63-1))]
+            if mode == "reduce":
+                metrics = args.get("aggregates", ["count", "first", "last", 
"delta"])
+                if not isinstance(metrics, list) or not metrics or any(v not 
in METRICS for v in metrics) or len(set(metrics)) != len(metrics):
+                    raise ValueError("aggregates must be distinct supported 
reduction aggregates")
+                parts += ["--aggregates", ",".join(metrics)]
+                if "group_by" in args:
+                    if args["group_by"] not in {"entity", "pooled"}:
+                        raise ValueError("group_by must be entity, pooled or 
session")
+                    parts += ["--group-by", args["group_by"]]
+                if "sort_by" in args:
+                    order = args.get("order", "desc")
+                    if args["sort_by"] not in metrics or order not in {"asc", 
"desc"}:
+                        raise ValueError("sort_by must be a selected 
aggregate; order asc or desc")
+                    parts += ["--sort-by", args["sort_by"], "--order", order]
+                elif "order" in args:
+                    raise ValueError("order requires sort_by")
+    if cmd == "stats":
+        if "origin" in args:
             if not {"start_ms", "end_ms", "width"} <= set(args) or "windows" 
in args:
                 raise ValueError("Grid requires origin,width,start_ms,end_ms 
and excludes windows")
             origin = args["origin"]
@@ -181,28 +247,12 @@ def build_command(args, package, features=()):
         elif any(k in args for k in ["width","step","unit"]):
             raise ValueError("width/step/unit require origin")
         if "timezone" in args:
+            if "origin" not in args and mode != "reduce":
+                raise ValueError("timezone requires origin")
             zone=args["timezone"]
             if not isinstance(zone,str) or len(zone)>100 or not 
re.fullmatch(r"[A-Za-z0-9_/+\-:]+",zone): raise ValueError("timezone must be an 
IANA zone or offset")
             parts += ["--timezone",zone]
-    if cmd == "reduce":
-        metrics=args.get("metrics",["count","first","last","delta"])
-        if not isinstance(metrics,list) or not metrics or any(v not in METRICS 
for v in metrics) or len(set(metrics))!=len(metrics): raise ValueError("metrics 
must be distinct supported reduction metrics")
-        group=args.get("group_by","entity")
-        if group not in {"entity","pooled"}: raise ValueError("group_by must 
be entity or pooled")
-        parts += ["--metrics",",".join(metrics),"--group-by",group]
-        if "rank_by" in args:
-            rank=args["rank_by"]; order=args.get("order","desc")
-            if rank not in metrics or order not in {"asc","desc"}: raise 
ValueError("rank_by must be selected metric; order asc or desc")
-            parts += ["--rank-by",rank,"--order",order]
-            if "top" in args:parts += 
["--top",str(integer(args["top"],"top",1,65536))]
-        elif "top" in args or "order" in args:raise ValueError("top/order 
require rank_by")
-    if cmd == "sessions":
-        parts += ["--gap-ms", str(integer(args.get("gap_ms"), "gap_ms", 1, 
2**63-1))]
-    if cmd == "extreme":
-        if args.get("mode") not in {"min", "max"}:
-            raise ValueError("mode must be min or max")
-        parts += ["--mode", args["mode"]]
-    if cmd in {"schema", "meta", "stats", "count", "cat", "head"} | TEMPORAL | 
ANALYTIC:
+    if cmd in {"schema", "meta", "stats", "count", "cat", "head"}:
         parts += ["-f", "ndjson"]
     elif cmd == "tail":
         parts += ["--format", "ndjson"]
@@ -233,12 +283,12 @@ def build_command(args, package, features=()):
                 raise ValueError("Window end_ms must be >= start_ms")
             ranges.append(f"{start}:{end}")
         parts += ["--windows", ",".join(ranges)]
-    if cmd in PAGED | {"tail"}:
+    if paged or cmd == "tail":
         limit = integer(args.get("limit",10 if cmd=="tail" else 200), 
"limit",1,2000)
-        parts += ["-n", str(limit + (1 if cmd in PAGED else 0))]
-    if cmd in PAGED:
+        parts += ["-n", str(limit + (1 if paged else 0))]
+    if paged:
         parts += ["--offset", 
str(integer(args.get("offset",0),"offset",0,100000000))]
-    if "aggregates" in args:
+    if "aggregates" in args and mode in (None, "plain"):
         values = args["aggregates"]
         if not isinstance(values,list) or not values or any(v not in 
AGGREGATES for v in values):
             raise ValueError("aggregates must be a nonempty subset of " + 
",".join(AGGREGATES))
@@ -269,7 +319,7 @@ def build_command(args, package, features=()):
         parts += 
["-t",",","-1",str(integer(args.get("left_field",1),"left_field",1,10000)),"-2",str(integer(args.get("right_field",1),"right_field",1,10000))]
     if cmd == "wc":
         parts += ["-c"]
-    if cmd not in {"find", "windows"}:
+    if cmd != "find":
         parts += paths
     return " ".join(shlex.quote(p) for p in parts)
 
@@ -331,7 +381,7 @@ def execute(config, request):
                             proc.wait()
                         finally:
                             signal.signal(signal.SIGTERM, previous)
-                page_command = args["command"] in PAGED | {"tail"}
+                page_command = is_paged(args) or args["command"] == "tail"
                 if page_command and (folder/"stdout.txt").stat().st_size > 
8*1024*1024:
                     raise ValueError("Page output exceeds 8 MiB; select fewer 
measurements")
                 with (folder/"stdout.txt").open(errors="replace") as stream:
@@ -341,7 +391,7 @@ def execute(config, request):
                 (folder/"resources.json").write_text(json.dumps(metrics))
                 
error=command_failed(args["command"],proc.returncode,timed_out,stderr)
                 payload={"stdout":raw[:40000],"stderr":"\n".join(line for line 
in stderr.splitlines() if not line.startswith("Picked up 
_JAVA_OPTIONS:"))[:2000],"truncated":len(raw)>40000,"is_error":error,"exit_code":proc.returncode,"timed_out":timed_out}
-                if not error and args["command"] in PAGED | {"tail"}:
+                if not error and page_command:
                     rows=[json.loads(line) for line in raw.splitlines() if 
line.strip()]
                     limit=args.get("limit",10 if args["command"]=="tail" else 
200)
                     selected=rows[:limit]
@@ -352,7 +402,7 @@ def execute(config, request):
                     if args["command"]=="tail" and len(selected)<len(rows):
                         raise ValueError("Tail page exceeds output budget; use 
a smaller limit")
                     offset=args.get("offset",0)
-                    more=args["command"] in PAGED and len(selected)<len(rows)
+                    more=is_paged(args) and len(selected)<len(rows)
                     
payload={"rows":selected,"offset":offset,"returned_rows":len(selected),"has_more":more,"next_offset":offset+len(selected)
 if more else None,"is_error":False}
                 if payload.get("truncated"):
                     payload["continuation"]="Narrow the path or parameters. 
Raw output is retained offline and cannot be opened by the agent."
diff --git a/benchmark/tqtsbench/test_fs_pilot.py 
b/benchmark/tqtsbench/test_fs_pilot.py
index bf3b0a1590e..059382495eb 100644
--- a/benchmark/tqtsbench/test_fs_pilot.py
+++ b/benchmark/tqtsbench/test_fs_pilot.py
@@ -66,29 +66,42 @@ class FsBoundaryTest(unittest.TestCase):
     def test_feature_gates_and_temporal_contracts(self):
         scope = "/root/iotdb_ndbc/station_42001"
         requests = [
-            {"command":"gaps","path":scope,"field":"wspd"},
-            
{"command":"sessions","path":scope,"field":"wspd","gap_ms":14400000},
-            
{"command":"extreme","path":scope,"field":"wspd","mode":"max","measurements":["wtmp"]},
+            
{"command":"stats","path":scope,"measurements":["wspd"],"gaps":True},
+            
{"command":"stats","path":scope,"measurements":["wspd"],"group_by":"session","gap_ms":14400000},
+            
{"command":"stats","path":scope,"by":"wspd","aggregates":["argmax"],"measurements":["wtmp"]},
         ]
         for request in requests:
             with self.assertRaises(ValueError):
                 build_command(request,"iotdb_ndbc")
             
command=build_command({**request,"limit":1,"offset":2},"iotdb_ndbc",["temporal","extreme"])
+            self.assertTrue(command.startswith("stats "))
             self.assertIn("-n 2",command)
             self.assertIn("--offset 2",command)
+        
self.assertIn("--gaps",build_command(requests[0],"iotdb_ndbc",["temporal"]))
+        self.assertIn("--group-by session --gap-ms 
14400000",build_command(requests[1],"iotdb_ndbc",["temporal"]))
+        self.assertIn("--by wspd --aggregates 
argmax",build_command(requests[2],"iotdb_ndbc",["extreme"]))
         for request in [
-            {**requests[0],"field":"wspd;sql"},
+            {**requests[0],"measurements":["wspd;sql"]},
+            {**requests[0],"measurements":["wspd","wtmp"]},
+            {**requests[0],"gaps":False},
             {**requests[1],"gap_ms":True},
             {**requests[1],"gap_ms":0},
             {**requests[1],"gap_ms":2**63},
             {**requests[1],"windows":[{"start_ms":0,"end_ms":10}]},
-            {**requests[2],"mode":"average"},
-            {"command":"gaps","field":"wspd"},
+            {**requests[2],"by":"wspd;sql"},
+            {**requests[2],"aggregates":["argmax","argmin"]},
+            {**requests[0],"group_by":"session","gap_ms":1},
+            {"command":"stats","measurements":["wspd"],"gaps":True},
+            
{"command":"stats","path":scope,"measurements":["wspd"],"gap_ms":1},
+            {"command":"stats","path":scope,"measurements":["wspd"],"limit":5},
+            {"command":"gaps","path":scope,"field":"wspd"},
+            {"command":"extreme","path":scope,"field":"wspd","mode":"max"},
         ]:
-            with self.assertRaises(ValueError):
+            with self.subTest(request=request),self.assertRaises(ValueError):
                 build_command(request,"iotdb_ndbc",["temporal","extreme"])
-        self.assertNotIn("extreme",help_text(scope,["temporal"])["commands"])
-        self.assertNotIn("sessions",help_text(scope,["extreme"])["commands"])
+        self.assertNotIn("by=<numeric 
measurement>",help_text(scope,["temporal"])["commands"]["stats"])
+        
self.assertNotIn("group_by=session",help_text(scope,["extreme"])["commands"]["stats"])
+        
self.assertEqual(set(help_text(scope,["temporal","extreme","grid","reduce"])["commands"]),set(help_text(scope)["commands"]))
 
     def test_grep_no_match_is_distinct_from_fatal_jvm_exit(self):
         self.assertFalse(command_failed("grep",1,False,""))
@@ -98,23 +111,27 @@ class FsBoundaryTest(unittest.TestCase):
         self.assertTrue(command_failed("stats",1,False,""))
 
     def test_grid_and_reduce_gates_and_types(self):
-        
grid={"command":"windows","origin":"2024-03-10T00:00:00","width":1,"unit":"day","timezone":"America/New_York","start_ms":1710046800000,"end_ms":1710215999999}
+        
grid={"command":"stats","path":"/root/iotdb_ndbc","measurements":["wspd"],"origin":"2024-03-10T00:00:00","width":1,"unit":"day","timezone":"America/New_York","start_ms":1710046800000,"end_ms":1710215999999}
         with 
self.assertRaises(ValueError):build_command(grid,"iotdb_ndbc",["reduce"])
         native=build_command(grid,"iotdb_ndbc",["grid"])
         self.assertIn("--origin 2024-03-10T00:00:00",native)
-        self.assertNotIn("/root",native)
-        self.assertIn("-n 201",native)
-        
reduce={**grid,"command":"reduce","path":"/root/iotdb_ndbc","field":"wspd","metrics":["avg","delta"],"rank_by":"delta","top":3}
+        self.assertIn("--unit day",native)
+        self.assertNotIn(" -n ",native)
+        reduce={**grid,"aggregates":["avg","delta"],"sort_by":"delta"}
         with 
self.assertRaises(ValueError):build_command(reduce,"iotdb_ndbc",["reduce"])
         native=build_command(reduce,"iotdb_ndbc",["grid","reduce"])
-        self.assertIn("--rank-by delta",native)
-        self.assertIn("--group-by entity",native)
-        self.assertIn("--top 3",native)
-        for changes in 
[{"width":True},{"timezone":"UTC;sql"},{"origin":"0|cat"},{"unit":"year"},{"windows":[{"start_ms":0,"end_ms":1}]},{"metrics":["delta","delta"]},{"rank_by":"sum"},{"group_by":"auto"}]:
+        self.assertIn("--aggregates avg,delta",native)
+        self.assertIn("--sort-by delta --order desc",native)
+        self.assertIn("-n 201",native)
+        
pooled=build_command({"command":"stats","path":"/root/iotdb_ndbc","measurements":["wspd"],"group_by":"pooled"},"iotdb_ndbc",["reduce"])
+        self.assertIn("--aggregates count,first,last,delta --group-by 
pooled",pooled)
+        for changes in 
[{"width":True},{"timezone":"UTC;sql"},{"origin":"0|cat"},{"unit":"year"},{"windows":[{"start_ms":0,"end_ms":1}]},{"aggregates":["delta","delta"]},{"sort_by":"sum"},{"group_by":"auto"},{"aggregates":["median","delta"]},{"top":3}]:
             with 
self.subTest(changes=changes),self.assertRaises(ValueError):build_command({**reduce,**changes},"iotdb_ndbc",["grid","reduce"])
+        for old in 
[{"command":"windows","origin":"0","width":1,"start_ms":0,"end_ms":1},{"command":"reduce","path":"/root/iotdb_ndbc","field":"wspd"}]:
+            with 
self.assertRaises(ValueError):build_command(old,"iotdb_ndbc",["grid","reduce"])
         contract=help_text("/root/iotdb_ndbc",["grid","reduce"])
-        self.assertIn("sample-weighted",contract["commands"]["reduce"])
-        self.assertIn("no left partial",contract["commands"]["windows"])
+        self.assertIn("sample-weighted",contract["commands"]["stats"])
+        self.assertIn("no left partial",contract["commands"]["stats"])
 
     def test_resource_metrics_preserve_units(self):
         self.assertEqual(resource_metrics("Maximum resident set size (kbytes): 
1234\nUser time (seconds): 1.25\nSystem time (seconds): 0.10"), 
{"peak_rss_kib": 1234.0, "cpu_user_seconds": 1.25, "cpu_system_seconds": 0.1})
diff --git 
a/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/FsHelpMessages.java
 
b/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/FsHelpMessages.java
index 33e7bb5ccdc..36228ee29c5 100644
--- 
a/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/FsHelpMessages.java
+++ 
b/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/FsHelpMessages.java
@@ -80,6 +80,12 @@ public final class FsHelpMessages {
     "--aggregates accepts 
count,min,max,sum,avg,median,first,last,min_time,max_time,null_count. Omit for 
all. Only requested fields are accumulated. min_time/max_time are first/last 
non-null times, not argmin/argmax."
     + " " + "--windows start:end,... accepts 1..256 inclusive epoch ranges in 
input order, including overlapping or duplicate windows; excludes 
--start/--end. One scan per device/table reads their merged union. Output adds 
zero-based window_index, window_start, window_end; empty Tree windows retain 
zero counts, empty Table windows have no entities."
     + " " + "Scalar aggregates stream; exact median uses bounded buffers and 
private temporary disk runs cleaned on completion/failure. BOOLEAN sum counts 
true; INT64 sum/avg/median use exact decimal strings."
+    + " " + "Window grid: --origin (epoch ms or ISO datetime) with positive 
--width, optional --step (default width), --unit ms|day|month and --timezone 
(default UTC) expands --start/--end into explicit inclusive windows (at most 
256, clipped to --end, calendar units anchored at origin); it excludes 
--windows."
+    + " " + "Analytic modes take one target field (-m, or --by for 
argmin/argmax), stream raw observations in the CLI and paginate OUTPUT rows 
with -n/--offset. At most one mode applies."
+    + " " + "Reduction: --aggregates 
count,sum,avg,min,max,first,last,delta,elapsed_ms,rate_per_ms (default 
count,first,last,delta), selected by any of delta/elapsed_ms/rate_per_ms, 
--group-by entity|pooled or --sort-by. pooled merges raw observations per 
window (sample-weighted mean); delta=last-first at non-null physical-time 
endpoints, elapsed_ms=last_at-first_at, rate_per_ms=delta/elapsed_ms (NULL at 
zero span). --sort-by aggregate --order asc|desc (default desc) ranks all 
result row [...]
+    + " " + "--gaps: successive non-null observation gaps per entity, assigned 
to the later observation; each window returns distinct first/last/min/max gaps 
with previous_at, observed_at and exact gap_ms; the real predecessor may lie 
before the window."
+    + " " + "--group-by session --gap-ms G: sessions split only when a gap is 
strictly greater than G; --start/--end filter before segmentation; no windows. 
Output session_index/start/end, count, avg, first, last."
+    + " " + "--aggregates argmin|argmax --by F: the earliest row where F is 
minimal/maximal per entity/window, with -m associated fields (NULL retained)."
   };
   public static final String[] COUNT = {
     "Print row/entity/non-null/null counts and time ranges for TAG and FIELD 
columns. TIME and"
@@ -187,7 +193,4 @@ public final class FsHelpMessages {
     "Leave filesystem mode with the requested exit status; quit is an alias.",
     "Status is 0; supplied status is reduced to its low 8 bits."
   };
-  public static final String[] GAPS = {"Complete non-null predecessor gaps per 
entity, assigned to the later observation. Each inclusive window returns 
distinct first/last/min/max gap observations; equal extrema choose the earliest 
time. Output includes previous_at, observed_at, exact decimal gap_ms and 
selected_as.", "Required --field; optional --windows start:end,... (1..256, 
inclusive, excludes --start/--end). Without windows use one inclusive start/end 
interval, unbounded if omitted. [...]
-  public static final String[] SESSIONS = {"Complete sessions per entity over 
non-null finite numeric --field observations. Required positive --gap-ms: a new 
session starts only when the next gap is strictly greater; equality remains in 
the same session. Output session_index/start/end, count, avg, first and last.", 
"Optional inclusive --start/--end filters BEFORE segmentation, so boundary 
sessions are clipped and session_index restarts at zero. No windows. Tree 
devices and full Table TAG [...]
-  public static final String[] EXTREME = {"Select the complete associated row 
for finite numeric --field with required --mode min|max, independently per 
entity/window. Ties choose earliest time; NULL comparison values are skipped, 
NULL associated fields stay NULL. No global pooling or cross-entity ranking.", 
"Optional -m associated FIELD (repeatable; target always included), inclusive 
--windows start:end,... OR --start/--end; omitted bounds mean all time. Output 
object/TAG identity, wind [...]
 }
diff --git 
a/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/FsWindowMessages.java
 
b/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/FsWindowMessages.java
index 2de515d93e1..9ee4fece61a 100644
--- 
a/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/FsWindowMessages.java
+++ 
b/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/FsWindowMessages.java
@@ -22,8 +22,4 @@ public final class FsWindowMessages {
   private FsWindowMessages() {}
   public static final String 
EXCEPTION_INVALID_WINDOW_GRID_REQUIRE_INCLUSIVE_START_END_ORIGIN_EPOCH_MS_OR_ISO_LOCAL_OFFSET_DATETIME_POSITIVE_WIDTH_STEP_UNIT_MS_DAY_MONTH_AND_TIMEZONE_LOCAL_BOUNDARIES_MUST_BE_UNAMBIGUOUS_AND_EXISTENT_AT_MOST_256_STARTS_WITHIN_THE_REQUESTED_RANGE_OVERFLOW_IS_REJECTED_BEBD1447
 = "Invalid window grid: require inclusive start/end, origin (epoch ms or ISO 
local/offset datetime), positive width/step, unit ms|day|month and timezone. 
Local boundaries must be unam [...]
   public static final String 
EXCEPTION_INVALID_REDUCTION_REQUIRE_A_FINITE_NUMERIC_FIELD_GROUP_BY_ENTITY_POOLED_METRICS_COUNT_SUM_AVG_MIN_MAX_FIRST_LAST_DELTA_ELAPSED_MS_RATE_PER_MS_RANK_BY_MUST_BE_A_SELECTED_METRIC_ORDER_ASC_DESC_POSITIVE_TOP_AT_MOST_65536_NONEMPTY_ENTITY_WINDOW_GROUPS_3742D176
 = "Invalid reduction: require a finite numeric field; group-by entity|pooled; 
metrics count,sum,avg,min,max,first,last,delta,elapsed_ms,rate_per_ms; rank-by 
must be a selected metric, order asc|de [...]
-  public static final String 
MESSAGE_GENERATE_EXPLICIT_WINDOWS_WITHOUT_READING_DATA_REQUIRED_START_END_ARE_INCLUSIVE_EPOCH_MS_ORIGIN_IS_EPOCH_MS_OR_ISO_LOCAL_OFFSET_DATETIME_WIDTH_IS_POSITIVE_STEP_DEFAULTS_TO_WIDTH_UNIT_MS_DAY_MONTH_DEFAULTS_TO_MS_TIMEZONE_DEFAULTS_TO_UTC_SELECT_GRID_STARTS_INSIDE_THE_RANGE_CLIP_EACH_FINAL_END_TO_THE_REQUESTED_END_OUTPUT_NOMINAL_HALF_OPEN_AND_EFFECTIVE_INCLUSIVE_BOUNDS_LOCAL_LABELS_ORIGIN_UNIT_AND_TIMEZONE_CALENDAR_OFFSETS_ARE_ANCHORED_TO_ORIGIN_NO_ITERA
 [...]
-  public static final String 
MESSAGE_REDUCE_RAW_FINITE_NUMERIC_OBSERVATIONS_LOCALLY_FIELD_REQUIRED_METRICS_DEFAULTS_TO_COUNT_FIRST_LAST_DELTA_GROUP_BY_ENTITY_DEFAULT_KEEPS_TREE_DEVICE_OR_FULL_TABLE_TAG_TUPLE_POOLED_EXPLICITLY_MERGES_OBSERVATIONS_PER_WINDOW_NEVER_AVERAGES_ENTITY_AVERAGES_NULL_TARGET_SKIPPED_EMPTY_GROUPS_OMITTED_DELTA_LAST_FIRST_ELAPSED_MS_LAST_AT_FIRST_AT_RATE_PER_MS_DELTA_ELAPSED_MS_NULL_FOR_ZERO_SPAN_ENDPOINT_TIES_USE_LEXICOGRAPHIC_ENTITY_IDENTITY_NULL_TAGS_FIRST_RETURN
 [...]
-  public static final String 
MESSAGE_GENERATE_AN_EXPLICIT_FIXED_DURATION_OR_CALENDAR_WINDOW_GRID_CC82BDC7 = 
"Generate an explicit fixed-duration or calendar window grid.";
-  public static final String 
MESSAGE_REDUCE_OBSERVATIONS_AT_AN_EXPLICIT_ENTITY_GRAIN_AND_RANK_RESULT_ROWS_6D9CCB5B
 = "Reduce observations at an explicit entity grain and rank result rows.";
 }
diff --git 
a/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/FsHelpMessages.java
 
b/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/FsHelpMessages.java
index 1d346848010..0d5c4d79d47 100644
--- 
a/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/FsHelpMessages.java
+++ 
b/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/FsHelpMessages.java
@@ -55,6 +55,12 @@ public final class FsHelpMessages {
     "--aggregates 接受 
count,min,max,sum,avg,median,first,last,min_time,max_time,null_count;省略时返回全部统计,仅累积所选字段。min_time/max_time
 为首末非空时间,不是极值所在时间。"
     + " " + "--windows start:end,... 接受按输入顺序排列的 1..256 个 epoch 闭区间,可重叠或重复,与 
--start/--end 互斥。每个设备/表只扫描一次合并后的区间并集,返回从零开始的 
window_index、window_start、window_end;空 Tree 窗口保留零计数,空 Table 窗口无实体行。"
     + " " + "标量统计流式计算;精确 median 使用有界缓冲和私有临时磁盘文件,完成或失败时清理。BOOLEAN sum 为 true 
数量;INT64 sum/avg/median 保留精确十进制字符串。"
+    + " " + "窗口网格:--origin(epoch 毫秒或 ISO 时间)加正数 --width,可选 
--step(默认等于宽度)、--unit ms|day|month 与 --timezone(默认 UTC),把 --start/--end 
展开为显式闭区间窗口(最多 256 个,末窗截到 --end,日历单位以 origin 为锚);与 --windows 互斥。"
+    + " " + "分析模式只接受一个目标字段(-m;argmin/argmax 用 --by),在 CLI 
中流式处理原始观测,-n/--offset 对输出行分页;同一次调用只能选一种模式。"
+    + " " + "归约:--aggregates 取 
count,sum,avg,min,max,first,last,delta,elapsed_ms,rate_per_ms(默认 
count,first,last,delta),出现 delta/elapsed_ms/rate_per_ms、--group-by 
entity|pooled 或 --sort-by 之一即进入该模式。pooled 按窗口合并原始观测(按样本加权平均);delta 
为非空物理时间端点的末值减首值,elapsed_ms 为 last_at 减 first_at,rate_per_ms 为 
delta/elapsed_ms(零跨度为 NULL)。--sort-by 聚合名 --order asc|desc(默认 
desc)在分页前对全部结果行全局排序,NULL 置后。非空分组最多 65536 个。"
+    + " " + "--gaps:按实体计算相邻非空观测的间隔,归属后一个观测;每个窗口返回去重后的首、末、最小、最大间隔,含 
previous_at、observed_at 与精确 gap_ms;真实前驱可以在窗口之前。"
+    + " " + "--group-by session --gap-ms G:仅当间隔严格大于 G 时切分会话;--start/--end 
在切分前过滤;不支持窗口。输出 session_index/start/end、count、avg、first、last。"
+    + " " + "--aggregates argmin|argmax --by F:按实体/窗口返回 F 取最小/最大值的最早一行,-m 
指定关联字段(保留 NULL)。"
   };
   public static final String[] COUNT = {
     "输出 TAG 和 FIELD 的行数、设备数、非空数、空值数及时间范围;排除 TIME 和 ATTRIBUTE。",
@@ -102,7 +108,4 @@ public final class FsHelpMessages {
   };
   public static final String[] HELP = {"输出通用帮助或指定命令帮助;-h 与 --help 等价。", 
"未指定命令时输出通用帮助。"};
   public static final String[] EXIT = {"按指定状态码退出文件系统模式;quit 为别名。", "状态码默认为 
0;指定值保留低 8 位。"};
-  public static final String[] GAPS = 
{"按实体完整计算非空观测的前驱间隔,归属到后一条观测。每个包含端点的窗口返回去重后的 first/last/min/max 
间隔观测;极值并列取最早时间。输出 previous_at、observed_at、精确十进制 gap_ms 与 selected_as。", "必需 
--field;可选 --windows start:end,...(1..256,包含端点,与 --start/--end 互斥)。无 windows 
时使用一个 start/end 区间,省略边界表示无界。真实前驱可在区间外,因此扫描包含下界之前的观测。Tree 设备与 Table 完整 TAG 
键独立;跳过 NULL 字段,空窗口或无间隔不返回行。-n/--offset 对输出行分页,默认无限/0;-f table|csv|ndjson,默认 
table;Table --tag-filter/--tag-match all|any 在分析前生效。"};
-  public static final String[] SESSIONS = {"按实体完整计算非空有限数值 --field 的 
session。必需正数 --gap-ms:仅在下一间隔严格大于阈值时分段,相等不分段。输出 
session_index/start/end、count、avg、first、last。", "可选包含端点的 --start/--end 
在分段之前过滤,因此边界 session 会裁剪,session_index 从零重新编号。不支持 windows。Tree 设备与 Table 完整 TAG 
组合不混合;跳过 NULL。-n/--offset 对输出 session 分页,默认无限/0;-f table|csv|ndjson;Table 
--tag-filter/--tag-match all|any。整数平均值保持精确十进制运算。"};
-  public static final String[] EXTREME = {"对有限数值 --field 使用必需的 --mode 
min|max,在每个实体/窗口内选择极值关联行。并列取最早时间;跳过 NULL 比较值,保留关联字段的 NULL。不跨实体混合或排名。", "可选 -m 
关联 FIELD(可重复,始终包含目标字段)、包含端点的 --windows start:end,... 或 
--start/--end;省略边界表示全时段。输出 object/TAG 
身份、window_index/start/end、observed_at、extreme_value 和 
value.<field>。空窗口不返回行。-n/--offset 对输出行分页,默认无限/0;-f table|csv|ndjson;Table 
--tag-filter/--tag-match all|any。"};
 }
diff --git 
a/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/FsWindowMessages.java
 
b/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/FsWindowMessages.java
index fa98530ecc0..d9583de89fc 100644
--- 
a/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/FsWindowMessages.java
+++ 
b/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/FsWindowMessages.java
@@ -22,8 +22,4 @@ public final class FsWindowMessages {
   private FsWindowMessages() {}
   public static final String 
EXCEPTION_INVALID_WINDOW_GRID_REQUIRE_INCLUSIVE_START_END_ORIGIN_EPOCH_MS_OR_ISO_LOCAL_OFFSET_DATETIME_POSITIVE_WIDTH_STEP_UNIT_MS_DAY_MONTH_AND_TIMEZONE_LOCAL_BOUNDARIES_MUST_BE_UNAMBIGUOUS_AND_EXISTENT_AT_MOST_256_STARTS_WITHIN_THE_REQUESTED_RANGE_OVERFLOW_IS_REJECTED_BEBD1447
 = "窗口网格无效:需提供包含端点的 start/end、origin(epoch 毫秒或 ISO 本地/偏移日期时间)、正数 
width/step、unit ms|day|month 和 timezone。本地边界必须存在且无歧义;范围内最多 256 个起点,拒绝溢出。";
   public static final String 
EXCEPTION_INVALID_REDUCTION_REQUIRE_A_FINITE_NUMERIC_FIELD_GROUP_BY_ENTITY_POOLED_METRICS_COUNT_SUM_AVG_MIN_MAX_FIRST_LAST_DELTA_ELAPSED_MS_RATE_PER_MS_RANK_BY_MUST_BE_A_SELECTED_METRIC_ORDER_ASC_DESC_POSITIVE_TOP_AT_MOST_65536_NONEMPTY_ENTITY_WINDOW_GROUPS_3742D176
 = "归约无效:需指定有限数值字段;group-by entity|pooled;metrics 
count,sum,avg,min,max,first,last,delta,elapsed_ms,rate_per_ms;rank-by 
必须为选中指标,order asc|desc,top 为正数;最多 65536 个非空实体/窗口分组。";
-  public static final String 
MESSAGE_GENERATE_EXPLICIT_WINDOWS_WITHOUT_READING_DATA_REQUIRED_START_END_ARE_INCLUSIVE_EPOCH_MS_ORIGIN_IS_EPOCH_MS_OR_ISO_LOCAL_OFFSET_DATETIME_WIDTH_IS_POSITIVE_STEP_DEFAULTS_TO_WIDTH_UNIT_MS_DAY_MONTH_DEFAULTS_TO_MS_TIMEZONE_DEFAULTS_TO_UTC_SELECT_GRID_STARTS_INSIDE_THE_RANGE_CLIP_EACH_FINAL_END_TO_THE_REQUESTED_END_OUTPUT_NOMINAL_HALF_OPEN_AND_EFFECTIVE_INCLUSIVE_BOUNDS_LOCAL_LABELS_ORIGIN_UNIT_AND_TIMEZONE_CALENDAR_OFFSETS_ARE_ANCHORED_TO_ORIGIN_NO_ITERA
 [...]
-  public static final String 
MESSAGE_REDUCE_RAW_FINITE_NUMERIC_OBSERVATIONS_LOCALLY_FIELD_REQUIRED_METRICS_DEFAULTS_TO_COUNT_FIRST_LAST_DELTA_GROUP_BY_ENTITY_DEFAULT_KEEPS_TREE_DEVICE_OR_FULL_TABLE_TAG_TUPLE_POOLED_EXPLICITLY_MERGES_OBSERVATIONS_PER_WINDOW_NEVER_AVERAGES_ENTITY_AVERAGES_NULL_TARGET_SKIPPED_EMPTY_GROUPS_OMITTED_DELTA_LAST_FIRST_ELAPSED_MS_LAST_AT_FIRST_AT_RATE_PER_MS_DELTA_ELAPSED_MS_NULL_FOR_ZERO_SPAN_ENDPOINT_TIES_USE_LEXICOGRAPHIC_ENTITY_IDENTITY_NULL_TAGS_FIRST_RETURN
 [...]
-  public static final String 
MESSAGE_GENERATE_AN_EXPLICIT_FIXED_DURATION_OR_CALENDAR_WINDOW_GRID_CC82BDC7 = 
"生成显式固定时长或日历窗口网格。";
-  public static final String 
MESSAGE_REDUCE_OBSERVATIONS_AT_AN_EXPLICIT_ENTITY_GRAIN_AND_RANK_RESULT_ROWS_6D9CCB5B
 = "按明确实体粒度归约观测并对结果行排名。";
 }
diff --git 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/FilesystemShell.java 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/FilesystemShell.java
index 58342dc6c70..7754eaf0af6 100644
--- 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/FilesystemShell.java
+++ 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/FilesystemShell.java
@@ -26,7 +26,6 @@ import org.apache.iotdb.cli.fs.command.FsShellWords;
 import org.apache.iotdb.cli.fs.command.ReadOptions;
 import org.apache.iotdb.cli.fs.command.ReductionOptions;
 import org.apache.iotdb.cli.fs.command.TemporalOptions;
-import org.apache.iotdb.cli.fs.command.WindowGrid;
 import org.apache.iotdb.cli.fs.node.FsColumn;
 import org.apache.iotdb.cli.fs.node.FsNode;
 import org.apache.iotdb.cli.fs.node.FsNodeType;
@@ -85,9 +84,6 @@ public class FilesystemShell {
           "meta",
           "schema",
           "stats",
-          "gaps",
-          "sessions",
-          "extreme",
           "count",
           "wc",
           "cat",
@@ -166,12 +162,9 @@ public class FilesystemShell {
           printNode(node);
         }
         return true;
-      case WINDOWS:
       case REDUCE:
         List<SqlRow> reduced =
-            command.getType() == FilesystemCommand.Type.WINDOWS
-                ? WindowGrid.from(command).rows()
-                : provider.reduce(resolve(command.getPath()), 
ReductionOptions.from(command));
+            provider.reduce(resolve(command.getPath()), 
ReductionOptions.from(command));
         ReadOptions reductionRead = command.getReadOptions();
         int from = (int) Math.min(reduced.size(), reductionRead.getOffset());
         int to =
diff --git 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommand.java
 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommand.java
index e270a1e263a..e0dcbfa0e77 100644
--- 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommand.java
+++ 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommand.java
@@ -36,7 +36,6 @@ public class FilesystemCommand {
     META,
     SCHEMA,
     STATS,
-    WINDOWS,
     REDUCE,
     GAPS,
     SESSIONS,
diff --git 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommandHelp.java
 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommandHelp.java
index bf887a6b9d9..14aac577a96 100644
--- 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommandHelp.java
+++ 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommandHelp.java
@@ -21,7 +21,6 @@ package org.apache.iotdb.cli.fs.command;
 
 import org.apache.iotdb.cli.i18n.CliMessages;
 import org.apache.iotdb.cli.i18n.FsHelpMessages;
-import org.apache.iotdb.cli.i18n.FsWindowMessages;
 
 import java.io.PrintStream;
 import java.util.LinkedHashMap;
@@ -40,30 +39,7 @@ public final class FilesystemCommandHelp {
           + " [--offset n] [--start time] [--end time]"
           + " [--tag-filter tag op [value]] [--tag-match all|any]";
 
-  private static final String TEMPORAL_READ =
-      "[-f table|ndjson|csv] [--offset n] [--start ms] [--end ms] 
[--tag-filter tag op [value]] [--tag-match all|any]";
-
   static {
-    add(
-        "windows",
-        "windows --start ms --end ms --origin epoch-or-ISO --width n [--step 
n] [--unit ms|day|month] [--timezone zone] [-n n] [-f ndjson] [--offset n]",
-        new String[] {
-          FsWindowMessages
-              
.MESSAGE_GENERATE_AN_EXPLICIT_FIXED_DURATION_OR_CALENDAR_WINDOW_GRID_CC82BDC7,
-          FsWindowMessages
-              
.MESSAGE_GENERATE_EXPLICIT_WINDOWS_WITHOUT_READING_DATA_REQUIRED_START_END_ARE_INCLUSIVE_EPOCH_MS_ORIGIN_IS_EPOCH_MS_OR_ISO_LOCAL_OFFSET_DATETIME_WIDTH_IS_POSITIVE_STEP_DEFAULTS_TO_WIDTH_UNIT_MS_DAY_MONTH_DEFAULTS_TO_MS_TIMEZONE_DEFAULTS_TO_UTC_SELECT_GRID_STARTS_INSIDE_THE_RANGE_CLIP_EACH_FINAL_END_TO_THE_REQUESTED_END_OUTPUT_NOMINAL_HALF_OPEN_AND_EFFECTIVE_INCLUSIVE_BOUNDS_LOCAL_LABELS_ORIGIN_UNIT_AND_TIMEZONE_CALENDAR_OFFSETS_ARE_ANCHORED_TO_ORIGIN_NO_ITERATIVE_MONTH_DRI
 [...]
-        },
-        "windows --start 0 --end 9999 --origin 0 --width 1000 -f ndjson");
-    add(
-        "reduce",
-        "reduce path --field field [--metrics 
count,sum,avg,min,max,first,last,delta,elapsed_ms,rate_per_ms] [--group-by 
entity|pooled] [--rank-by metric --order asc|desc --top n] [--windows 
start:end,... | --start ms --end ms] [--origin epoch-or-ISO --width n --step n 
--unit ms|day|month --timezone zone] [-n n] [--offset n] [-f table|csv|ndjson] 
[--tag-filter tag op value] [--tag-match all|any]",
-        new String[] {
-          FsWindowMessages
-              
.MESSAGE_REDUCE_OBSERVATIONS_AT_AN_EXPLICIT_ENTITY_GRAIN_AND_RANK_RESULT_ROWS_6D9CCB5B,
-          FsWindowMessages
-              
.MESSAGE_REDUCE_RAW_FINITE_NUMERIC_OBSERVATIONS_LOCALLY_FIELD_REQUIRED_METRICS_DEFAULTS_TO_COUNT_FIRST_LAST_DELTA_GROUP_BY_ENTITY_DEFAULT_KEEPS_TREE_DEVICE_OR_FULL_TABLE_TAG_TUPLE_POOLED_EXPLICITLY_MERGES_OBSERVATIONS_PER_WINDOW_NEVER_AVERAGES_ENTITY_AVERAGES_NULL_TARGET_SKIPPED_EMPTY_GROUPS_OMITTED_DELTA_LAST_FIRST_ELAPSED_MS_LAST_AT_FIRST_AT_RATE_PER_MS_DELTA_ELAPSED_MS_NULL_FOR_ZERO_SPAN_ENDPOINT_TIES_USE_LEXICOGRAPHIC_ENTITY_IDENTITY_NULL_TAGS_FIRST_RETURN_ENDPOINT_IDEN
 [...]
-        },
-        "reduce /root/db --field value --metrics avg,delta --rank-by delta 
--top 5 -f ndjson");
     add("pwd", "pwd", FsHelpMessages.PWD, "pwd");
     add("ls", "ls [-laR] " + FORMAT + " [path]", FsHelpMessages.LS, "ls /\n  
ls -la /db1");
     add("ll", "ll [-aR] " + FORMAT + " [path]", FsHelpMessages.LL, "ll -a 
/db1");
@@ -82,26 +58,18 @@ public final class FilesystemCommandHelp {
             + SCOPE
             + " "
             + FORMAT
-            + " [--start time] [--end time] [--tag-filter tag op [value]]"
-            + " [--tag-match all|any] [--aggregates 
count,min,max,sum,avg,median,first,last,min_time,max_time,null_count] 
[--windows start:end,...] [path]",
+            + " [--start time] [--end time] [--tag-filter tag op [value]] 
[--tag-match all|any]"
+            + " [--aggregates list] [--windows start:end,... | --origin 
epoch-or-ISO --width n"
+            + " [--step n] [--unit ms|day|month] [--timezone zone]]"
+            + " [--group-by entity|pooled|session] [--gap-ms duration] 
[--gaps] [--by field]"
+            + " [--sort-by aggregate [--order asc|desc]] [-n count] [--offset 
n] [path]",
         FsHelpMessages.STATS,
-        "stats /db1/table1.csv -m temperature --start 0 --end 1000 
--aggregates avg,median");
-    add(
-        "gaps",
-        "gaps path --field field [--windows start:end,...] [-n count] " + 
TEMPORAL_READ,
-        FsHelpMessages.GAPS,
-        "gaps /root/db/device --field value --windows 
0:3599999,3600000:7199999 -f ndjson");
-    add(
-        "sessions",
-        "sessions path --field field --gap-ms duration [-n count] " + 
TEMPORAL_READ,
-        FsHelpMessages.SESSIONS,
-        "sessions /root/db/device --field value --gap-ms 14400000 -f ndjson");
-    add(
-        "extreme",
-        "extreme path --field field --mode min|max [-m field ...] [--windows 
start:end,...] [-n count] "
-            + TEMPORAL_READ,
-        FsHelpMessages.EXTREME,
-        "extreme /root/db/device --field temperature --mode max -m humidity -f 
ndjson");
+        "stats /db1/table1.csv -m temperature --start 0 --end 1000 
--aggregates avg,median\n"
+            + "  stats /root/db -m value --aggregates avg,delta --sort-by 
delta -n 5\n"
+            + "  stats /root/db/device -m value --start 0 --end 86399999 
--origin 0 --width 3600000\n"
+            + "  stats /root/db/device -m value --gaps --windows 
0:3599999,3600000:7199999\n"
+            + "  stats /root/db/device -m value --group-by session --gap-ms 
14400000\n"
+            + "  stats /root/db/device --by temperature --aggregates argmax -m 
humidity");
     add(
         "count",
         "count " + SCOPE + " " + FORMAT + " [path]",
diff --git 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommandParser.java
 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommandParser.java
index 7e418737eb4..f2f34a2f268 100644
--- 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommandParser.java
+++ 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/FilesystemCommandParser.java
@@ -123,11 +123,138 @@ public class FilesystemCommandParser {
   }
 
   private static FilesystemCommand.Type commandType(String command) {
+    if (INTERNAL_MODES.contains(command)) return 
FilesystemCommand.Type.INVALID;
     return "quit".equals(command)
         ? FilesystemCommand.Type.EXIT
         : FilesystemCommand.Type.valueOf(command.toUpperCase(Locale.ROOT));
   }
 
+  /** Analytic modes of {@code stats}; they are internal command types, not 
command names. */
+  private static final List<String> INTERNAL_MODES =
+      java.util.Arrays.asList("windows", "reduce", "gaps", "sessions", 
"extreme");
+
+  private static final List<String> GRID_FLAGS =
+      java.util.Arrays.asList("--origin", "--width", "--step", "--unit", 
"--timezone");
+
+  private static final List<String> REDUCTION_ONLY_AGGREGATES =
+      java.util.Arrays.asList("delta", "elapsed_ms", "rate_per_ms");
+
+  private static final List<String> ANALYTIC_ONLY_FLAGS =
+      java.util.Arrays.asList("--by", "--gap-ms", "--sort-by", "--order", 
"-n", "--offset");
+
+  /**
+   * Chooses the engine behind {@code stats}: plain statistics, or the 
reduction/temporal engines
+   * selected by parameters. At most one analytic mode may be requested.
+   */
+  private static FilesystemCommand.Type statsMode(Arguments args) {
+    List<String> aggregates =
+        args.has("--aggregates")
+            ? java.util.Arrays.asList(args.value("--aggregates").split(",", 
-1))
+            : java.util.Collections.emptyList();
+    String groupBy = args.valueOrDefault("--group-by", "");
+    List<FilesystemCommand.Type> modes = new ArrayList<>();
+    if (args.has("--gaps")) modes.add(FilesystemCommand.Type.GAPS);
+    if ("session".equals(groupBy)) modes.add(FilesystemCommand.Type.SESSIONS);
+    if (aggregates.contains("argmin") || aggregates.contains("argmax"))
+      modes.add(FilesystemCommand.Type.EXTREME);
+    if ((args.has("--group-by") && !"session".equals(groupBy))
+        || args.has("--sort-by")
+        || aggregates.stream().anyMatch(REDUCTION_ONLY_AGGREGATES::contains))
+      modes.add(FilesystemCommand.Type.REDUCE);
+    if (modes.size() > 1)
+      throw invalid(
+          CliMessages.EXCEPTION_ARG_UNEXPECTED_ARGUMENT_ARG_3EF9EC3F,
+          "stats",
+          "--gaps, --group-by session, argmin/argmax and reduction options are 
exclusive");
+    return modes.isEmpty() ? FilesystemCommand.Type.STATS : modes.get(0);
+  }
+
+  /** Rewrites {@code stats} parameters into the options of the selected 
internal engine. */
+  private static FilesystemCommand analyticStats(
+      String command, FilesystemCommand.Type mode, Arguments args) {
+    if (args.has("--by") != (mode == FilesystemCommand.Type.EXTREME)
+        || (args.has("--gap-ms") && mode != FilesystemCommand.Type.SESSIONS)
+        || ((args.has("--sort-by") || args.has("--order"))
+            && mode != FilesystemCommand.Type.REDUCE))
+      throw invalid(
+          CliMessages.EXCEPTION_ARG_UNEXPECTED_ARGUMENT_ARG_3EF9EC3F, command, 
mode.name());
+    if (mode == FilesystemCommand.Type.EXTREME) {
+      List<String> aggregates = 
java.util.Arrays.asList(args.value("--aggregates").split(",", -1));
+      if (aggregates.size() != 1) throw TemporalOptions.invalid();
+      args.options.put("--field", args.value("--by"));
+      args.options.put("--mode", "argmax".equals(aggregates.get(0)) ? "max" : 
"min");
+      args.options.remove("--by");
+      args.options.remove("--aggregates");
+    } else {
+      List<String> fields = args.values("-m");
+      if (fields.size() != 1)
+        throw mode == FilesystemCommand.Type.REDUCE
+            ? ReductionOptions.invalid()
+            : TemporalOptions.invalid();
+      args.options.put("--field", fields.get(0));
+      args.options.remove("-m");
+      args.repeated.remove("-m");
+    }
+    switch (mode) {
+      case GAPS:
+        if (args.has("--aggregates")) throw TemporalOptions.invalid();
+        args.options.remove("--gaps");
+        break;
+      case SESSIONS:
+        if (args.has("--aggregates")) throw TemporalOptions.invalid();
+        args.options.remove("--group-by");
+        break;
+      case REDUCE:
+        if (args.has("--aggregates")) args.options.put("--metrics", 
args.value("--aggregates"));
+        if (args.has("--sort-by")) args.options.put("--rank-by", 
args.value("--sort-by"));
+        args.options.remove("--aggregates");
+        args.options.remove("--sort-by");
+        break;
+      default:
+        break;
+    }
+    // The reduction engine expands grids itself; the temporal engines take 
explicit windows.
+    if (mode != FilesystemCommand.Type.REDUCE) gridToWindows(args);
+    if (args.has("--windows") && args.value("--windows").isEmpty())
+      throw mode == FilesystemCommand.Type.REDUCE
+          ? ReductionOptions.invalid()
+          : TemporalOptions.invalid();
+    FilesystemCommand analytic =
+        withReadOptions(
+                FilesystemCommand.path(mode, args.path(false))
+                    .withLimit(
+                        args.has("-n")
+                            ? unsignedInteger(command, "-n", args.value("-n"), 
false)
+                            : -1),
+                args,
+                "-f")
+            .withOptions(args.options);
+    if (mode == FilesystemCommand.Type.REDUCE) ReductionOptions.from(analytic);
+    else TemporalOptions.from(analytic);
+    return analytic;
+  }
+
+  /**
+   * Expands {@code --origin/--width/--step/--unit/--timezone} with {@code 
--start/--end} into the
+   * equivalent explicit {@code --windows} list.
+   */
+  private static void gridToWindows(Arguments args) {
+    if (!args.has("--origin")) {
+      for (String flag : GRID_FLAGS) if (args.has(flag)) throw 
WindowGrid.invalid();
+      return;
+    }
+    if (args.has("--windows")) throw WindowGrid.invalid();
+    FilesystemCommand probe =
+        withReadOptions(
+                FilesystemCommand.path(FilesystemCommand.Type.STATS, 
DEFAULT_PATH), args, "-f")
+            .withOptions(args.options);
+    String ranges = WindowGrid.from(probe).ranges();
+    for (String flag : GRID_FLAGS) args.options.remove(flag);
+    args.options.remove("--start");
+    args.options.remove("--end");
+    args.options.put("--windows", ranges);
+  }
+
   private static FilesystemCommand parseCommand(String command, Arguments 
args) {
     FilesystemCommand.Type type = commandType(command);
     switch (type) {
@@ -146,51 +273,29 @@ public class FilesystemCommandParser {
       case CD:
         args.paths(0, 1);
         return FilesystemCommand.path(type, args.operands.isEmpty() ? "/" : 
args.operands.get(0));
-      case WINDOWS:
-      case REDUCE:
-        validateScope(args);
-        if (type == FilesystemCommand.Type.WINDOWS) args.paths(0, 0);
-        if (args.has("--windows") && args.value("--windows").isEmpty())
-          throw ReductionOptions.invalid();
-        FilesystemCommand reduction =
-            withReadOptions(
-                    FilesystemCommand.path(type, args.path(type == 
FilesystemCommand.Type.REDUCE))
-                        .withLimit(
-                            args.has("-n")
-                                ? unsignedInteger(command, "-n", 
args.value("-n"), false)
-                                : -1),
-                    args,
-                    "-f")
-                .withOptions(args.options);
-        if (type == FilesystemCommand.Type.REDUCE) 
ReductionOptions.from(reduction);
-        else WindowGrid.from(reduction);
-        return reduction;
-      case GAPS:
-      case SESSIONS:
-      case EXTREME:
+      case STATS:
         validateScope(args);
-        FilesystemCommand temporal =
-            withReadOptions(
-                    FilesystemCommand.path(type, args.path(true))
-                        .withLimit(
-                            args.has("-n")
-                                ? unsignedInteger(command, "-n", 
args.value("-n"), false)
-                                : -1),
-                    args,
-                    "-f")
-                .withOptions(args.options);
-        if (args.has("--windows") && args.value("--windows").isEmpty())
-          throw TemporalOptions.invalid();
-        TemporalOptions.from(temporal);
-        return temporal;
+        FilesystemCommand.Type mode = statsMode(args);
+        if (mode != FilesystemCommand.Type.STATS) return 
analyticStats(command, mode, args);
+        for (String flag : ANALYTIC_ONLY_FLAGS)
+          if (args.has(flag))
+            throw 
invalid(CliMessages.EXCEPTION_ARG_UNSUPPORTED_OPTION_ARG_33DE669D, command, 
flag);
+        gridToWindows(args);
+        if (args.has("--aggregates")) 
validateAggregates(args.value("--aggregates"));
+        FilesystemCommand statistics =
+            withReadOptions(FilesystemCommand.path(type, args.path(false)), 
args, "-f");
+        if (args.has("--windows")) {
+          String windows = args.value("--windows");
+          if (windows.isEmpty())
+            throw invalid(
+                CliMessages.EXCEPTION_ARG_UNEXPECTED_ARGUMENT_ARG_3EF9EC3F, 
"stats", windows);
+          statistics.getReadOptions().withStatistics("", windows);
+        }
+        return statistics;
       case SCHEMA:
       case META:
-      case STATS:
       case COUNT:
         validateScope(args);
-        if (type == FilesystemCommand.Type.STATS && args.has("--aggregates")) {
-          validateAggregates(args.value("--aggregates"));
-        }
         FilesystemCommand metadata =
             withReadOptions(FilesystemCommand.path(type, args.path(false)), 
args, "-f");
         if (args.has("--windows")) {
@@ -753,7 +858,8 @@ public class FilesystemCommandParser {
                   || "-i".equals(flag)
                   || "-v".equals(flag)
                   || "-n".equals(flag)))
-          || (("export".equals(command) || "sketch".equals(command)) && 
"--force".equals(flag));
+          || (("export".equals(command) || "sketch".equals(command)) && 
"--force".equals(flag))
+          || ("stats".equals(command) && "--gaps".equals(flag));
     }
 
     private boolean allShortFlags(String token) {
@@ -781,51 +887,6 @@ public class FilesystemCommandParser {
               || "--table".equals(flag)
               || "-m".equals(flag)
               || "--measurements".equals(flag);
-        case "windows":
-        case "reduce":
-          return java.util.Arrays.asList(
-                      "--origin",
-                      "--width",
-                      "--step",
-                      "--unit",
-                      "--timezone",
-                      "--start",
-                      "--end",
-                      "-f",
-                      "--format",
-                      "-n",
-                      "--limit",
-                      "--offset")
-                  .contains(flag)
-              || ("reduce".equals(command)
-                  && java.util.Arrays.asList(
-                          "--field",
-                          "--metrics",
-                          "--group-by",
-                          "--rank-by",
-                          "--order",
-                          "--top",
-                          "--windows",
-                          "--tag-filter",
-                          "--tag-match")
-                      .contains(flag));
-        case "gaps":
-        case "sessions":
-        case "extreme":
-          return "--field".equals(flag)
-              || ("sessions".equals(command) && "--gap-ms".equals(flag))
-              || ("extreme".equals(command)
-                  && ("--mode".equals(flag) || "-m".equals(flag) || 
"--measurements".equals(flag)))
-              || (!"sessions".equals(command) && "--windows".equals(flag))
-              || "-f".equals(flag)
-              || "--format".equals(flag)
-              || "-n".equals(flag)
-              || "--limit".equals(flag)
-              || "--offset".equals(flag)
-              || "--start".equals(flag)
-              || "--end".equals(flag)
-              || "--tag-filter".equals(flag)
-              || "--tag-match".equals(flag);
         case "stats":
           return "-f".equals(flag)
               || "--format".equals(flag)
@@ -840,7 +901,22 @@ public class FilesystemCommandParser {
               || "--tag-filter".equals(flag)
               || "--tag-match".equals(flag)
               || "--aggregates".equals(flag)
-              || "--windows".equals(flag);
+              || "--windows".equals(flag)
+              || java.util.Arrays.asList(
+                      "--origin",
+                      "--width",
+                      "--step",
+                      "--unit",
+                      "--timezone",
+                      "--group-by",
+                      "--gap-ms",
+                      "--by",
+                      "--sort-by",
+                      "--order",
+                      "-n",
+                      "--limit",
+                      "--offset")
+                  .contains(flag);
         case "sketch":
           return "-o".equals(flag) || "--output".equals(flag);
         case "export":
diff --git 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/WindowGrid.java
 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/WindowGrid.java
index 48f74cc40b9..bee001b6ae7 100644
--- 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/WindowGrid.java
+++ 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/cli/fs/command/WindowGrid.java
@@ -74,7 +74,6 @@ public final class WindowGrid {
         } else
           for (ReadOptions.Window w : read.getWindows())
             g.bounds.add(new Bounds(w.getStart(), w.getEnd(), null, null));
-        if (c.getType() == FilesystemCommand.Type.WINDOWS) throw invalid();
         return g;
       }
       if (read.getStart() == null
diff --git 
a/iotdb-client/cli/src/test/java/org/apache/iotdb/cli/fs/command/FilesystemCommandParserTest.java
 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/cli/fs/command/FilesystemCommandParserTest.java
index 8c17b782bab..804f2b661ea 100644
--- 
a/iotdb-client/cli/src/test/java/org/apache/iotdb/cli/fs/command/FilesystemCommandParserTest.java
+++ 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/cli/fs/command/FilesystemCommandParserTest.java
@@ -23,6 +23,8 @@ import org.apache.iotdb.cli.i18n.CliMessages;
 
 import org.junit.Test;
 
+import java.util.Collections;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -781,28 +783,78 @@ public class FilesystemCommandParserTest {
   }
 
   @Test
-  public void temporalCommandsValidateContractBeforeExecution() {
-    assertEquals(
-        FilesystemCommand.Type.GAPS,
+  public void statsSelectsAnalyticModesByParameters() {
+    FilesystemCommand gaps =
         FilesystemCommandParser.parse(
-                "gaps /root/db/d --field x --windows -10:0,0:10 -n 3 --offset 
1 -f ndjson")
-            .getType());
+            "stats /root/db/d -m x --gaps --windows -10:0,0:10 -n 3 --offset 1 
-f ndjson");
+    assertEquals(FilesystemCommand.Type.GAPS, gaps.getType());
+    assertEquals("x", gaps.optionValue("--field", ""));
+    assertTrue(gaps.getReadOptions().getColumns().isEmpty());
     assertEquals(
         FilesystemCommand.Type.SESSIONS,
         FilesystemCommandParser.parse(
-                "sessions /db/t.csv --field x --gap-ms 14400000 --start 0 
--end 10")
+                "stats /db/t.csv -m x --group-by session --gap-ms 14400000 
--start 0 --end 10")
             .getType());
+    FilesystemCommand extreme =
+        FilesystemCommandParser.parse("stats /root/db/d --by x --aggregates 
argmax -m y");
+    assertEquals(FilesystemCommand.Type.EXTREME, extreme.getType());
+    assertEquals("max", extreme.optionValue("--mode", ""));
+    assertEquals(Collections.singletonList("y"), 
extreme.getReadOptions().getColumns());
+    FilesystemCommand reduce =
+        FilesystemCommandParser.parse(
+            "stats /root/db -m x --aggregates avg,delta --sort-by delta 
--order asc -n 5");
+    assertEquals(FilesystemCommand.Type.REDUCE, reduce.getType());
+    assertEquals("avg,delta", reduce.optionValue("--metrics", ""));
+    assertEquals("delta", reduce.optionValue("--rank-by", ""));
+    assertEquals(
+        FilesystemCommand.Type.REDUCE,
+        FilesystemCommandParser.parse("stats /root/db -m x --group-by 
pooled").getType());
+    assertEquals(
+        FilesystemCommand.Type.STATS,
+        FilesystemCommandParser.parse("stats /root/db -m x --aggregates 
avg,median").getType());
+  }
+
+  @Test
+  public void statsExpandsInlineGridIntoExplicitWindows() {
+    FilesystemCommand c =
+        FilesystemCommandParser.parse(
+            "stats /root/db/d -m x --start 0 --end 25 --origin 0 --width 10");
+    assertEquals(FilesystemCommand.Type.STATS, c.getType());
+    assertEquals(3, c.getReadOptions().getWindows().size());
+    assertEquals(20L, c.getReadOptions().getWindows().get(2).getStart());
+    assertEquals(25L, c.getReadOptions().getWindows().get(2).getEnd());
     assertEquals(
-        FilesystemCommand.Type.EXTREME,
-        FilesystemCommandParser.parse("extreme /root/db/d --field x --mode max 
-m y").getType());
+        FilesystemCommand.Type.GAPS,
+        FilesystemCommandParser.parse(
+                "stats /root/db/d -m x --gaps --start 0 --end 25 --origin 0 
--width 10")
+            .getType());
+  }
+
+  @Test
+  public void analyticStatsValidateContractBeforeExecution() {
     for (String command :
         new String[] {
-          "gaps /root/db/d",
-          "sessions /root/db/d --field x --gap-ms 0",
-          "sessions /root/db/d --field x --gap-ms 1 --windows 0:1",
-          "extreme /root/db/d --field x --mode top",
-          "gaps /root/db/d --field x --start 10 --end 0",
-          "extreme /root/db/d --field x --mode max --windows 0:1 --end 1"
+          "gaps /root/db/d --field x",
+          "sessions /root/db/d --field x --gap-ms 1",
+          "extreme /root/db/d --field x --mode max",
+          "reduce /root/db --field x",
+          "windows --start 0 --end 10 --origin 0 --width 1",
+          "stats /root/db/d --gaps",
+          "stats /root/db/d -m x -m y --gaps",
+          "stats /root/db/d -m x --group-by session --gap-ms 0",
+          "stats /root/db/d -m x --group-by session --gap-ms 1 --windows 0:1",
+          "stats /root/db/d --by x --aggregates argmax,argmin",
+          "stats /root/db/d -m x --aggregates argmax",
+          "stats /root/db/d -m x --gaps --start 10 --end 0",
+          "stats /root/db/d --by x --aggregates argmax --windows 0:1 --end 1",
+          "stats /root/db/d -m x --gaps --group-by session --gap-ms 1",
+          "stats /root/db/d -m x --gaps --aggregates delta",
+          "stats /root/db/d -m x --aggregates avg,median --sort-by avg",
+          "stats /root/db/d -m x -n 3",
+          "stats /root/db/d -m x --order asc",
+          "stats /root/db/d -m x --gap-ms 1",
+          "stats /root/db/d -m x --width 10 --start 0 --end 10",
+          "stats /root/db/d -m x --origin 0 --width 10 --windows 0:1"
         })
       assertEquals(
           command,
diff --git 
a/iotdb-client/cli/src/test/java/org/apache/iotdb/cli/fs/provider/FsReductionTest.java
 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/cli/fs/provider/FsReductionTest.java
index e67355b90a2..6d3763d7ae3 100644
--- 
a/iotdb-client/cli/src/test/java/org/apache/iotdb/cli/fs/provider/FsReductionTest.java
+++ 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/cli/fs/provider/FsReductionTest.java
@@ -46,11 +46,12 @@ public class FsReductionTest {
   }
 
   private WindowGrid grid(String flags) {
-    return WindowGrid.from(parse("windows -f ndjson " + flags));
+    return WindowGrid.from(parse("stats /root/db -m x --aggregates delta -f 
ndjson " + flags));
   }
 
   private ReductionOptions options(String flags) {
-    return ReductionOptions.from(parse("reduce /root/db --field x " + flags));
+    String mode = flags.contains("--group-by") ? "" : " --group-by entity";
+    return ReductionOptions.from(parse("stats /root/db -m x" + mode + " " + 
flags));
   }
 
   private List<FsColumn> schema() {
@@ -70,9 +71,10 @@ public class FsReductionTest {
   public void rejectsUnusedGridPathAndSubmillisecondOrigin() {
     for (String command :
         Arrays.asList(
-            "windows /root/db --start 0 --end 10 --origin 0 --width 1",
-            "windows --start 0 --end 10 --origin 1970-01-01T00:00:00.0001Z 
--width 1",
-            "reduce /root/db --field x --windows ''")) {
+            "windows --start 0 --end 10 --origin 0 --width 1",
+            "reduce /root/db --field x --aggregates delta",
+            "stats /root/db -m x --start 0 --end 10 --origin 
1970-01-01T00:00:00.0001Z --width 1",
+            "stats /root/db -m x --aggregates delta --windows ''")) {
       assertEquals(
           FilesystemCommand.Type.INVALID, 
FilesystemCommandParser.parse(command).getType());
     }
@@ -130,7 +132,7 @@ public class FsReductionTest {
             "--start 0 --end 10 --origin 0 --width 0"))
       assertEquals(
           FilesystemCommand.Type.INVALID,
-          FilesystemCommandParser.parse("windows " + flags).getType());
+          FilesystemCommandParser.parse("stats /root/db -m x " + 
flags).getType());
   }
 
   @Test
@@ -140,7 +142,7 @@ public class FsReductionTest {
             "tree",
             "/root/db",
             options(
-                "--group-by pooled --metrics 
count,sum,avg,delta,first,last,elapsed_ms,rate_per_ms"));
+                "--group-by pooled --aggregates 
count,sum,avg,delta,first,last,elapsed_ms,rate_per_ms"));
     feed(e, "root.db.b", SqlRow.of("time", "10", "x", "90"));
     feed(
         e,
@@ -162,7 +164,7 @@ public class FsReductionTest {
   public void entityGrainNullTagsAndDuplicateWindows() throws Exception {
     FsReduction e =
         new FsReduction(
-            "table", "db.t", options("--windows 0:10,0:10,20:30 --metrics 
count,delta"));
+            "table", "db.t", options("--windows 0:10,0:10,20:30 --aggregates 
count,delta"));
     feed(
         e,
         "db.t",
@@ -183,11 +185,11 @@ public class FsReductionTest {
         new FsReduction(
             "tree",
             "/root/db",
-            options("--metrics avg --rank-by avg --top 2 --windows 
0:10,20:30"));
+            options("--aggregates avg --sort-by avg --windows 0:10,20:30"));
     feed(e, "b", SqlRow.of("time", "0", "x", "5"), SqlRow.of("time", "20", 
"x", "6"));
     feed(e, "a", SqlRow.of("time", "0", "x", "5"), SqlRow.of("time", "20", 
"x", "6"));
     List<SqlRow> r = e.finish();
-    assertEquals(2, r.size());
+    assertEquals(4, r.size());
     assertEquals("a", r.get(0).get("object"));
     assertEquals("1", r.get(0).get("window_index"));
     assertEquals("2", r.get(1).get("rank"));
@@ -196,7 +198,7 @@ public class FsReductionTest {
   @Test
   public void endpointDifferenceAndSpanAvoidInt64Overflow() throws Exception {
     FsReduction e =
-        new FsReduction("tree", "x", options("--metrics 
first,last,delta,elapsed_ms,rate_per_ms"));
+        new FsReduction("tree", "x", options("--aggregates 
first,last,delta,elapsed_ms,rate_per_ms"));
     feed(
         e,
         "a",
@@ -212,7 +214,7 @@ public class FsReductionTest {
   public void zeroSpanNullLastAndAscendingRank() throws Exception {
     FsReduction e =
         new FsReduction(
-            "tree", "x", options("--metrics delta,rate_per_ms --rank-by 
rate_per_ms --order asc"));
+            "tree", "x", options("--aggregates delta,rate_per_ms --sort-by 
rate_per_ms --order asc"));
     feed(e, "a", SqlRow.of("time", "0", "x", "3"));
     feed(e, "b", SqlRow.of("time", "0", "x", "4"), SqlRow.of("time", "2", "x", 
"2"));
     List<SqlRow> r = e.finish();
@@ -231,13 +233,13 @@ public class FsReductionTest {
     }
     for (String flags :
         Arrays.asList(
-            "--metrics avg --rank-by delta",
+            "--aggregates avg --sort-by delta",
             "--group-by unknown",
-            "--metrics count,count",
+            "--aggregates count,count",
             "--top 2",
             "--origin 0 --width 1"))
       assertEquals(
           FilesystemCommand.Type.INVALID,
-          FilesystemCommandParser.parse("reduce /root/db --field x " + 
flags).getType());
+          FilesystemCommandParser.parse("stats /root/db -m x " + 
flags).getType());
   }
 }

Reply via email to