You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by "capistrant (via GitHub)" <gi...@apache.org> on 2026/02/25 01:57:20 UTC

[PR] Reindexing timeline UI (druid)

capistrant opened a new pull request, #19051:
URL: https://github.com/apache/druid/pull/19051

   <!-- Thanks for trying to help us make Apache Druid be the best it can be! Please fill out as much of the following information as is possible (where relevant, and remove it when irrelevant) to help make the intention and scope of this PR clear in order to ease review. -->
   
   <!-- Please read the doc for contribution (https://github.com/apache/druid/blob/master/CONTRIBUTING.md) before making this PR. Also, once you open a PR, please _avoid using force pushes and rebasing_ since these make it difficult for reviewers to see what you've changed in response to their reviews. See [the 'If your pull request shows conflicts with master' section](https://github.com/apache/druid/blob/master/CONTRIBUTING.md#if-your-pull-request-shows-conflicts-with-master) for more details. -->
   
   <!-- Replace XXXX with the id of the issue fixed in this PR. Remove this section if there is no corresponding issue. Don't reference the issue in the title of this pull-request. -->
   
   <!-- If you are a committer, follow the PR action item checklist for committers:
   https://github.com/apache/druid/blob/master/dev/committer-instructions.md#pr-and-issue-action-item-checklist-for-committers. -->
   
   ### Description
   
   <!-- Describe the goal of this PR, what problem are you fixing. If there is a corresponding issue (referenced above), it's not necessary to repeat the description here, however, you may choose to keep one summary sentence. -->
   
   <!-- Describe your patch: what did you change in code? How did you fix the problem? -->
   
   <!-- If there are several relatively logically separate changes in this PR, create a mini-section for each of them. For example: -->
   
   #### New Supervisor API (cascading reindexing supervisors only)
   
   ```
   GET /druid/indexer/v1/supervisor/{supervisorId}/reindexingTimeline
   ```
   
   This generates a timeline of search intervals for reindexing with the effective sets of rules that are used to create the underlying inline compaction configs for the different intervals. This is the business end of the console UI described below
   
   #### Console visualization of reindexing timeline (cascading reindexing supervisors only)
   
   For cascading compaction supervisors you can get a timeline view of how rules from the rule provider(s) will apply to your datasource. You can view how skip offsets (if they are configured) will change the timeline too. This visualization is a great help for operators in understanding in how their underlying rules will be applied across the datasource history. I will add some screen shots for reference
   
   <img width="1550" height="731" alt="image" src="https://github.com/user-attachments/assets/90c46174-f473-4bb5-934e-dd56dfedac20" />
   
   <img width="1581" height="746" alt="image" src="https://github.com/user-attachments/assets/c5b96afb-d672-4547-a58f-8790fcd52a63" />
   
   <img width="1592" height="741" alt="image" src="https://github.com/user-attachments/assets/1156217a-841e-4125-af2e-737ffac30461" />
   
   
   #### Refactor `CompactionSupervisorTest` Embedded Tests
   
   Split out the cascading template tests to their own class from the inline compaction supervisor tests. Sharing one file was getting convoluted. They share a base class for what makes sense.
   
   <!--
   In each section, please describe design decisions made, including:
    - Choice of algorithms
    - Behavioral aspects. What configuration values are acceptable? How are corner cases and error conditions handled, such as when there are insufficient resources?
    - Class organization and design (how the logic is split between classes, inheritance, composition, design patterns)
    - Method organization and design (how the logic is split between methods, parameters and return types)
    - Naming (class, method, API, configuration, HTTP endpoint, names of emitted metrics)
   -->
   
   
   <!-- It's good to describe an alternative design (or mention an alternative name) for every design (or naming) decision point and compare the alternatives with the designs that you've implemented (or the names you've chosen) to highlight the advantages of the chosen designs and names. -->
   
   <!-- If there was a discussion of the design of the feature implemented in this PR elsewhere (e. g. a "Proposal" issue, any other issue, or a thread in the development mailing list), link to that discussion from this PR description and explain what have changed in your final design compared to your original proposal or the consensus version in the end of the discussion. If something hasn't changed since the original discussion, you can omit a detailed discussion of those aspects of the design here, perhaps apart from brief mentioning for the sake of readability of this PR description. -->
   
   <!-- Some of the aspects mentioned above may be omitted for simple and small changes. -->
   
   #### Release note
   <!-- Give your best effort to summarize your changes in a couple of sentences aimed toward Druid users. 
   
   If your change doesn't have end user impact, you can skip this section.
   
   For tips about how to write a good release note, see [Release notes](https://github.com/apache/druid/blob/master/CONTRIBUTING.md#release-notes).
   
   -->
   
   
   <hr>
   
   ##### Key changed/added classes in this PR
    * `CascadingReindexingTemplate`
    * `ReindexingTimelineView`
    * `SupervisorResource`
    * `web-console/src/components/reindexing-timeline/reindexing-timeline.scss`
   
   <hr>
   
   <!-- Check the items by putting "x" in the brackets for the done things. Not all of these items apply to every PR. Remove the items which are not done or not relevant to the PR. None of the items from the checklist below are strictly necessary, but it would be very helpful if you at least self-review the PR. -->
   
   This PR has:
   
   - [ ] been self-reviewed.
   - [ ] added documentation for new or modified features or behaviors.
   - [ ] a release note entry in the PR description.
   - [ ] added Javadocs for most classes and all non-trivial methods. Linked related entities via Javadoc links.
   - [ ] added or updated version, license, or notice information in [licenses.yaml](https://github.com/apache/druid/blob/master/dev/license.md)
   - [ ] added comments explaining the "why" and the intent of the code wherever would not be obvious for an unfamiliar reader.
   - [ ] added unit tests or modified existing tests to cover new code paths, ensuring the threshold for [code coverage](https://github.com/apache/druid/blob/master/dev/code-review/code-coverage.md) is met.
   - [ ] added integration tests.
   - [ ] been tested in a test Druid cluster.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "vogievetsky (via GitHub)" <gi...@apache.org>.
vogievetsky commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3244858276


##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);
+      const result = resp.data;
+      if (result && result.length > 0 && result[0].result) {
+        const maxTime = result[0].result.maxTime;
+        setQueriedMaxTime(maxTime);
+      } else {
+        AppToaster.show({
+          message: 'No data found in datasource',
+          intent: Intent.WARNING,
+        });
+      }
+    } catch (e) {
+      AppToaster.show({
+        message: `Failed to query max time: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+    } finally {
+      setQueryingMaxTime(false);
+    }
+  };
+
+  // Calculate effective end time if we have queried max time and skipOffsetFromLatest
+  let effectiveEndTime: Date | undefined;
+  if (queriedMaxTime && skipOffset && !skipOffset.isApplied) {
+    const period = skipOffset.period;
+    try {
+      const duration = new Duration(period);
+      effectiveEndTime = duration.shift(new Date(queriedMaxTime), Timezone.UTC, -1);
+    } catch (e) {
+      console.error('Failed to parse skip offset period:', period, e);
+      AppToaster.show({
+        message: `Invalid skip offset period format: ${period}`,
+        intent: Intent.WARNING,
+      });
+    }
+  }
+
+  // Display validation error if present
+  if (validationError) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Invalid Supervisor Configuration">
+          <p>
+            <strong>
+              The segment granularity rule definitions have created an illegal segment granularity
+              timeline.
+            </strong>
+          </p>
+          {validationError.errorType === 'INVALID_GRANULARITY_TIMELINE' &&
+            validationError.olderInterval && (
+              <>
+                <p>
+                  Segment granularity must stay the same or become <strong>coarser</strong> as data
+                  ages from present to past. Your configuration violates this constraint:
+                </p>
+                <ul>
+                  <li>
+                    <strong>Older interval</strong> (further in the past):{' '}
+                    <code>{formatInterval(validationError.olderInterval)}</code> has{' '}
+                    <strong>finer</strong> granularity:{' '}
+                    <Tag intent={Intent.PRIMARY}>{validationError.olderGranularity}</Tag>
+                  </li>
+                  <li>
+                    <strong>Newer interval</strong> (more recent):{' '}
+                    <code>{formatInterval(validationError.newerInterval!)}</code> has{' '}
+                    <strong>coarser</strong> granularity:{' '}
+                    <Tag intent={Intent.WARNING}>{validationError.newerGranularity}</Tag>
+                  </li>
+                </ul>
+                <p>
+                  <strong>To fix this:</strong> Adjust your segment granularity rules so that as
+                  time moves from present to past, the granularity either stays the same or gets
+                  coarser (e.g., HOUR → DAY → MONTH → YEAR).
+                </p>
+              </>
+            )}
+          {validationError.errorType !== 'INVALID_GRANULARITY_TIMELINE' && (
+            <p>{validationError.message}</p>
+          )}
+        </Callout>
+      </div>
+    );
+  }
+
+  if (intervals.length === 0) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.WARNING}>
+          No reindexing intervals found. This may indicate that the rule provider is not ready or no
+          rules are configured.
+        </Callout>
+      </div>
+    );
+  }
+
+  const selectedInterval =
+    selectedIntervalIndex !== undefined ? intervals[selectedIntervalIndex] : undefined;
+
+  return (
+    <div className="reindexing-timeline">
+      <div className="timeline-header">
+        <div className="header-info">
+          <strong>DataSource:</strong> {timelineData.dataSource}
+          <span className="spacer">|</span>
+          <Tooltip
+            content="The reference time used in conjunction with each rule's 'olderThan' attribute to calculate which intervals a rule should apply to."
+            position="bottom"
+          >
+            <strong className="help-hint">Reference Time:</strong>
+          </Tooltip>{' '}
+          {formatDateTimeUTC(referenceTime)}
+        </div>
+        {skipOffset && (
+          <div className="skip-offset-info">
+            {skipOffset.isApplied && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                Skip Offset: {skipOffset.type} ({skipOffset.period})
+              </Tag>
+            )}
+            {!skipOffset.isApplied && !queriedMaxTime && (
+              <>
+                <Tooltip
+                  content={
+                    `This supervisor is configured to skip compaction of any search interval that is covered by ` +
+                    `or overlaps the threshold of the latest timestamp in the data minus ${skipOffset.period}. ` +
+                    `However, the underlying segment data is not available in this preview, so the timeline does not ` +
+                    `reflect which intervals will be skipped during actual compaction.`
+                  }
+                  position="bottom"
+                >
+                  <Tag minimal intent={Intent.WARNING} icon={IconNames.WARNING_SIGN}>
+                    {skipOffset.type} ({skipOffset.period}): Not reflected in this preview
+                  </Tag>
+                </Tooltip>
+                <Button
+                  text="Query latest timestamp"
+                  icon={IconNames.REFRESH}
+                  small
+                  onClick={() => void handleQueryMaxTime()}
+                  loading={queryingMaxTime}
+                  className="query-button"
+                />
+              </>
+            )}
+            {!skipOffset.isApplied && queriedMaxTime && effectiveEndTime && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                {skipOffset.type} ({skipOffset.period}): Applied (latest:{' '}
+                {formatDateTimeUTC(queriedMaxTime)})
+              </Tag>
+            )}
+          </div>
+        )}
+      </div>
+
+      <Card className="timeline-bar-container">
+        <div className="timeline-bar" role="toolbar" aria-label="Reindexing timeline intervals">
+          {intervals.map((interval, idx) => {
+            const [start, end] = interval.interval.split('/');
+            const isSelected = selectedIntervalIndex === idx;
+
+            // Check if interval is skipped due to skip offset (either from API or from queried max time)
+            let isSkipped = interval.ruleCount === 0;
+            if (!isSkipped && effectiveEndTime) {
+              const intervalEnd = new Date(end);
+              isSkipped = intervalEnd > effectiveEndTime;
+            }
+
+            return (
+              <div
+                key={interval.interval}
+                className={`timeline-segment ${isSelected ? 'selected' : ''} ${
+                  isSkipped ? 'skipped' : ''
+                }`}
+                style={{
+                  backgroundColor: isSkipped ? SKIPPED_INTERVAL_COLOR : getIntervalColor(idx),
+                  flex: 1,
+                }}
+                role={isSkipped ? undefined : 'button'}
+                tabIndex={isSkipped ? undefined : 0}
+                aria-label={
+                  isSkipped
+                    ? `Skipped interval ${interval.interval}`
+                    : `Interval ${interval.interval} with ${interval.ruleCount} rule${
+                        interval.ruleCount !== 1 ? 's' : ''
+                      }`
+                }
+                aria-selected={isSelected}
+                onClick={() => !isSkipped && setSelectedIntervalIndex(idx)}
+                onKeyDown={e => {
+                  if (!isSkipped && (e.key === 'Enter' || e.key === ' ')) {
+                    e.preventDefault();
+                    setSelectedIntervalIndex(idx);
+                  }
+                }}
+                title={
+                  isSkipped
+                    ? `${interval.interval}\nSkipped (beyond skip offset)`
+                    : `${interval.interval}\n${interval.ruleCount} rule(s) applied`
+                }
+              >
+                <div className="segment-label">
+                  <div className="segment-date">{formatDateShort(start)}</div>
+                  <div className="segment-date">{formatDateShort(end)}</div>
+                  <div className="segment-rules">
+                    <Tag minimal intent={isSkipped ? Intent.DANGER : undefined}>
+                      {isSkipped
+                        ? 'skipped'
+                        : `${interval.ruleCount} rule${interval.ruleCount !== 1 ? 's' : ''}`}
+                    </Tag>
+                  </div>
+                </div>
+              </div>
+            );
+          })}
+        </div>
+        <div className="timeline-hint">Click on an interval to view its configuration details</div>
+      </Card>
+
+      {selectedInterval && selectedInterval.ruleCount > 0 && (
+        <IntervalDetailPanel
+          interval={selectedInterval}
+          onClose={() => setSelectedIntervalIndex(undefined)}
+        />
+      )}
+    </div>
+  );
+});
+
+function formatDateShort(isoDate: string): string {
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  const d = new Date(isoDate);
+  return `${UTC_MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
+}
+
+const UTC_MONTH_NAMES = [
+  'Jan',
+  'Feb',
+  'Mar',
+  'Apr',
+  'May',
+  'Jun',
+  'Jul',
+  'Aug',
+  'Sep',
+  'Oct',
+  'Nov',
+  'Dec',
+];
+
+function formatDateTimeUTC(isoDate: string): string {
+  // Handle start of time / very old dates
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  // Format using UTC methods to avoid local timezone shifting.
+  // date-fns format() uses the browser's local timezone, so we extract UTC
+  // components manually to ensure the displayed time is actually UTC.
+  const d = new Date(isoDate);
+  const month = UTC_MONTH_NAMES[d.getUTCMonth()];
+  const day = d.getUTCDate();
+  const year = d.getUTCFullYear();
+  const hours = d.getUTCHours();
+  const minutes = String(d.getUTCMinutes()).padStart(2, '0');
+  const ampm = hours >= 12 ? 'PM' : 'AM';
+  const displayHours = hours % 12 || 12;
+  return `${month} ${day}, ${year} ${displayHours}:${minutes} ${ampm} UTC`;
+}
+
+function formatInterval(interval: string): string {
+  const [start, end] = interval.split('/');
+  const formattedStart = start.startsWith('-') ? '-INF' : start;
+  const formattedEnd = end ? end : 'now';
+  return `${formattedStart}/${formattedEnd}`;
+}
+
+function handleCopyToClipboard(data: CompactionConfig | ReindexingRule[], label: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  copy(jsonValue, { format: 'text/plain' });
+  AppToaster.show({
+    message: `${label} copied to clipboard`,
+    intent: Intent.SUCCESS,
+  });
+}
+
+function handleDownloadJson(data: CompactionConfig | ReindexingRule[], filename: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  downloadFile(jsonValue, 'json', filename);
+}
+
+function getPartitionType(tuningConfig: Record<string, unknown> | undefined): string | undefined {
+  if (!tuningConfig) return undefined;
+  const partitionsSpec = tuningConfig.partitionsSpec;
+  if (partitionsSpec && typeof partitionsSpec === 'object' && partitionsSpec !== null) {
+    return (partitionsSpec as Record<string, unknown>).type as string | undefined;
+  }
+  return undefined;
+}
+
+interface IntervalDetailPanelProps {
+  interval: IntervalConfig;
+  onClose: () => void;
+}
+
+function IntervalDetailPanel({ interval, onClose }: IntervalDetailPanelProps) {
+  const [showFullConfig, setShowFullConfig] = useState(false);
+  const [showRawRules, setShowRawRules] = useState(false);
+  const { config } = interval;
+
+  const deletionRuleCount = interval.appliedRules.filter(r => r.type === 'deletion').length;
+  const metricsCount = config.metricsSpec?.length || 0;
+  const dimensionsCount = config.dimensionsSpec?.dimensions?.length || 0;
+  const projectionsCount = config.projections?.length || 0;
+
+  return (
+    <>
+      <Card className="interval-detail-panel">
+        <div className="detail-header">
+          <div>
+            <h3>Interval: {formatInterval(interval.interval)}</h3>
+          </div>
+          <Button
+            icon={IconNames.CROSS}
+            minimal
+            onClick={onClose}
+            aria-label="Close interval details"
+          />
+        </div>
+
+        <div className="detail-content">
+          <Tooltip
+            content="A high-level summary of the merged rule configuration for this interval — use View Full Configuration for complete details."
+            position="bottom"
+          >

Review Comment:
   Web console does not really use `<Tooltip>` it is more extreme! Search for `data-label`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "vogievetsky (via GitHub)" <gi...@apache.org>.
vogievetsky commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3244896710


##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);
+      const result = resp.data;
+      if (result && result.length > 0 && result[0].result) {
+        const maxTime = result[0].result.maxTime;
+        setQueriedMaxTime(maxTime);
+      } else {
+        AppToaster.show({
+          message: 'No data found in datasource',
+          intent: Intent.WARNING,
+        });
+      }
+    } catch (e) {
+      AppToaster.show({
+        message: `Failed to query max time: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+    } finally {
+      setQueryingMaxTime(false);
+    }
+  };
+
+  // Calculate effective end time if we have queried max time and skipOffsetFromLatest
+  let effectiveEndTime: Date | undefined;
+  if (queriedMaxTime && skipOffset && !skipOffset.isApplied) {
+    const period = skipOffset.period;
+    try {
+      const duration = new Duration(period);
+      effectiveEndTime = duration.shift(new Date(queriedMaxTime), Timezone.UTC, -1);
+    } catch (e) {
+      console.error('Failed to parse skip offset period:', period, e);
+      AppToaster.show({
+        message: `Invalid skip offset period format: ${period}`,
+        intent: Intent.WARNING,
+      });
+    }
+  }
+
+  // Display validation error if present
+  if (validationError) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Invalid Supervisor Configuration">
+          <p>
+            <strong>
+              The segment granularity rule definitions have created an illegal segment granularity
+              timeline.
+            </strong>
+          </p>
+          {validationError.errorType === 'INVALID_GRANULARITY_TIMELINE' &&
+            validationError.olderInterval && (
+              <>
+                <p>
+                  Segment granularity must stay the same or become <strong>coarser</strong> as data
+                  ages from present to past. Your configuration violates this constraint:
+                </p>
+                <ul>
+                  <li>
+                    <strong>Older interval</strong> (further in the past):{' '}
+                    <code>{formatInterval(validationError.olderInterval)}</code> has{' '}
+                    <strong>finer</strong> granularity:{' '}
+                    <Tag intent={Intent.PRIMARY}>{validationError.olderGranularity}</Tag>
+                  </li>
+                  <li>
+                    <strong>Newer interval</strong> (more recent):{' '}
+                    <code>{formatInterval(validationError.newerInterval!)}</code> has{' '}
+                    <strong>coarser</strong> granularity:{' '}
+                    <Tag intent={Intent.WARNING}>{validationError.newerGranularity}</Tag>
+                  </li>
+                </ul>
+                <p>
+                  <strong>To fix this:</strong> Adjust your segment granularity rules so that as
+                  time moves from present to past, the granularity either stays the same or gets
+                  coarser (e.g., HOUR → DAY → MONTH → YEAR).
+                </p>
+              </>
+            )}
+          {validationError.errorType !== 'INVALID_GRANULARITY_TIMELINE' && (
+            <p>{validationError.message}</p>
+          )}
+        </Callout>
+      </div>
+    );
+  }
+
+  if (intervals.length === 0) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.WARNING}>
+          No reindexing intervals found. This may indicate that the rule provider is not ready or no
+          rules are configured.
+        </Callout>
+      </div>
+    );
+  }
+
+  const selectedInterval =
+    selectedIntervalIndex !== undefined ? intervals[selectedIntervalIndex] : undefined;
+
+  return (
+    <div className="reindexing-timeline">
+      <div className="timeline-header">
+        <div className="header-info">
+          <strong>DataSource:</strong> {timelineData.dataSource}
+          <span className="spacer">|</span>
+          <Tooltip
+            content="The reference time used in conjunction with each rule's 'olderThan' attribute to calculate which intervals a rule should apply to."
+            position="bottom"
+          >
+            <strong className="help-hint">Reference Time:</strong>
+          </Tooltip>{' '}
+          {formatDateTimeUTC(referenceTime)}
+        </div>
+        {skipOffset && (
+          <div className="skip-offset-info">
+            {skipOffset.isApplied && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                Skip Offset: {skipOffset.type} ({skipOffset.period})
+              </Tag>
+            )}
+            {!skipOffset.isApplied && !queriedMaxTime && (
+              <>
+                <Tooltip
+                  content={
+                    `This supervisor is configured to skip compaction of any search interval that is covered by ` +
+                    `or overlaps the threshold of the latest timestamp in the data minus ${skipOffset.period}. ` +
+                    `However, the underlying segment data is not available in this preview, so the timeline does not ` +
+                    `reflect which intervals will be skipped during actual compaction.`
+                  }
+                  position="bottom"
+                >
+                  <Tag minimal intent={Intent.WARNING} icon={IconNames.WARNING_SIGN}>
+                    {skipOffset.type} ({skipOffset.period}): Not reflected in this preview
+                  </Tag>
+                </Tooltip>
+                <Button
+                  text="Query latest timestamp"
+                  icon={IconNames.REFRESH}
+                  small
+                  onClick={() => void handleQueryMaxTime()}
+                  loading={queryingMaxTime}
+                  className="query-button"
+                />
+              </>
+            )}
+            {!skipOffset.isApplied && queriedMaxTime && effectiveEndTime && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                {skipOffset.type} ({skipOffset.period}): Applied (latest:{' '}
+                {formatDateTimeUTC(queriedMaxTime)})
+              </Tag>
+            )}
+          </div>
+        )}
+      </div>
+
+      <Card className="timeline-bar-container">
+        <div className="timeline-bar" role="toolbar" aria-label="Reindexing timeline intervals">
+          {intervals.map((interval, idx) => {
+            const [start, end] = interval.interval.split('/');
+            const isSelected = selectedIntervalIndex === idx;
+
+            // Check if interval is skipped due to skip offset (either from API or from queried max time)
+            let isSkipped = interval.ruleCount === 0;
+            if (!isSkipped && effectiveEndTime) {
+              const intervalEnd = new Date(end);
+              isSkipped = intervalEnd > effectiveEndTime;
+            }
+
+            return (
+              <div
+                key={interval.interval}
+                className={`timeline-segment ${isSelected ? 'selected' : ''} ${
+                  isSkipped ? 'skipped' : ''
+                }`}
+                style={{
+                  backgroundColor: isSkipped ? SKIPPED_INTERVAL_COLOR : getIntervalColor(idx),
+                  flex: 1,
+                }}
+                role={isSkipped ? undefined : 'button'}
+                tabIndex={isSkipped ? undefined : 0}
+                aria-label={
+                  isSkipped
+                    ? `Skipped interval ${interval.interval}`
+                    : `Interval ${interval.interval} with ${interval.ruleCount} rule${
+                        interval.ruleCount !== 1 ? 's' : ''
+                      }`
+                }
+                aria-selected={isSelected}
+                onClick={() => !isSkipped && setSelectedIntervalIndex(idx)}
+                onKeyDown={e => {
+                  if (!isSkipped && (e.key === 'Enter' || e.key === ' ')) {
+                    e.preventDefault();
+                    setSelectedIntervalIndex(idx);
+                  }
+                }}
+                title={
+                  isSkipped
+                    ? `${interval.interval}\nSkipped (beyond skip offset)`
+                    : `${interval.interval}\n${interval.ruleCount} rule(s) applied`
+                }
+              >
+                <div className="segment-label">
+                  <div className="segment-date">{formatDateShort(start)}</div>
+                  <div className="segment-date">{formatDateShort(end)}</div>
+                  <div className="segment-rules">
+                    <Tag minimal intent={isSkipped ? Intent.DANGER : undefined}>
+                      {isSkipped
+                        ? 'skipped'
+                        : `${interval.ruleCount} rule${interval.ruleCount !== 1 ? 's' : ''}`}
+                    </Tag>
+                  </div>
+                </div>
+              </div>
+            );
+          })}
+        </div>
+        <div className="timeline-hint">Click on an interval to view its configuration details</div>
+      </Card>
+
+      {selectedInterval && selectedInterval.ruleCount > 0 && (
+        <IntervalDetailPanel
+          interval={selectedInterval}
+          onClose={() => setSelectedIntervalIndex(undefined)}
+        />
+      )}
+    </div>
+  );
+});
+
+function formatDateShort(isoDate: string): string {
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  const d = new Date(isoDate);
+  return `${UTC_MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
+}
+
+const UTC_MONTH_NAMES = [
+  'Jan',
+  'Feb',
+  'Mar',
+  'Apr',
+  'May',
+  'Jun',
+  'Jul',
+  'Aug',
+  'Sep',
+  'Oct',
+  'Nov',
+  'Dec',
+];
+
+function formatDateTimeUTC(isoDate: string): string {
+  // Handle start of time / very old dates
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  // Format using UTC methods to avoid local timezone shifting.
+  // date-fns format() uses the browser's local timezone, so we extract UTC
+  // components manually to ensure the displayed time is actually UTC.
+  const d = new Date(isoDate);
+  const month = UTC_MONTH_NAMES[d.getUTCMonth()];
+  const day = d.getUTCDate();
+  const year = d.getUTCFullYear();
+  const hours = d.getUTCHours();
+  const minutes = String(d.getUTCMinutes()).padStart(2, '0');
+  const ampm = hours >= 12 ? 'PM' : 'AM';
+  const displayHours = hours % 12 || 12;
+  return `${month} ${day}, ${year} ${displayHours}:${minutes} ${ampm} UTC`;
+}
+
+function formatInterval(interval: string): string {
+  const [start, end] = interval.split('/');
+  const formattedStart = start.startsWith('-') ? '-INF' : start;
+  const formattedEnd = end ? end : 'now';
+  return `${formattedStart}/${formattedEnd}`;
+}
+
+function handleCopyToClipboard(data: CompactionConfig | ReindexingRule[], label: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  copy(jsonValue, { format: 'text/plain' });
+  AppToaster.show({
+    message: `${label} copied to clipboard`,
+    intent: Intent.SUCCESS,
+  });
+}
+
+function handleDownloadJson(data: CompactionConfig | ReindexingRule[], filename: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  downloadFile(jsonValue, 'json', filename);
+}
+
+function getPartitionType(tuningConfig: Record<string, unknown> | undefined): string | undefined {
+  if (!tuningConfig) return undefined;
+  const partitionsSpec = tuningConfig.partitionsSpec;
+  if (partitionsSpec && typeof partitionsSpec === 'object' && partitionsSpec !== null) {
+    return (partitionsSpec as Record<string, unknown>).type as string | undefined;
+  }
+  return undefined;
+}
+
+interface IntervalDetailPanelProps {
+  interval: IntervalConfig;
+  onClose: () => void;
+}
+
+function IntervalDetailPanel({ interval, onClose }: IntervalDetailPanelProps) {
+  const [showFullConfig, setShowFullConfig] = useState(false);
+  const [showRawRules, setShowRawRules] = useState(false);
+  const { config } = interval;
+
+  const deletionRuleCount = interval.appliedRules.filter(r => r.type === 'deletion').length;
+  const metricsCount = config.metricsSpec?.length || 0;
+  const dimensionsCount = config.dimensionsSpec?.dimensions?.length || 0;
+  const projectionsCount = config.projections?.length || 0;
+
+  return (
+    <>
+      <Card className="interval-detail-panel">
+        <div className="detail-header">
+          <div>
+            <h3>Interval: {formatInterval(interval.interval)}</h3>
+          </div>
+          <Button
+            icon={IconNames.CROSS}
+            minimal
+            onClick={onClose}
+            aria-label="Close interval details"
+          />
+        </div>
+
+        <div className="detail-content">
+          <Tooltip
+            content="A high-level summary of the merged rule configuration for this interval — use View Full Configuration for complete details."
+            position="bottom"
+          >
+            <div className="config-summary-label">Effective Configuration</div>
+          </Tooltip>
+          <div className="config-badges">
+            {config.granularitySpec?.segmentGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.CALENDAR}>
+                Segment: {config.granularitySpec.segmentGranularity}
+              </Tag>
+            )}
+            {config.granularitySpec?.queryGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.TIME}>
+                Query: {config.granularitySpec.queryGranularity}
+              </Tag>
+            )}
+            {getPartitionType(config.tuningConfig) && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.SPLIT_COLUMNS}>
+                Partitioning: {getPartitionType(config.tuningConfig)}
+              </Tag>
+            )}
+            {metricsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CALCULATOR}>
+                {metricsCount} metric{metricsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {dimensionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TAG}>
+                {dimensionsCount} dimension{dimensionsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {projectionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CUBE}>
+                {projectionsCount} projection{projectionsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {deletionRuleCount > 0 && (
+              <Tag minimal intent={Intent.WARNING} icon={IconNames.TRASH}>
+                {deletionRuleCount} deletion clause{deletionRuleCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+          </div>
+
+          <div className="full-config-section">
+            <Button
+              icon={IconNames.CODE}
+              text="View Full Configuration"
+              intent={Intent.PRIMARY}
+              onClick={() => setShowFullConfig(true)}
+            />
+            <Button
+              icon={IconNames.PROPERTIES}
+              text={`View ${interval.ruleCount} Raw Rule${interval.ruleCount !== 1 ? 's' : ''}`}
+              intent={Intent.PRIMARY}
+              onClick={() => setShowRawRules(true)}
+            />
+          </div>
+        </div>
+      </Card>
+
+      <Dialog
+        isOpen={showFullConfig}
+        onClose={() => setShowFullConfig(false)}
+        title={
+          <Tooltip content={interval.interval} position="bottom">
+            <span>{formatInterval(interval.interval)}</span>
+          </Tooltip>
+        }
+        className="reindexing-config-dialog"
+        canOutsideClickClose
+      >
+        <div className="bp5-dialog-body">
+          <ConfigJsonViewer config={config} />
+        </div>
+        <div className="bp5-dialog-footer">
+          <div className="bp5-dialog-footer-actions">
+            <Button
+              text="Copy"
+              icon={IconNames.DUPLICATE}
+              intent={Intent.PRIMARY}
+              onClick={() => handleCopyToClipboard(config, 'Configuration')}
+            />
+            <Button
+              text="Download"
+              icon={IconNames.DOWNLOAD}
+              intent={Intent.PRIMARY}
+              onClick={() =>
+                handleDownloadJson(
+                  config,
+                  `reindexing-config-${interval.interval.replace(/\//g, '-')}.json`,
+                )
+              }
+            />
+          </div>
+        </div>
+      </Dialog>
+
+      <Dialog
+        isOpen={showRawRules}
+        onClose={() => setShowRawRules(false)}
+        title={
+          <Tooltip
+            content={`${interval.appliedRules.length} rules for ${interval.interval}`}
+            position="bottom"
+          >
+            <span>Rules for {formatInterval(interval.interval)}</span>
+          </Tooltip>
+        }
+        className="reindexing-config-dialog"
+        canOutsideClickClose
+      >
+        <div className="bp5-dialog-body">

Review Comment:
   doing `className="bp5-dialog-body"` is an anti-pattern prefer `className={Classes.DIALOG_BODY}` instead



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Cascading Reindexing Supervisor UI component fore viewing timeline of rule applications (druid)

Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r2850726494


##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorResource.java:
##########
@@ -351,6 +357,80 @@ public Response getAllTaskStats(
     );
   }
 
+  @GET
+  @Path("/{id}/reindexingTimeline")
+  @Produces(MediaType.APPLICATION_JSON)
+  @ResourceFilters(SupervisorResourceFilter.class)
+  public Response getReindexingTimeline(
+      @PathParam("id") final String id,
+      @QueryParam("referenceTime") @Nullable final String referenceTimeStr
+  )
+  {
+    return asLeaderWithSupervisorManager(
+        manager -> {
+          Optional<SupervisorSpec> specOptional = manager.getSupervisorSpec(id);
+          if (!specOptional.isPresent()) {
+            return Response.status(Response.Status.NOT_FOUND)
+                           .entity(ImmutableMap.of("error", StringUtils.format("[%s] does not exist", id)))
+                           .build();
+          }
+
+          SupervisorSpec spec = specOptional.get();
+          if (!(spec instanceof CompactionSupervisorSpec)) {
+            return Response.status(Response.Status.BAD_REQUEST)
+                           .entity(ImmutableMap.of(
+                               "error",
+                               StringUtils.format(
+                                   "[%s] is not a compaction supervisor (type: %s)",

Review Comment:
   I think we can omit reporting back the actual type of the supervisor found.
   ```suggestion
                                      "Supervisor[%s] is not a compaction supervisor",
   ```



##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/ReindexingTimelineView.java:
##########
@@ -0,0 +1,497 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.druid.indexing.compact;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonInclude;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.annotation.JsonSubTypes;
+import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import org.apache.druid.server.compaction.ReindexingDataSchemaRule;
+import org.apache.druid.server.compaction.ReindexingDeletionRule;
+import org.apache.druid.server.compaction.ReindexingIOConfigRule;
+import org.apache.druid.server.compaction.ReindexingRule;
+import org.apache.druid.server.compaction.ReindexingSegmentGranularityRule;
+import org.apache.druid.server.compaction.ReindexingTuningConfigRule;
+import org.apache.druid.server.coordinator.DataSourceCompactionConfig;
+import org.joda.time.DateTime;
+import org.joda.time.Interval;
+import org.joda.time.Period;
+
+import javax.annotation.Nullable;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+/**
+ * Represents the timeline of search intervals and their associated reindexing configurations
+ * for a cascading reindexing supervisor. This view helps operators understand how different
+ * rules are applied across time intervals.
+ */
+public class ReindexingTimelineView
+{
+  private final String dataSource;
+  private final DateTime referenceTime;
+  private final SkipOffsetInfo skipOffset;
+  private final List<IntervalConfig> intervals;
+  private final ValidationError validationError;
+
+  @JsonCreator
+  public ReindexingTimelineView(
+      @JsonProperty("dataSource") String dataSource,
+      @JsonProperty("referenceTime") DateTime referenceTime,
+      @JsonProperty("skipOffset") @Nullable SkipOffsetInfo skipOffset,
+      @JsonProperty("intervals") List<IntervalConfig> intervals,
+      @JsonProperty("validationError") @Nullable ValidationError validationError
+  )
+  {
+    this.dataSource = dataSource;
+    this.referenceTime = referenceTime;
+    this.skipOffset = skipOffset;
+    this.intervals = Collections.unmodifiableList(intervals);
+    this.validationError = validationError;
+  }
+
+  @JsonProperty
+  public String getDataSource()
+  {
+    return dataSource;
+  }
+
+  @JsonProperty
+  public DateTime getReferenceTime()
+  {
+    return referenceTime;
+  }
+
+  @JsonProperty
+  @JsonInclude(JsonInclude.Include.NON_NULL)
+  @Nullable
+  public SkipOffsetInfo getSkipOffset()
+  {
+    return skipOffset;
+  }
+
+  @JsonProperty
+  public List<IntervalConfig> getIntervals()
+  {
+    return intervals;
+  }
+
+  @JsonProperty
+  @JsonInclude(JsonInclude.Include.NON_NULL)
+  @Nullable
+  public ValidationError getValidationError()
+  {
+    return validationError;
+  }
+
+  @Override
+  public boolean equals(Object o)
+  {
+    if (this == o) {
+      return true;
+    }
+    if (o == null || getClass() != o.getClass()) {
+      return false;
+    }
+    ReindexingTimelineView that = (ReindexingTimelineView) o;
+    return Objects.equals(dataSource, that.dataSource) &&
+           Objects.equals(referenceTime, that.referenceTime) &&
+           Objects.equals(skipOffset, that.skipOffset) &&
+           Objects.equals(intervals, that.intervals) &&
+           Objects.equals(validationError, that.validationError);
+  }
+
+  @Override
+  public int hashCode()
+  {
+    return Objects.hash(dataSource, referenceTime, skipOffset, intervals, validationError);
+  }
+
+  /**
+   * Information about a validation error that occurred while building the timeline.
+   */
+  public static class ValidationError
+  {
+    private final String errorType;
+    private final String message;
+    private final String olderInterval;
+    private final String olderGranularity;
+    private final String newerInterval;
+    private final String newerGranularity;
+
+    @JsonCreator
+    public ValidationError(
+        @JsonProperty("errorType") String errorType,
+        @JsonProperty("message") String message,
+        @JsonProperty("olderInterval") @Nullable String olderInterval,
+        @JsonProperty("olderGranularity") @Nullable String olderGranularity,
+        @JsonProperty("newerInterval") @Nullable String newerInterval,
+        @JsonProperty("newerGranularity") @Nullable String newerGranularity
+    )
+    {
+      this.errorType = errorType;
+      this.message = message;
+      this.olderInterval = olderInterval;
+      this.olderGranularity = olderGranularity;
+      this.newerInterval = newerInterval;
+      this.newerGranularity = newerGranularity;
+    }
+
+    @JsonProperty
+    public String getErrorType()
+    {
+      return errorType;
+    }
+
+    @JsonProperty
+    public String getMessage()
+    {
+      return message;
+    }
+
+    @JsonProperty
+    @JsonInclude(JsonInclude.Include.NON_NULL)
+    @Nullable
+    public String getOlderInterval()
+    {
+      return olderInterval;
+    }
+
+    @JsonProperty
+    @JsonInclude(JsonInclude.Include.NON_NULL)
+    @Nullable
+    public String getOlderGranularity()
+    {
+      return olderGranularity;
+    }
+
+    @JsonProperty
+    @JsonInclude(JsonInclude.Include.NON_NULL)
+    @Nullable
+    public String getNewerInterval()
+    {
+      return newerInterval;
+    }
+
+    @JsonProperty
+    @JsonInclude(JsonInclude.Include.NON_NULL)
+    @Nullable
+    public String getNewerGranularity()
+    {
+      return newerGranularity;
+    }
+
+    @Override
+    public boolean equals(Object o)
+    {
+      if (this == o) {
+        return true;
+      }
+      if (o == null || getClass() != o.getClass()) {
+        return false;
+      }
+      ValidationError that = (ValidationError) o;
+      return Objects.equals(errorType, that.errorType) &&
+             Objects.equals(message, that.message) &&
+             Objects.equals(olderInterval, that.olderInterval) &&
+             Objects.equals(olderGranularity, that.olderGranularity) &&
+             Objects.equals(newerInterval, that.newerInterval) &&
+             Objects.equals(newerGranularity, that.newerGranularity);
+    }
+
+    @Override
+    public int hashCode()
+    {
+      return Objects.hash(errorType, message, olderInterval, olderGranularity, newerInterval, newerGranularity);
+    }
+  }
+
+  /**
+   * Information about skip offsets and whether they were applied.
+   * Exactly one of {@code applied} or {@code notApplied} must be non-null.
+   */
+  public static class SkipOffsetInfo
+  {
+    private final AppliedSkipOffset applied;
+    private final NotAppliedSkipOffset notApplied;

Review Comment:
   Nit: These two classes feel a little unnecessary. We could have just have the actual fields in the class `SkipOffsetInfo` directly: `type`, `period`, a boolean for `isApplied`, a nullable `effectiveEndTime` mutually exclusive with a nullable `errorMessage`.



##########
indexing-service/src/test/java/org/apache/druid/indexing/compact/CascadingReindexingTemplateTest.java:
##########
@@ -1507,6 +1516,323 @@ public void test_generateAlignedSearchIntervals_failsWhenOlderRuleHasFinerGranul
     );
   }
 
+  /**
+   * Comprehensive test covering:
+   * - Multiple intervals with different segment granularities
+   * - All rule types (segment gran, data schema, deletion, tuning, IO)
+   * - Non-segment-gran rules triggering interval splitting
+   * - Applied rules tracking with correct rule types in each interval
+   * - Full DataSourceCompactionConfig generation
+   * - Rule count accuracy
+   */
+  @Test
+  public void test_getReindexingTimelineView_comprehensive()
+  {
+    DateTime referenceTime = DateTimes.of("2025-02-01T00:00:00Z");
+
+    // Create rules with various periods to test interval generation and splitting
+    ReindexingSegmentGranularityRule segGran7d = new ReindexingSegmentGranularityRule(
+        "seg-gran-7d",
+        null,
+        Period.days(7),
+        Granularities.HOUR
+    );
+
+    ReindexingSegmentGranularityRule segGran30d = new ReindexingSegmentGranularityRule(
+        "seg-gran-30d",
+        null,
+        Period.days(30),
+        Granularities.DAY
+    );
+
+    // Data schema rule at P15D (will split the HOUR interval)
+    ReindexingDataSchemaRule dataSchema15d = new ReindexingDataSchemaRule(
+        "data-schema-15d",
+        null,
+        Period.days(15),
+        new UserCompactionTaskDimensionsConfig(null),
+        new AggregatorFactory[]{new CountAggregatorFactory("count")},
+        Granularities.MINUTE,
+        true,
+        null
+    );
+
+    // Deletion rules at different periods
+    ReindexingDeletionRule deletion10d = new ReindexingDeletionRule(
+        "deletion-10d",
+        null,
+        Period.days(10),
+        new EqualityFilter("country", ColumnType.STRING, "US", null),
+        null
+    );
+
+    ReindexingDeletionRule deletion20d = new ReindexingDeletionRule(
+        "deletion-20d",
+        null,
+        Period.days(20),
+        new EqualityFilter("device", ColumnType.STRING, "mobile", null),
+        null
+    );
+
+    // Tuning and IO rules
+    ReindexingTuningConfigRule tuning7d = new ReindexingTuningConfigRule(
+        "tuning-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskQueryTuningConfig(

Review Comment:
   Didn't we add a builder for this class in the previous PR?



##########
indexing-service/src/test/java/org/apache/druid/indexing/compact/CascadingReindexingTemplateTest.java:
##########
@@ -1507,6 +1516,323 @@ public void test_generateAlignedSearchIntervals_failsWhenOlderRuleHasFinerGranul
     );
   }
 
+  /**
+   * Comprehensive test covering:
+   * - Multiple intervals with different segment granularities
+   * - All rule types (segment gran, data schema, deletion, tuning, IO)
+   * - Non-segment-gran rules triggering interval splitting
+   * - Applied rules tracking with correct rule types in each interval
+   * - Full DataSourceCompactionConfig generation
+   * - Rule count accuracy
+   */
+  @Test
+  public void test_getReindexingTimelineView_comprehensive()
+  {
+    DateTime referenceTime = DateTimes.of("2025-02-01T00:00:00Z");
+
+    // Create rules with various periods to test interval generation and splitting
+    ReindexingSegmentGranularityRule segGran7d = new ReindexingSegmentGranularityRule(
+        "seg-gran-7d",
+        null,
+        Period.days(7),
+        Granularities.HOUR
+    );
+
+    ReindexingSegmentGranularityRule segGran30d = new ReindexingSegmentGranularityRule(
+        "seg-gran-30d",
+        null,
+        Period.days(30),
+        Granularities.DAY
+    );
+
+    // Data schema rule at P15D (will split the HOUR interval)
+    ReindexingDataSchemaRule dataSchema15d = new ReindexingDataSchemaRule(
+        "data-schema-15d",
+        null,
+        Period.days(15),
+        new UserCompactionTaskDimensionsConfig(null),
+        new AggregatorFactory[]{new CountAggregatorFactory("count")},
+        Granularities.MINUTE,
+        true,
+        null
+    );
+
+    // Deletion rules at different periods
+    ReindexingDeletionRule deletion10d = new ReindexingDeletionRule(
+        "deletion-10d",
+        null,
+        Period.days(10),
+        new EqualityFilter("country", ColumnType.STRING, "US", null),
+        null
+    );
+
+    ReindexingDeletionRule deletion20d = new ReindexingDeletionRule(
+        "deletion-20d",
+        null,
+        Period.days(20),
+        new EqualityFilter("device", ColumnType.STRING, "mobile", null),
+        null
+    );
+
+    // Tuning and IO rules
+    ReindexingTuningConfigRule tuning7d = new ReindexingTuningConfigRule(
+        "tuning-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskQueryTuningConfig(
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null
+        )
+    );
+
+    ReindexingIOConfigRule io7d = new ReindexingIOConfigRule(
+        "io-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskIOConfig(true)
+    );
+
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()
+                                                                  .segmentGranularityRules(List.of(segGran7d, segGran30d))
+                                                                  .dataSchemaRules(List.of(dataSchema15d))
+                                                                  .deletionRules(List.of(deletion10d, deletion20d))
+                                                                  .tuningConfigRules(List.of(tuning7d))
+                                                                  .ioConfigRules(List.of(io7d))
+                                                                  .build();
+
+    CascadingReindexingTemplate template = new CascadingReindexingTemplate(
+        "testDS",
+        null,
+        null,
+        provider,
+        null,
+        null,
+        null,
+        null,
+        Granularities.DAY
+    );
+
+    ReindexingTimelineView timeline = template.getReindexingTimelineView(referenceTime);
+
+    // Verify basic timeline properties
+    Assertions.assertEquals("testDS", timeline.getDataSource());
+    Assertions.assertEquals(referenceTime, timeline.getReferenceTime());
+    Assertions.assertNull(timeline.getValidationError());
+    Assertions.assertNull(timeline.getSkipOffset());
+
+    // Verify we have multiple intervals (splitting should occur)
+    Assertions.assertTrue(timeline.getIntervals().size() >= 2, "Expected at least 2 intervals");
+
+    // Verify each interval has correct structure
+    for (ReindexingTimelineView.IntervalConfig intervalConfig : timeline.getIntervals()) {
+      Assertions.assertNotNull(intervalConfig.getInterval());
+      Assertions.assertTrue(intervalConfig.getRuleCount() > 0, "Rule count should be > 0");
+      Assertions.assertNotNull(intervalConfig.getConfig());
+      Assertions.assertNotNull(intervalConfig.getAppliedRules());
+      Assertions.assertEquals(
+          intervalConfig.getRuleCount(),
+          intervalConfig.getAppliedRules().size(),
+          "Applied rules size should match rule count"
+      );
+
+      // Verify config has expected components
+      DataSourceCompactionConfig config = intervalConfig.getConfig();
+      Assertions.assertNotNull(config.getGranularitySpec(), "Should have granularity spec");
+      Assertions.assertNotNull(config.getGranularitySpec().getSegmentGranularity(), "Should have segment granularity");
+
+      // Verify appliedRules contain expected rule types
+      boolean hasTuningRule = intervalConfig.getAppliedRules().stream()
+                                            .anyMatch(r -> r instanceof ReindexingTuningConfigRule);
+      boolean hasIORule = intervalConfig.getAppliedRules().stream()
+                                        .anyMatch(r -> r instanceof ReindexingIOConfigRule);
+      boolean hasDataSchemaRule = intervalConfig.getAppliedRules().stream()
+                                                .anyMatch(r -> r instanceof ReindexingDataSchemaRule);
+      boolean hasDeletionRule = intervalConfig.getAppliedRules().stream()
+                                              .anyMatch(r -> r instanceof ReindexingDeletionRule);
+      boolean hasSegmentGranRule = intervalConfig.getAppliedRules().stream()
+                                                 .anyMatch(r -> r instanceof ReindexingSegmentGranularityRule);
+
+      // Most recent intervals should have more rules applied
+      if (intervalConfig.getInterval().getEnd().isAfter(referenceTime.minusDays(10))) {
+        Assertions.assertTrue(hasTuningRule, "Recent intervals should have tuning rules");
+        Assertions.assertTrue(hasIORule, "Recent intervals should have IO rules");
+      }
+    }
+  }
+
+  /**
+   * Test that skipOffsetFromNow correctly skips intervals and populates skipOffset.applied
+   */
+  @Test
+  public void test_getReindexingTimelineView_skipOffsetFromNow_skipsProperIntervals()
+  {
+    DateTime referenceTime = DateTimes.of("2025-01-29T00:00:00Z");
+    Period skipOffset = Period.days(10);
+
+    // Create rules where the most recent rule has a period SMALLER than the skip offset
+    // This ensures the interval would extend beyond the effectiveEndTime and get clamped
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()
+                                                                  .segmentGranularityRules(List.of(
+                                                                      new ReindexingSegmentGranularityRule("seg-3d", null, Period.days(3), Granularities.HOUR),
+                                                                      new ReindexingSegmentGranularityRule("seg-30d", null, Period.days(30), Granularities.DAY)
+                                                                  ))
+                                                                  .build();
+
+    CascadingReindexingTemplate template = new CascadingReindexingTemplate(
+        "testDS",
+        null,
+        null,
+        provider,
+        null,
+        null,
+        null,
+        skipOffset, // skipOffsetFromNow
+        Granularities.DAY
+    );
+
+    ReindexingTimelineView timeline = template.getReindexingTimelineView(referenceTime);
+
+    // Verify skipOffset is applied
+    Assertions.assertNotNull(timeline.getSkipOffset(), "Skip offset should be present");
+    Assertions.assertNotNull(timeline.getSkipOffset().getApplied(), "Skip offset should be applied");
+    Assertions.assertNull(timeline.getSkipOffset().getNotApplied(), "Skip offset notApplied should be null");
+
+    ReindexingTimelineView.AppliedSkipOffset applied = timeline.getSkipOffset().getApplied();
+    Assertions.assertEquals("skipOffsetFromNow", applied.getType());
+    Assertions.assertEquals(skipOffset, applied.getPeriod());
+
+    DateTime expectedEffectiveEndTime = referenceTime.minus(skipOffset);
+    Assertions.assertEquals(expectedEffectiveEndTime, applied.getEffectiveEndTime());
+
+    for (ReindexingTimelineView.IntervalConfig intervalConfig : timeline.getIntervals()) {
+      if (intervalConfig.getInterval().getEnd().isAfter(expectedEffectiveEndTime)) {
+        Assertions.assertEquals(0, intervalConfig.getRuleCount());
+      }
+    }
+  }
+
+  /**
+   * Test validation error when granularity timeline is invalid
+   */
+  @Test
+  public void test_getReindexingTimelineView_validationError_invalidGranularityTimeline()
+  {
+    DateTime referenceTime = DateTimes.of("2025-01-29T16:15:00Z");
+
+    // Create rules that violate the granularity constraint:
+    // Older data (P90D) has DAY granularity, newer data (P30D) has HOUR granularity
+    // This means as we move from past to present, granularity gets finer (valid)
+    // But then if we add MONTH for recent data, it becomes coarser (invalid)
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()

Review Comment:
   Style tip: Move the `.builder()` to the next line to make the whole thing feel less crowded.
   ```suggestion
       ReindexingRuleProvider provider = InlineReindexingRuleProvider
           .builder()
   ```



##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorResource.java:
##########
@@ -351,6 +357,80 @@ public Response getAllTaskStats(
     );
   }
 
+  @GET
+  @Path("/{id}/reindexingTimeline")
+  @Produces(MediaType.APPLICATION_JSON)
+  @ResourceFilters(SupervisorResourceFilter.class)
+  public Response getReindexingTimeline(
+      @PathParam("id") final String id,
+      @QueryParam("referenceTime") @Nullable final String referenceTimeStr
+  )
+  {
+    return asLeaderWithSupervisorManager(
+        manager -> {
+          Optional<SupervisorSpec> specOptional = manager.getSupervisorSpec(id);
+          if (!specOptional.isPresent()) {
+            return Response.status(Response.Status.NOT_FOUND)
+                           .entity(ImmutableMap.of("error", StringUtils.format("[%s] does not exist", id)))
+                           .build();
+          }
+
+          SupervisorSpec spec = specOptional.get();
+          if (!(spec instanceof CompactionSupervisorSpec)) {
+            return Response.status(Response.Status.BAD_REQUEST)
+                           .entity(ImmutableMap.of(
+                               "error",
+                               StringUtils.format(
+                                   "[%s] is not a compaction supervisor (type: %s)",
+                                   id,
+                                   spec.getClass().getSimpleName()
+                               )
+                           ))
+                           .build();
+          }
+
+          CompactionSupervisorSpec compactionSpec = (CompactionSupervisorSpec) spec;
+
+          DateTime referenceTime;
+          if (referenceTimeStr != null) {
+            try {
+              referenceTime = DateTimes.of(referenceTimeStr);
+            }
+            catch (IllegalArgumentException e) {
+              return Response.status(Response.Status.BAD_REQUEST)
+                             .entity(ImmutableMap.of(
+                                 "error",
+                                 StringUtils.format("Invalid referenceTime format: %s", referenceTimeStr)

Review Comment:
   ```suggestion
                                    StringUtils.format("Reference time[%s] is in invalid format. Use ISO 8601 standard format.")
   ```
   
   By the way, you could also try doing the following to make the various conditions in this method cleaner.
   ```java
   return ServletResourceUtils.buildErrorResponseFrom(
       InvalidInput.exception(...)
   );
   ```



##########
indexing-service/src/test/java/org/apache/druid/indexing/compact/CascadingReindexingTemplateTest.java:
##########
@@ -1507,6 +1516,323 @@ public void test_generateAlignedSearchIntervals_failsWhenOlderRuleHasFinerGranul
     );
   }
 
+  /**
+   * Comprehensive test covering:
+   * - Multiple intervals with different segment granularities
+   * - All rule types (segment gran, data schema, deletion, tuning, IO)
+   * - Non-segment-gran rules triggering interval splitting
+   * - Applied rules tracking with correct rule types in each interval
+   * - Full DataSourceCompactionConfig generation
+   * - Rule count accuracy
+   */
+  @Test
+  public void test_getReindexingTimelineView_comprehensive()
+  {
+    DateTime referenceTime = DateTimes.of("2025-02-01T00:00:00Z");
+
+    // Create rules with various periods to test interval generation and splitting
+    ReindexingSegmentGranularityRule segGran7d = new ReindexingSegmentGranularityRule(
+        "seg-gran-7d",
+        null,
+        Period.days(7),
+        Granularities.HOUR
+    );
+
+    ReindexingSegmentGranularityRule segGran30d = new ReindexingSegmentGranularityRule(
+        "seg-gran-30d",
+        null,
+        Period.days(30),
+        Granularities.DAY
+    );
+
+    // Data schema rule at P15D (will split the HOUR interval)
+    ReindexingDataSchemaRule dataSchema15d = new ReindexingDataSchemaRule(
+        "data-schema-15d",
+        null,
+        Period.days(15),
+        new UserCompactionTaskDimensionsConfig(null),
+        new AggregatorFactory[]{new CountAggregatorFactory("count")},
+        Granularities.MINUTE,
+        true,
+        null
+    );
+
+    // Deletion rules at different periods
+    ReindexingDeletionRule deletion10d = new ReindexingDeletionRule(
+        "deletion-10d",
+        null,
+        Period.days(10),
+        new EqualityFilter("country", ColumnType.STRING, "US", null),
+        null
+    );
+
+    ReindexingDeletionRule deletion20d = new ReindexingDeletionRule(
+        "deletion-20d",
+        null,
+        Period.days(20),
+        new EqualityFilter("device", ColumnType.STRING, "mobile", null),
+        null
+    );
+
+    // Tuning and IO rules
+    ReindexingTuningConfigRule tuning7d = new ReindexingTuningConfigRule(
+        "tuning-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskQueryTuningConfig(
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null
+        )
+    );
+
+    ReindexingIOConfigRule io7d = new ReindexingIOConfigRule(
+        "io-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskIOConfig(true)
+    );
+
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()
+                                                                  .segmentGranularityRules(List.of(segGran7d, segGran30d))
+                                                                  .dataSchemaRules(List.of(dataSchema15d))
+                                                                  .deletionRules(List.of(deletion10d, deletion20d))
+                                                                  .tuningConfigRules(List.of(tuning7d))
+                                                                  .ioConfigRules(List.of(io7d))
+                                                                  .build();
+
+    CascadingReindexingTemplate template = new CascadingReindexingTemplate(
+        "testDS",
+        null,
+        null,
+        provider,
+        null,
+        null,
+        null,
+        null,
+        Granularities.DAY
+    );
+
+    ReindexingTimelineView timeline = template.getReindexingTimelineView(referenceTime);
+
+    // Verify basic timeline properties
+    Assertions.assertEquals("testDS", timeline.getDataSource());
+    Assertions.assertEquals(referenceTime, timeline.getReferenceTime());
+    Assertions.assertNull(timeline.getValidationError());
+    Assertions.assertNull(timeline.getSkipOffset());
+
+    // Verify we have multiple intervals (splitting should occur)
+    Assertions.assertTrue(timeline.getIntervals().size() >= 2, "Expected at least 2 intervals");
+
+    // Verify each interval has correct structure
+    for (ReindexingTimelineView.IntervalConfig intervalConfig : timeline.getIntervals()) {
+      Assertions.assertNotNull(intervalConfig.getInterval());
+      Assertions.assertTrue(intervalConfig.getRuleCount() > 0, "Rule count should be > 0");
+      Assertions.assertNotNull(intervalConfig.getConfig());
+      Assertions.assertNotNull(intervalConfig.getAppliedRules());
+      Assertions.assertEquals(
+          intervalConfig.getRuleCount(),
+          intervalConfig.getAppliedRules().size(),
+          "Applied rules size should match rule count"
+      );
+
+      // Verify config has expected components
+      DataSourceCompactionConfig config = intervalConfig.getConfig();
+      Assertions.assertNotNull(config.getGranularitySpec(), "Should have granularity spec");
+      Assertions.assertNotNull(config.getGranularitySpec().getSegmentGranularity(), "Should have segment granularity");
+
+      // Verify appliedRules contain expected rule types
+      boolean hasTuningRule = intervalConfig.getAppliedRules().stream()
+                                            .anyMatch(r -> r instanceof ReindexingTuningConfigRule);
+      boolean hasIORule = intervalConfig.getAppliedRules().stream()
+                                        .anyMatch(r -> r instanceof ReindexingIOConfigRule);
+      boolean hasDataSchemaRule = intervalConfig.getAppliedRules().stream()
+                                                .anyMatch(r -> r instanceof ReindexingDataSchemaRule);
+      boolean hasDeletionRule = intervalConfig.getAppliedRules().stream()
+                                              .anyMatch(r -> r instanceof ReindexingDeletionRule);
+      boolean hasSegmentGranRule = intervalConfig.getAppliedRules().stream()
+                                                 .anyMatch(r -> r instanceof ReindexingSegmentGranularityRule);
+
+      // Most recent intervals should have more rules applied
+      if (intervalConfig.getInterval().getEnd().isAfter(referenceTime.minusDays(10))) {
+        Assertions.assertTrue(hasTuningRule, "Recent intervals should have tuning rules");
+        Assertions.assertTrue(hasIORule, "Recent intervals should have IO rules");
+      }
+    }
+  }
+
+  /**
+   * Test that skipOffsetFromNow correctly skips intervals and populates skipOffset.applied
+   */

Review Comment:
   Not really needed as the test name already captures this.



##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorResource.java:
##########
@@ -351,6 +357,80 @@ public Response getAllTaskStats(
     );
   }
 
+  @GET
+  @Path("/{id}/reindexingTimeline")
+  @Produces(MediaType.APPLICATION_JSON)
+  @ResourceFilters(SupervisorResourceFilter.class)
+  public Response getReindexingTimeline(
+      @PathParam("id") final String id,
+      @QueryParam("referenceTime") @Nullable final String referenceTimeStr
+  )
+  {
+    return asLeaderWithSupervisorManager(
+        manager -> {
+          Optional<SupervisorSpec> specOptional = manager.getSupervisorSpec(id);
+          if (!specOptional.isPresent()) {
+            return Response.status(Response.Status.NOT_FOUND)
+                           .entity(ImmutableMap.of("error", StringUtils.format("[%s] does not exist", id)))

Review Comment:
   ```suggestion
                              .entity(ImmutableMap.of("error", StringUtils.format("Supervisor[%s] does not exist", id)))
   ```



##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorResource.java:
##########
@@ -351,6 +357,80 @@ public Response getAllTaskStats(
     );
   }
 
+  @GET
+  @Path("/{id}/reindexingTimeline")
+  @Produces(MediaType.APPLICATION_JSON)
+  @ResourceFilters(SupervisorResourceFilter.class)
+  public Response getReindexingTimeline(
+      @PathParam("id") final String id,
+      @QueryParam("referenceTime") @Nullable final String referenceTimeStr
+  )
+  {
+    return asLeaderWithSupervisorManager(
+        manager -> {
+          Optional<SupervisorSpec> specOptional = manager.getSupervisorSpec(id);
+          if (!specOptional.isPresent()) {
+            return Response.status(Response.Status.NOT_FOUND)
+                           .entity(ImmutableMap.of("error", StringUtils.format("[%s] does not exist", id)))
+                           .build();
+          }
+
+          SupervisorSpec spec = specOptional.get();
+          if (!(spec instanceof CompactionSupervisorSpec)) {
+            return Response.status(Response.Status.BAD_REQUEST)
+                           .entity(ImmutableMap.of(
+                               "error",
+                               StringUtils.format(
+                                   "[%s] is not a compaction supervisor (type: %s)",
+                                   id,
+                                   spec.getClass().getSimpleName()
+                               )
+                           ))
+                           .build();
+          }
+
+          CompactionSupervisorSpec compactionSpec = (CompactionSupervisorSpec) spec;
+
+          DateTime referenceTime;
+          if (referenceTimeStr != null) {
+            try {
+              referenceTime = DateTimes.of(referenceTimeStr);
+            }
+            catch (IllegalArgumentException e) {
+              return Response.status(Response.Status.BAD_REQUEST)
+                             .entity(ImmutableMap.of(
+                                 "error",
+                                 StringUtils.format("Invalid referenceTime format: %s", referenceTimeStr)
+                             ))
+                             .build();
+            }
+          } else {
+            referenceTime = DateTimes.nowUtc();
+          }
+
+          CompactionJobTemplate template = compactionSpec.getTemplate();
+          if (!(template instanceof CascadingReindexingTemplate)) {
+            return Response.status(Response.Status.BAD_REQUEST)
+                           .entity(ImmutableMap.of(
+                               "error",
+                               StringUtils.format(
+                                   "Reindexing timeline is only available for cascading reindexing supervisors. " +
+                                   "Supervisor [%s] uses template type: %s",

Review Comment:
   ```suggestion
                                      "Reindexing timeline is not available for supervisor[%s] as it does not use a cascading template",
   ```



##########
indexing-service/src/test/java/org/apache/druid/indexing/compact/CascadingReindexingTemplateTest.java:
##########
@@ -1507,6 +1516,323 @@ public void test_generateAlignedSearchIntervals_failsWhenOlderRuleHasFinerGranul
     );
   }
 
+  /**
+   * Comprehensive test covering:
+   * - Multiple intervals with different segment granularities
+   * - All rule types (segment gran, data schema, deletion, tuning, IO)
+   * - Non-segment-gran rules triggering interval splitting
+   * - Applied rules tracking with correct rule types in each interval
+   * - Full DataSourceCompactionConfig generation
+   * - Rule count accuracy
+   */
+  @Test
+  public void test_getReindexingTimelineView_comprehensive()
+  {
+    DateTime referenceTime = DateTimes.of("2025-02-01T00:00:00Z");
+
+    // Create rules with various periods to test interval generation and splitting
+    ReindexingSegmentGranularityRule segGran7d = new ReindexingSegmentGranularityRule(
+        "seg-gran-7d",
+        null,
+        Period.days(7),
+        Granularities.HOUR
+    );
+
+    ReindexingSegmentGranularityRule segGran30d = new ReindexingSegmentGranularityRule(
+        "seg-gran-30d",
+        null,
+        Period.days(30),
+        Granularities.DAY
+    );
+
+    // Data schema rule at P15D (will split the HOUR interval)
+    ReindexingDataSchemaRule dataSchema15d = new ReindexingDataSchemaRule(
+        "data-schema-15d",
+        null,
+        Period.days(15),
+        new UserCompactionTaskDimensionsConfig(null),
+        new AggregatorFactory[]{new CountAggregatorFactory("count")},
+        Granularities.MINUTE,
+        true,
+        null
+    );
+
+    // Deletion rules at different periods
+    ReindexingDeletionRule deletion10d = new ReindexingDeletionRule(
+        "deletion-10d",
+        null,
+        Period.days(10),
+        new EqualityFilter("country", ColumnType.STRING, "US", null),
+        null
+    );
+
+    ReindexingDeletionRule deletion20d = new ReindexingDeletionRule(
+        "deletion-20d",
+        null,
+        Period.days(20),
+        new EqualityFilter("device", ColumnType.STRING, "mobile", null),
+        null
+    );
+
+    // Tuning and IO rules
+    ReindexingTuningConfigRule tuning7d = new ReindexingTuningConfigRule(
+        "tuning-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskQueryTuningConfig(
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null
+        )
+    );
+
+    ReindexingIOConfigRule io7d = new ReindexingIOConfigRule(
+        "io-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskIOConfig(true)
+    );
+
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()
+                                                                  .segmentGranularityRules(List.of(segGran7d, segGran30d))
+                                                                  .dataSchemaRules(List.of(dataSchema15d))
+                                                                  .deletionRules(List.of(deletion10d, deletion20d))
+                                                                  .tuningConfigRules(List.of(tuning7d))
+                                                                  .ioConfigRules(List.of(io7d))
+                                                                  .build();
+
+    CascadingReindexingTemplate template = new CascadingReindexingTemplate(
+        "testDS",
+        null,
+        null,
+        provider,
+        null,
+        null,
+        null,
+        null,
+        Granularities.DAY
+    );
+
+    ReindexingTimelineView timeline = template.getReindexingTimelineView(referenceTime);
+
+    // Verify basic timeline properties
+    Assertions.assertEquals("testDS", timeline.getDataSource());
+    Assertions.assertEquals(referenceTime, timeline.getReferenceTime());
+    Assertions.assertNull(timeline.getValidationError());
+    Assertions.assertNull(timeline.getSkipOffset());
+
+    // Verify we have multiple intervals (splitting should occur)
+    Assertions.assertTrue(timeline.getIntervals().size() >= 2, "Expected at least 2 intervals");
+
+    // Verify each interval has correct structure
+    for (ReindexingTimelineView.IntervalConfig intervalConfig : timeline.getIntervals()) {
+      Assertions.assertNotNull(intervalConfig.getInterval());
+      Assertions.assertTrue(intervalConfig.getRuleCount() > 0, "Rule count should be > 0");
+      Assertions.assertNotNull(intervalConfig.getConfig());
+      Assertions.assertNotNull(intervalConfig.getAppliedRules());
+      Assertions.assertEquals(
+          intervalConfig.getRuleCount(),
+          intervalConfig.getAppliedRules().size(),
+          "Applied rules size should match rule count"
+      );
+
+      // Verify config has expected components
+      DataSourceCompactionConfig config = intervalConfig.getConfig();
+      Assertions.assertNotNull(config.getGranularitySpec(), "Should have granularity spec");
+      Assertions.assertNotNull(config.getGranularitySpec().getSegmentGranularity(), "Should have segment granularity");
+
+      // Verify appliedRules contain expected rule types
+      boolean hasTuningRule = intervalConfig.getAppliedRules().stream()
+                                            .anyMatch(r -> r instanceof ReindexingTuningConfigRule);
+      boolean hasIORule = intervalConfig.getAppliedRules().stream()
+                                        .anyMatch(r -> r instanceof ReindexingIOConfigRule);
+      boolean hasDataSchemaRule = intervalConfig.getAppliedRules().stream()
+                                                .anyMatch(r -> r instanceof ReindexingDataSchemaRule);
+      boolean hasDeletionRule = intervalConfig.getAppliedRules().stream()
+                                              .anyMatch(r -> r instanceof ReindexingDeletionRule);
+      boolean hasSegmentGranRule = intervalConfig.getAppliedRules().stream()
+                                                 .anyMatch(r -> r instanceof ReindexingSegmentGranularityRule);
+
+      // Most recent intervals should have more rules applied
+      if (intervalConfig.getInterval().getEnd().isAfter(referenceTime.minusDays(10))) {
+        Assertions.assertTrue(hasTuningRule, "Recent intervals should have tuning rules");
+        Assertions.assertTrue(hasIORule, "Recent intervals should have IO rules");
+      }
+    }
+  }
+
+  /**
+   * Test that skipOffsetFromNow correctly skips intervals and populates skipOffset.applied
+   */
+  @Test
+  public void test_getReindexingTimelineView_skipOffsetFromNow_skipsProperIntervals()
+  {
+    DateTime referenceTime = DateTimes.of("2025-01-29T00:00:00Z");
+    Period skipOffset = Period.days(10);
+
+    // Create rules where the most recent rule has a period SMALLER than the skip offset
+    // This ensures the interval would extend beyond the effectiveEndTime and get clamped
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()
+                                                                  .segmentGranularityRules(List.of(
+                                                                      new ReindexingSegmentGranularityRule("seg-3d", null, Period.days(3), Granularities.HOUR),
+                                                                      new ReindexingSegmentGranularityRule("seg-30d", null, Period.days(30), Granularities.DAY)
+                                                                  ))
+                                                                  .build();
+
+    CascadingReindexingTemplate template = new CascadingReindexingTemplate(
+        "testDS",
+        null,
+        null,
+        provider,
+        null,
+        null,
+        null,
+        skipOffset, // skipOffsetFromNow
+        Granularities.DAY
+    );
+
+    ReindexingTimelineView timeline = template.getReindexingTimelineView(referenceTime);
+
+    // Verify skipOffset is applied
+    Assertions.assertNotNull(timeline.getSkipOffset(), "Skip offset should be present");
+    Assertions.assertNotNull(timeline.getSkipOffset().getApplied(), "Skip offset should be applied");
+    Assertions.assertNull(timeline.getSkipOffset().getNotApplied(), "Skip offset notApplied should be null");
+
+    ReindexingTimelineView.AppliedSkipOffset applied = timeline.getSkipOffset().getApplied();
+    Assertions.assertEquals("skipOffsetFromNow", applied.getType());
+    Assertions.assertEquals(skipOffset, applied.getPeriod());
+
+    DateTime expectedEffectiveEndTime = referenceTime.minus(skipOffset);
+    Assertions.assertEquals(expectedEffectiveEndTime, applied.getEffectiveEndTime());
+
+    for (ReindexingTimelineView.IntervalConfig intervalConfig : timeline.getIntervals()) {
+      if (intervalConfig.getInterval().getEnd().isAfter(expectedEffectiveEndTime)) {
+        Assertions.assertEquals(0, intervalConfig.getRuleCount());
+      }
+    }
+  }
+
+  /**
+   * Test validation error when granularity timeline is invalid
+   */

Review Comment:
   Not really needed since the test name captures this already.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "vogievetsky (via GitHub)" <gi...@apache.org>.
vogievetsky commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3244852186


##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);
+      const result = resp.data;
+      if (result && result.length > 0 && result[0].result) {
+        const maxTime = result[0].result.maxTime;
+        setQueriedMaxTime(maxTime);
+      } else {
+        AppToaster.show({
+          message: 'No data found in datasource',
+          intent: Intent.WARNING,
+        });
+      }
+    } catch (e) {
+      AppToaster.show({
+        message: `Failed to query max time: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+    } finally {
+      setQueryingMaxTime(false);
+    }
+  };
+
+  // Calculate effective end time if we have queried max time and skipOffsetFromLatest
+  let effectiveEndTime: Date | undefined;
+  if (queriedMaxTime && skipOffset && !skipOffset.isApplied) {
+    const period = skipOffset.period;
+    try {
+      const duration = new Duration(period);
+      effectiveEndTime = duration.shift(new Date(queriedMaxTime), Timezone.UTC, -1);
+    } catch (e) {
+      console.error('Failed to parse skip offset period:', period, e);
+      AppToaster.show({
+        message: `Invalid skip offset period format: ${period}`,
+        intent: Intent.WARNING,
+      });
+    }
+  }
+
+  // Display validation error if present
+  if (validationError) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Invalid Supervisor Configuration">
+          <p>
+            <strong>
+              The segment granularity rule definitions have created an illegal segment granularity
+              timeline.
+            </strong>
+          </p>
+          {validationError.errorType === 'INVALID_GRANULARITY_TIMELINE' &&
+            validationError.olderInterval && (
+              <>
+                <p>
+                  Segment granularity must stay the same or become <strong>coarser</strong> as data
+                  ages from present to past. Your configuration violates this constraint:
+                </p>
+                <ul>
+                  <li>
+                    <strong>Older interval</strong> (further in the past):{' '}
+                    <code>{formatInterval(validationError.olderInterval)}</code> has{' '}
+                    <strong>finer</strong> granularity:{' '}
+                    <Tag intent={Intent.PRIMARY}>{validationError.olderGranularity}</Tag>
+                  </li>
+                  <li>
+                    <strong>Newer interval</strong> (more recent):{' '}
+                    <code>{formatInterval(validationError.newerInterval!)}</code> has{' '}
+                    <strong>coarser</strong> granularity:{' '}
+                    <Tag intent={Intent.WARNING}>{validationError.newerGranularity}</Tag>
+                  </li>
+                </ul>
+                <p>
+                  <strong>To fix this:</strong> Adjust your segment granularity rules so that as
+                  time moves from present to past, the granularity either stays the same or gets
+                  coarser (e.g., HOUR → DAY → MONTH → YEAR).
+                </p>
+              </>
+            )}
+          {validationError.errorType !== 'INVALID_GRANULARITY_TIMELINE' && (
+            <p>{validationError.message}</p>
+          )}
+        </Callout>
+      </div>
+    );
+  }
+
+  if (intervals.length === 0) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.WARNING}>
+          No reindexing intervals found. This may indicate that the rule provider is not ready or no
+          rules are configured.
+        </Callout>
+      </div>
+    );
+  }
+
+  const selectedInterval =
+    selectedIntervalIndex !== undefined ? intervals[selectedIntervalIndex] : undefined;
+
+  return (
+    <div className="reindexing-timeline">
+      <div className="timeline-header">
+        <div className="header-info">
+          <strong>DataSource:</strong> {timelineData.dataSource}
+          <span className="spacer">|</span>
+          <Tooltip
+            content="The reference time used in conjunction with each rule's 'olderThan' attribute to calculate which intervals a rule should apply to."
+            position="bottom"
+          >
+            <strong className="help-hint">Reference Time:</strong>
+          </Tooltip>{' '}
+          {formatDateTimeUTC(referenceTime)}
+        </div>
+        {skipOffset && (
+          <div className="skip-offset-info">
+            {skipOffset.isApplied && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                Skip Offset: {skipOffset.type} ({skipOffset.period})
+              </Tag>
+            )}
+            {!skipOffset.isApplied && !queriedMaxTime && (
+              <>
+                <Tooltip
+                  content={
+                    `This supervisor is configured to skip compaction of any search interval that is covered by ` +
+                    `or overlaps the threshold of the latest timestamp in the data minus ${skipOffset.period}. ` +
+                    `However, the underlying segment data is not available in this preview, so the timeline does not ` +
+                    `reflect which intervals will be skipped during actual compaction.`
+                  }
+                  position="bottom"
+                >
+                  <Tag minimal intent={Intent.WARNING} icon={IconNames.WARNING_SIGN}>
+                    {skipOffset.type} ({skipOffset.period}): Not reflected in this preview
+                  </Tag>
+                </Tooltip>
+                <Button
+                  text="Query latest timestamp"
+                  icon={IconNames.REFRESH}
+                  small
+                  onClick={() => void handleQueryMaxTime()}
+                  loading={queryingMaxTime}
+                  className="query-button"
+                />
+              </>
+            )}
+            {!skipOffset.isApplied && queriedMaxTime && effectiveEndTime && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                {skipOffset.type} ({skipOffset.period}): Applied (latest:{' '}
+                {formatDateTimeUTC(queriedMaxTime)})
+              </Tag>
+            )}
+          </div>
+        )}
+      </div>
+
+      <Card className="timeline-bar-container">
+        <div className="timeline-bar" role="toolbar" aria-label="Reindexing timeline intervals">
+          {intervals.map((interval, idx) => {
+            const [start, end] = interval.interval.split('/');
+            const isSelected = selectedIntervalIndex === idx;
+
+            // Check if interval is skipped due to skip offset (either from API or from queried max time)
+            let isSkipped = interval.ruleCount === 0;
+            if (!isSkipped && effectiveEndTime) {
+              const intervalEnd = new Date(end);
+              isSkipped = intervalEnd > effectiveEndTime;
+            }
+
+            return (
+              <div
+                key={interval.interval}
+                className={`timeline-segment ${isSelected ? 'selected' : ''} ${
+                  isSkipped ? 'skipped' : ''
+                }`}
+                style={{
+                  backgroundColor: isSkipped ? SKIPPED_INTERVAL_COLOR : getIntervalColor(idx),
+                  flex: 1,
+                }}
+                role={isSkipped ? undefined : 'button'}
+                tabIndex={isSkipped ? undefined : 0}
+                aria-label={
+                  isSkipped
+                    ? `Skipped interval ${interval.interval}`
+                    : `Interval ${interval.interval} with ${interval.ruleCount} rule${
+                        interval.ruleCount !== 1 ? 's' : ''
+                      }`
+                }
+                aria-selected={isSelected}
+                onClick={() => !isSkipped && setSelectedIntervalIndex(idx)}
+                onKeyDown={e => {
+                  if (!isSkipped && (e.key === 'Enter' || e.key === ' ')) {
+                    e.preventDefault();
+                    setSelectedIntervalIndex(idx);
+                  }
+                }}
+                title={
+                  isSkipped
+                    ? `${interval.interval}\nSkipped (beyond skip offset)`
+                    : `${interval.interval}\n${interval.ruleCount} rule(s) applied`
+                }
+              >
+                <div className="segment-label">
+                  <div className="segment-date">{formatDateShort(start)}</div>
+                  <div className="segment-date">{formatDateShort(end)}</div>
+                  <div className="segment-rules">
+                    <Tag minimal intent={isSkipped ? Intent.DANGER : undefined}>
+                      {isSkipped
+                        ? 'skipped'
+                        : `${interval.ruleCount} rule${interval.ruleCount !== 1 ? 's' : ''}`}
+                    </Tag>
+                  </div>
+                </div>
+              </div>
+            );
+          })}
+        </div>
+        <div className="timeline-hint">Click on an interval to view its configuration details</div>
+      </Card>
+
+      {selectedInterval && selectedInterval.ruleCount > 0 && (
+        <IntervalDetailPanel
+          interval={selectedInterval}
+          onClose={() => setSelectedIntervalIndex(undefined)}
+        />
+      )}
+    </div>
+  );
+});
+
+function formatDateShort(isoDate: string): string {
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  const d = new Date(isoDate);
+  return `${UTC_MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
+}
+
+const UTC_MONTH_NAMES = [
+  'Jan',
+  'Feb',
+  'Mar',
+  'Apr',
+  'May',
+  'Jun',
+  'Jul',
+  'Aug',
+  'Sep',
+  'Oct',
+  'Nov',
+  'Dec',
+];
+
+function formatDateTimeUTC(isoDate: string): string {
+  // Handle start of time / very old dates
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  // Format using UTC methods to avoid local timezone shifting.
+  // date-fns format() uses the browser's local timezone, so we extract UTC
+  // components manually to ensure the displayed time is actually UTC.
+  const d = new Date(isoDate);
+  const month = UTC_MONTH_NAMES[d.getUTCMonth()];
+  const day = d.getUTCDate();
+  const year = d.getUTCFullYear();
+  const hours = d.getUTCHours();
+  const minutes = String(d.getUTCMinutes()).padStart(2, '0');
+  const ampm = hours >= 12 ? 'PM' : 'AM';
+  const displayHours = hours % 12 || 12;
+  return `${month} ${day}, ${year} ${displayHours}:${minutes} ${ampm} UTC`;
+}
+
+function formatInterval(interval: string): string {
+  const [start, end] = interval.split('/');
+  const formattedStart = start.startsWith('-') ? '-INF' : start;
+  const formattedEnd = end ? end : 'now';
+  return `${formattedStart}/${formattedEnd}`;
+}
+
+function handleCopyToClipboard(data: CompactionConfig | ReindexingRule[], label: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  copy(jsonValue, { format: 'text/plain' });
+  AppToaster.show({
+    message: `${label} copied to clipboard`,
+    intent: Intent.SUCCESS,
+  });
+}
+
+function handleDownloadJson(data: CompactionConfig | ReindexingRule[], filename: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  downloadFile(jsonValue, 'json', filename);
+}
+
+function getPartitionType(tuningConfig: Record<string, unknown> | undefined): string | undefined {
+  if (!tuningConfig) return undefined;
+  const partitionsSpec = tuningConfig.partitionsSpec;
+  if (partitionsSpec && typeof partitionsSpec === 'object' && partitionsSpec !== null) {
+    return (partitionsSpec as Record<string, unknown>).type as string | undefined;
+  }
+  return undefined;
+}
+
+interface IntervalDetailPanelProps {
+  interval: IntervalConfig;
+  onClose: () => void;
+}
+
+function IntervalDetailPanel({ interval, onClose }: IntervalDetailPanelProps) {
+  const [showFullConfig, setShowFullConfig] = useState(false);
+  const [showRawRules, setShowRawRules] = useState(false);
+  const { config } = interval;
+
+  const deletionRuleCount = interval.appliedRules.filter(r => r.type === 'deletion').length;
+  const metricsCount = config.metricsSpec?.length || 0;
+  const dimensionsCount = config.dimensionsSpec?.dimensions?.length || 0;
+  const projectionsCount = config.projections?.length || 0;
+
+  return (
+    <>
+      <Card className="interval-detail-panel">
+        <div className="detail-header">
+          <div>
+            <h3>Interval: {formatInterval(interval.interval)}</h3>
+          </div>
+          <Button
+            icon={IconNames.CROSS}
+            minimal
+            onClick={onClose}
+            aria-label="Close interval details"
+          />
+        </div>
+
+        <div className="detail-content">
+          <Tooltip
+            content="A high-level summary of the merged rule configuration for this interval — use View Full Configuration for complete details."
+            position="bottom"
+          >
+            <div className="config-summary-label">Effective Configuration</div>
+          </Tooltip>
+          <div className="config-badges">
+            {config.granularitySpec?.segmentGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.CALENDAR}>
+                Segment: {config.granularitySpec.segmentGranularity}
+              </Tag>
+            )}
+            {config.granularitySpec?.queryGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.TIME}>
+                Query: {config.granularitySpec.queryGranularity}
+              </Tag>
+            )}
+            {getPartitionType(config.tuningConfig) && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.SPLIT_COLUMNS}>
+                Partitioning: {getPartitionType(config.tuningConfig)}
+              </Tag>
+            )}
+            {metricsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CALCULATOR}>
+                {metricsCount} metric{metricsCount !== 1 ? 's' : ''}

Review Comment:
   this is what the `pluralIfNeeded` utility function is for.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "vogievetsky (via GitHub)" <gi...@apache.org>.
vogievetsky commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3244875010


##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);
+      const result = resp.data;
+      if (result && result.length > 0 && result[0].result) {
+        const maxTime = result[0].result.maxTime;
+        setQueriedMaxTime(maxTime);
+      } else {
+        AppToaster.show({
+          message: 'No data found in datasource',
+          intent: Intent.WARNING,
+        });
+      }
+    } catch (e) {
+      AppToaster.show({
+        message: `Failed to query max time: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+    } finally {
+      setQueryingMaxTime(false);
+    }
+  };
+
+  // Calculate effective end time if we have queried max time and skipOffsetFromLatest
+  let effectiveEndTime: Date | undefined;
+  if (queriedMaxTime && skipOffset && !skipOffset.isApplied) {
+    const period = skipOffset.period;
+    try {
+      const duration = new Duration(period);
+      effectiveEndTime = duration.shift(new Date(queriedMaxTime), Timezone.UTC, -1);
+    } catch (e) {
+      console.error('Failed to parse skip offset period:', period, e);
+      AppToaster.show({
+        message: `Invalid skip offset period format: ${period}`,
+        intent: Intent.WARNING,
+      });
+    }
+  }
+
+  // Display validation error if present
+  if (validationError) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Invalid Supervisor Configuration">
+          <p>
+            <strong>
+              The segment granularity rule definitions have created an illegal segment granularity
+              timeline.
+            </strong>
+          </p>
+          {validationError.errorType === 'INVALID_GRANULARITY_TIMELINE' &&
+            validationError.olderInterval && (
+              <>
+                <p>
+                  Segment granularity must stay the same or become <strong>coarser</strong> as data
+                  ages from present to past. Your configuration violates this constraint:
+                </p>
+                <ul>
+                  <li>
+                    <strong>Older interval</strong> (further in the past):{' '}
+                    <code>{formatInterval(validationError.olderInterval)}</code> has{' '}
+                    <strong>finer</strong> granularity:{' '}
+                    <Tag intent={Intent.PRIMARY}>{validationError.olderGranularity}</Tag>
+                  </li>
+                  <li>
+                    <strong>Newer interval</strong> (more recent):{' '}
+                    <code>{formatInterval(validationError.newerInterval!)}</code> has{' '}
+                    <strong>coarser</strong> granularity:{' '}
+                    <Tag intent={Intent.WARNING}>{validationError.newerGranularity}</Tag>
+                  </li>
+                </ul>
+                <p>
+                  <strong>To fix this:</strong> Adjust your segment granularity rules so that as
+                  time moves from present to past, the granularity either stays the same or gets
+                  coarser (e.g., HOUR → DAY → MONTH → YEAR).
+                </p>
+              </>
+            )}
+          {validationError.errorType !== 'INVALID_GRANULARITY_TIMELINE' && (
+            <p>{validationError.message}</p>
+          )}
+        </Callout>
+      </div>
+    );
+  }
+
+  if (intervals.length === 0) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.WARNING}>
+          No reindexing intervals found. This may indicate that the rule provider is not ready or no
+          rules are configured.
+        </Callout>
+      </div>
+    );
+  }
+
+  const selectedInterval =
+    selectedIntervalIndex !== undefined ? intervals[selectedIntervalIndex] : undefined;
+
+  return (
+    <div className="reindexing-timeline">
+      <div className="timeline-header">
+        <div className="header-info">
+          <strong>DataSource:</strong> {timelineData.dataSource}
+          <span className="spacer">|</span>
+          <Tooltip
+            content="The reference time used in conjunction with each rule's 'olderThan' attribute to calculate which intervals a rule should apply to."
+            position="bottom"
+          >
+            <strong className="help-hint">Reference Time:</strong>
+          </Tooltip>{' '}
+          {formatDateTimeUTC(referenceTime)}
+        </div>
+        {skipOffset && (
+          <div className="skip-offset-info">
+            {skipOffset.isApplied && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                Skip Offset: {skipOffset.type} ({skipOffset.period})
+              </Tag>
+            )}
+            {!skipOffset.isApplied && !queriedMaxTime && (
+              <>
+                <Tooltip
+                  content={
+                    `This supervisor is configured to skip compaction of any search interval that is covered by ` +
+                    `or overlaps the threshold of the latest timestamp in the data minus ${skipOffset.period}. ` +
+                    `However, the underlying segment data is not available in this preview, so the timeline does not ` +
+                    `reflect which intervals will be skipped during actual compaction.`
+                  }
+                  position="bottom"
+                >
+                  <Tag minimal intent={Intent.WARNING} icon={IconNames.WARNING_SIGN}>
+                    {skipOffset.type} ({skipOffset.period}): Not reflected in this preview
+                  </Tag>
+                </Tooltip>
+                <Button
+                  text="Query latest timestamp"
+                  icon={IconNames.REFRESH}
+                  small
+                  onClick={() => void handleQueryMaxTime()}
+                  loading={queryingMaxTime}
+                  className="query-button"
+                />
+              </>
+            )}
+            {!skipOffset.isApplied && queriedMaxTime && effectiveEndTime && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                {skipOffset.type} ({skipOffset.period}): Applied (latest:{' '}
+                {formatDateTimeUTC(queriedMaxTime)})
+              </Tag>
+            )}
+          </div>
+        )}
+      </div>
+
+      <Card className="timeline-bar-container">
+        <div className="timeline-bar" role="toolbar" aria-label="Reindexing timeline intervals">
+          {intervals.map((interval, idx) => {
+            const [start, end] = interval.interval.split('/');
+            const isSelected = selectedIntervalIndex === idx;
+
+            // Check if interval is skipped due to skip offset (either from API or from queried max time)
+            let isSkipped = interval.ruleCount === 0;
+            if (!isSkipped && effectiveEndTime) {
+              const intervalEnd = new Date(end);
+              isSkipped = intervalEnd > effectiveEndTime;
+            }
+
+            return (
+              <div
+                key={interval.interval}
+                className={`timeline-segment ${isSelected ? 'selected' : ''} ${
+                  isSkipped ? 'skipped' : ''
+                }`}
+                style={{
+                  backgroundColor: isSkipped ? SKIPPED_INTERVAL_COLOR : getIntervalColor(idx),
+                  flex: 1,
+                }}
+                role={isSkipped ? undefined : 'button'}
+                tabIndex={isSkipped ? undefined : 0}
+                aria-label={
+                  isSkipped
+                    ? `Skipped interval ${interval.interval}`
+                    : `Interval ${interval.interval} with ${interval.ruleCount} rule${
+                        interval.ruleCount !== 1 ? 's' : ''
+                      }`
+                }
+                aria-selected={isSelected}
+                onClick={() => !isSkipped && setSelectedIntervalIndex(idx)}
+                onKeyDown={e => {
+                  if (!isSkipped && (e.key === 'Enter' || e.key === ' ')) {
+                    e.preventDefault();
+                    setSelectedIntervalIndex(idx);
+                  }
+                }}
+                title={
+                  isSkipped
+                    ? `${interval.interval}\nSkipped (beyond skip offset)`
+                    : `${interval.interval}\n${interval.ruleCount} rule(s) applied`
+                }
+              >
+                <div className="segment-label">
+                  <div className="segment-date">{formatDateShort(start)}</div>
+                  <div className="segment-date">{formatDateShort(end)}</div>
+                  <div className="segment-rules">
+                    <Tag minimal intent={isSkipped ? Intent.DANGER : undefined}>
+                      {isSkipped
+                        ? 'skipped'
+                        : `${interval.ruleCount} rule${interval.ruleCount !== 1 ? 's' : ''}`}
+                    </Tag>
+                  </div>
+                </div>
+              </div>
+            );
+          })}
+        </div>
+        <div className="timeline-hint">Click on an interval to view its configuration details</div>
+      </Card>
+
+      {selectedInterval && selectedInterval.ruleCount > 0 && (
+        <IntervalDetailPanel
+          interval={selectedInterval}
+          onClose={() => setSelectedIntervalIndex(undefined)}
+        />
+      )}
+    </div>
+  );
+});
+
+function formatDateShort(isoDate: string): string {
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  const d = new Date(isoDate);
+  return `${UTC_MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
+}
+
+const UTC_MONTH_NAMES = [
+  'Jan',
+  'Feb',
+  'Mar',
+  'Apr',
+  'May',
+  'Jun',
+  'Jul',
+  'Aug',
+  'Sep',
+  'Oct',
+  'Nov',
+  'Dec',
+];
+
+function formatDateTimeUTC(isoDate: string): string {
+  // Handle start of time / very old dates
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  // Format using UTC methods to avoid local timezone shifting.
+  // date-fns format() uses the browser's local timezone, so we extract UTC
+  // components manually to ensure the displayed time is actually UTC.
+  const d = new Date(isoDate);
+  const month = UTC_MONTH_NAMES[d.getUTCMonth()];
+  const day = d.getUTCDate();
+  const year = d.getUTCFullYear();
+  const hours = d.getUTCHours();
+  const minutes = String(d.getUTCMinutes()).padStart(2, '0');
+  const ampm = hours >= 12 ? 'PM' : 'AM';
+  const displayHours = hours % 12 || 12;
+  return `${month} ${day}, ${year} ${displayHours}:${minutes} ${ampm} UTC`;
+}
+
+function formatInterval(interval: string): string {
+  const [start, end] = interval.split('/');
+  const formattedStart = start.startsWith('-') ? '-INF' : start;
+  const formattedEnd = end ? end : 'now';
+  return `${formattedStart}/${formattedEnd}`;
+}
+
+function handleCopyToClipboard(data: CompactionConfig | ReindexingRule[], label: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  copy(jsonValue, { format: 'text/plain' });
+  AppToaster.show({
+    message: `${label} copied to clipboard`,
+    intent: Intent.SUCCESS,
+  });
+}
+
+function handleDownloadJson(data: CompactionConfig | ReindexingRule[], filename: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  downloadFile(jsonValue, 'json', filename);
+}
+
+function getPartitionType(tuningConfig: Record<string, unknown> | undefined): string | undefined {
+  if (!tuningConfig) return undefined;
+  const partitionsSpec = tuningConfig.partitionsSpec;
+  if (partitionsSpec && typeof partitionsSpec === 'object' && partitionsSpec !== null) {
+    return (partitionsSpec as Record<string, unknown>).type as string | undefined;
+  }
+  return undefined;
+}
+
+interface IntervalDetailPanelProps {
+  interval: IntervalConfig;
+  onClose: () => void;
+}
+
+function IntervalDetailPanel({ interval, onClose }: IntervalDetailPanelProps) {
+  const [showFullConfig, setShowFullConfig] = useState(false);
+  const [showRawRules, setShowRawRules] = useState(false);
+  const { config } = interval;
+
+  const deletionRuleCount = interval.appliedRules.filter(r => r.type === 'deletion').length;
+  const metricsCount = config.metricsSpec?.length || 0;
+  const dimensionsCount = config.dimensionsSpec?.dimensions?.length || 0;
+  const projectionsCount = config.projections?.length || 0;
+
+  return (
+    <>
+      <Card className="interval-detail-panel">
+        <div className="detail-header">
+          <div>
+            <h3>Interval: {formatInterval(interval.interval)}</h3>
+          </div>
+          <Button
+            icon={IconNames.CROSS}
+            minimal
+            onClick={onClose}
+            aria-label="Close interval details"
+          />
+        </div>
+
+        <div className="detail-content">
+          <Tooltip
+            content="A high-level summary of the merged rule configuration for this interval — use View Full Configuration for complete details."
+            position="bottom"
+          >
+            <div className="config-summary-label">Effective Configuration</div>
+          </Tooltip>
+          <div className="config-badges">
+            {config.granularitySpec?.segmentGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.CALENDAR}>
+                Segment: {config.granularitySpec.segmentGranularity}
+              </Tag>
+            )}
+            {config.granularitySpec?.queryGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.TIME}>
+                Query: {config.granularitySpec.queryGranularity}
+              </Tag>
+            )}
+            {getPartitionType(config.tuningConfig) && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.SPLIT_COLUMNS}>
+                Partitioning: {getPartitionType(config.tuningConfig)}
+              </Tag>
+            )}
+            {metricsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CALCULATOR}>
+                {metricsCount} metric{metricsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {dimensionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TAG}>

Review Comment:
   I feel like the intents are being used here just to add color coding to the `Tag` s but that is not how intents should be used. A better approach would be some colored text with custom colors (not the intent colors)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r2853927687


##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorResource.java:
##########
@@ -351,6 +357,79 @@
     );
   }
 
+  @GET
+  @Path("/{id}/reindexingTimeline")
+  @Produces(MediaType.APPLICATION_JSON)
+  @ResourceFilters(SupervisorResourceFilter.class)
+  public Response getReindexingTimeline(
+      @PathParam("id") final String id,
+      @QueryParam("referenceTime") @Nullable final String referenceTimeStr
+  )
+  {
+    return asLeaderWithSupervisorManager(
+        manager -> {
+          Optional<SupervisorSpec> specOptional = manager.getSupervisorSpec(id);
+          if (!specOptional.isPresent()) {
+            return Response.status(Response.Status.NOT_FOUND)
+                           .entity(ImmutableMap.of("error", StringUtils.format("Supervisor[%s] does not exist", id)))
+                           .build();
+          }
+
+          SupervisorSpec spec = specOptional.get();
+          if (!(spec instanceof CompactionSupervisorSpec)) {
+            return Response.status(Response.Status.BAD_REQUEST)
+                           .entity(ImmutableMap.of(
+                               "error",
+                               StringUtils.format(
+                                   "Supervisor[%s] is not a compaction supervisor",
+                                   id,
+                                   spec.getClass().getSimpleName()
+                               )

Review Comment:
   ## Unused format argument
   
   This format call refers to 1 argument(s) but supplies 2 argument(s).
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/10834)



##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorResource.java:
##########
@@ -351,6 +357,79 @@
     );
   }
 
+  @GET
+  @Path("/{id}/reindexingTimeline")
+  @Produces(MediaType.APPLICATION_JSON)
+  @ResourceFilters(SupervisorResourceFilter.class)
+  public Response getReindexingTimeline(
+      @PathParam("id") final String id,
+      @QueryParam("referenceTime") @Nullable final String referenceTimeStr
+  )
+  {
+    return asLeaderWithSupervisorManager(
+        manager -> {
+          Optional<SupervisorSpec> specOptional = manager.getSupervisorSpec(id);
+          if (!specOptional.isPresent()) {
+            return Response.status(Response.Status.NOT_FOUND)
+                           .entity(ImmutableMap.of("error", StringUtils.format("Supervisor[%s] does not exist", id)))
+                           .build();
+          }
+
+          SupervisorSpec spec = specOptional.get();
+          if (!(spec instanceof CompactionSupervisorSpec)) {
+            return Response.status(Response.Status.BAD_REQUEST)
+                           .entity(ImmutableMap.of(
+                               "error",
+                               StringUtils.format(
+                                   "Supervisor[%s] is not a compaction supervisor",
+                                   id,
+                                   spec.getClass().getSimpleName()
+                               )
+                           ))
+                           .build();
+          }
+
+          CompactionSupervisorSpec compactionSpec = (CompactionSupervisorSpec) spec;
+
+          DateTime referenceTime;
+          if (referenceTimeStr != null) {
+            try {
+              referenceTime = DateTimes.of(referenceTimeStr);
+            }
+            catch (IllegalArgumentException e) {
+              return Response.status(Response.Status.BAD_REQUEST)
+                             .entity(ImmutableMap.of(
+                                 "error",
+                                 StringUtils.format("Reference time[%s] is in invalid format. Use ISO 8601 standard format.")

Review Comment:
   ## Missing format argument
   
   This format call refers to 1 argument(s) but only supplies 0 argument(s).
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/10836)



##########
indexing-service/src/main/java/org/apache/druid/indexing/overlord/supervisor/SupervisorResource.java:
##########
@@ -351,6 +357,79 @@
     );
   }
 
+  @GET
+  @Path("/{id}/reindexingTimeline")
+  @Produces(MediaType.APPLICATION_JSON)
+  @ResourceFilters(SupervisorResourceFilter.class)
+  public Response getReindexingTimeline(
+      @PathParam("id") final String id,
+      @QueryParam("referenceTime") @Nullable final String referenceTimeStr
+  )
+  {
+    return asLeaderWithSupervisorManager(
+        manager -> {
+          Optional<SupervisorSpec> specOptional = manager.getSupervisorSpec(id);
+          if (!specOptional.isPresent()) {
+            return Response.status(Response.Status.NOT_FOUND)
+                           .entity(ImmutableMap.of("error", StringUtils.format("Supervisor[%s] does not exist", id)))
+                           .build();
+          }
+
+          SupervisorSpec spec = specOptional.get();
+          if (!(spec instanceof CompactionSupervisorSpec)) {
+            return Response.status(Response.Status.BAD_REQUEST)
+                           .entity(ImmutableMap.of(
+                               "error",
+                               StringUtils.format(
+                                   "Supervisor[%s] is not a compaction supervisor",
+                                   id,
+                                   spec.getClass().getSimpleName()
+                               )
+                           ))
+                           .build();
+          }
+
+          CompactionSupervisorSpec compactionSpec = (CompactionSupervisorSpec) spec;
+
+          DateTime referenceTime;
+          if (referenceTimeStr != null) {
+            try {
+              referenceTime = DateTimes.of(referenceTimeStr);
+            }
+            catch (IllegalArgumentException e) {
+              return Response.status(Response.Status.BAD_REQUEST)
+                             .entity(ImmutableMap.of(
+                                 "error",
+                                 StringUtils.format("Reference time[%s] is in invalid format. Use ISO 8601 standard format.")
+                             ))
+                             .build();
+            }
+          } else {
+            referenceTime = DateTimes.nowUtc();
+          }
+
+          CompactionJobTemplate template = compactionSpec.getTemplate();
+          if (!(template instanceof CascadingReindexingTemplate)) {
+            return Response.status(Response.Status.BAD_REQUEST)
+                           .entity(ImmutableMap.of(
+                               "error",
+                               StringUtils.format(
+                                   "Reindexing timeline is not available for supervisor[%s] as it does not use a cascading template",
+                                   id,
+                                   template.getClass().getSimpleName()
+                               )

Review Comment:
   ## Unused format argument
   
   This format call refers to 1 argument(s) but supplies 2 argument(s).
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/10835)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "vogievetsky (via GitHub)" <gi...@apache.org>.
vogievetsky commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3244865622


##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);
+      const result = resp.data;
+      if (result && result.length > 0 && result[0].result) {
+        const maxTime = result[0].result.maxTime;
+        setQueriedMaxTime(maxTime);
+      } else {
+        AppToaster.show({
+          message: 'No data found in datasource',
+          intent: Intent.WARNING,
+        });
+      }
+    } catch (e) {
+      AppToaster.show({
+        message: `Failed to query max time: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+    } finally {
+      setQueryingMaxTime(false);
+    }
+  };
+
+  // Calculate effective end time if we have queried max time and skipOffsetFromLatest
+  let effectiveEndTime: Date | undefined;
+  if (queriedMaxTime && skipOffset && !skipOffset.isApplied) {
+    const period = skipOffset.period;
+    try {
+      const duration = new Duration(period);
+      effectiveEndTime = duration.shift(new Date(queriedMaxTime), Timezone.UTC, -1);
+    } catch (e) {
+      console.error('Failed to parse skip offset period:', period, e);
+      AppToaster.show({
+        message: `Invalid skip offset period format: ${period}`,
+        intent: Intent.WARNING,
+      });
+    }
+  }
+
+  // Display validation error if present
+  if (validationError) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Invalid Supervisor Configuration">
+          <p>
+            <strong>
+              The segment granularity rule definitions have created an illegal segment granularity
+              timeline.
+            </strong>
+          </p>
+          {validationError.errorType === 'INVALID_GRANULARITY_TIMELINE' &&
+            validationError.olderInterval && (
+              <>
+                <p>
+                  Segment granularity must stay the same or become <strong>coarser</strong> as data
+                  ages from present to past. Your configuration violates this constraint:
+                </p>
+                <ul>
+                  <li>
+                    <strong>Older interval</strong> (further in the past):{' '}
+                    <code>{formatInterval(validationError.olderInterval)}</code> has{' '}
+                    <strong>finer</strong> granularity:{' '}
+                    <Tag intent={Intent.PRIMARY}>{validationError.olderGranularity}</Tag>
+                  </li>
+                  <li>
+                    <strong>Newer interval</strong> (more recent):{' '}
+                    <code>{formatInterval(validationError.newerInterval!)}</code> has{' '}
+                    <strong>coarser</strong> granularity:{' '}
+                    <Tag intent={Intent.WARNING}>{validationError.newerGranularity}</Tag>
+                  </li>
+                </ul>
+                <p>
+                  <strong>To fix this:</strong> Adjust your segment granularity rules so that as
+                  time moves from present to past, the granularity either stays the same or gets
+                  coarser (e.g., HOUR → DAY → MONTH → YEAR).
+                </p>
+              </>
+            )}
+          {validationError.errorType !== 'INVALID_GRANULARITY_TIMELINE' && (
+            <p>{validationError.message}</p>
+          )}
+        </Callout>
+      </div>
+    );
+  }
+
+  if (intervals.length === 0) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.WARNING}>
+          No reindexing intervals found. This may indicate that the rule provider is not ready or no
+          rules are configured.
+        </Callout>
+      </div>
+    );
+  }
+
+  const selectedInterval =
+    selectedIntervalIndex !== undefined ? intervals[selectedIntervalIndex] : undefined;
+
+  return (
+    <div className="reindexing-timeline">
+      <div className="timeline-header">
+        <div className="header-info">
+          <strong>DataSource:</strong> {timelineData.dataSource}
+          <span className="spacer">|</span>
+          <Tooltip
+            content="The reference time used in conjunction with each rule's 'olderThan' attribute to calculate which intervals a rule should apply to."
+            position="bottom"
+          >
+            <strong className="help-hint">Reference Time:</strong>
+          </Tooltip>{' '}
+          {formatDateTimeUTC(referenceTime)}
+        </div>
+        {skipOffset && (
+          <div className="skip-offset-info">
+            {skipOffset.isApplied && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                Skip Offset: {skipOffset.type} ({skipOffset.period})
+              </Tag>
+            )}
+            {!skipOffset.isApplied && !queriedMaxTime && (
+              <>
+                <Tooltip
+                  content={
+                    `This supervisor is configured to skip compaction of any search interval that is covered by ` +
+                    `or overlaps the threshold of the latest timestamp in the data minus ${skipOffset.period}. ` +
+                    `However, the underlying segment data is not available in this preview, so the timeline does not ` +
+                    `reflect which intervals will be skipped during actual compaction.`
+                  }
+                  position="bottom"
+                >
+                  <Tag minimal intent={Intent.WARNING} icon={IconNames.WARNING_SIGN}>
+                    {skipOffset.type} ({skipOffset.period}): Not reflected in this preview
+                  </Tag>
+                </Tooltip>
+                <Button
+                  text="Query latest timestamp"
+                  icon={IconNames.REFRESH}
+                  small
+                  onClick={() => void handleQueryMaxTime()}
+                  loading={queryingMaxTime}
+                  className="query-button"
+                />
+              </>
+            )}
+            {!skipOffset.isApplied && queriedMaxTime && effectiveEndTime && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                {skipOffset.type} ({skipOffset.period}): Applied (latest:{' '}
+                {formatDateTimeUTC(queriedMaxTime)})
+              </Tag>
+            )}
+          </div>
+        )}
+      </div>
+
+      <Card className="timeline-bar-container">
+        <div className="timeline-bar" role="toolbar" aria-label="Reindexing timeline intervals">
+          {intervals.map((interval, idx) => {
+            const [start, end] = interval.interval.split('/');
+            const isSelected = selectedIntervalIndex === idx;
+
+            // Check if interval is skipped due to skip offset (either from API or from queried max time)
+            let isSkipped = interval.ruleCount === 0;
+            if (!isSkipped && effectiveEndTime) {
+              const intervalEnd = new Date(end);
+              isSkipped = intervalEnd > effectiveEndTime;
+            }
+
+            return (
+              <div
+                key={interval.interval}
+                className={`timeline-segment ${isSelected ? 'selected' : ''} ${
+                  isSkipped ? 'skipped' : ''
+                }`}
+                style={{
+                  backgroundColor: isSkipped ? SKIPPED_INTERVAL_COLOR : getIntervalColor(idx),
+                  flex: 1,
+                }}
+                role={isSkipped ? undefined : 'button'}
+                tabIndex={isSkipped ? undefined : 0}
+                aria-label={
+                  isSkipped
+                    ? `Skipped interval ${interval.interval}`
+                    : `Interval ${interval.interval} with ${interval.ruleCount} rule${
+                        interval.ruleCount !== 1 ? 's' : ''
+                      }`
+                }
+                aria-selected={isSelected}
+                onClick={() => !isSkipped && setSelectedIntervalIndex(idx)}
+                onKeyDown={e => {
+                  if (!isSkipped && (e.key === 'Enter' || e.key === ' ')) {
+                    e.preventDefault();
+                    setSelectedIntervalIndex(idx);
+                  }
+                }}
+                title={
+                  isSkipped
+                    ? `${interval.interval}\nSkipped (beyond skip offset)`
+                    : `${interval.interval}\n${interval.ruleCount} rule(s) applied`
+                }
+              >
+                <div className="segment-label">
+                  <div className="segment-date">{formatDateShort(start)}</div>
+                  <div className="segment-date">{formatDateShort(end)}</div>
+                  <div className="segment-rules">
+                    <Tag minimal intent={isSkipped ? Intent.DANGER : undefined}>
+                      {isSkipped
+                        ? 'skipped'
+                        : `${interval.ruleCount} rule${interval.ruleCount !== 1 ? 's' : ''}`}
+                    </Tag>
+                  </div>
+                </div>
+              </div>
+            );
+          })}
+        </div>
+        <div className="timeline-hint">Click on an interval to view its configuration details</div>
+      </Card>
+
+      {selectedInterval && selectedInterval.ruleCount > 0 && (
+        <IntervalDetailPanel
+          interval={selectedInterval}
+          onClose={() => setSelectedIntervalIndex(undefined)}
+        />
+      )}
+    </div>
+  );
+});
+
+function formatDateShort(isoDate: string): string {
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  const d = new Date(isoDate);
+  return `${UTC_MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
+}
+
+const UTC_MONTH_NAMES = [
+  'Jan',
+  'Feb',
+  'Mar',
+  'Apr',
+  'May',
+  'Jun',
+  'Jul',
+  'Aug',
+  'Sep',
+  'Oct',
+  'Nov',
+  'Dec',
+];
+
+function formatDateTimeUTC(isoDate: string): string {
+  // Handle start of time / very old dates
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  // Format using UTC methods to avoid local timezone shifting.
+  // date-fns format() uses the browser's local timezone, so we extract UTC
+  // components manually to ensure the displayed time is actually UTC.
+  const d = new Date(isoDate);
+  const month = UTC_MONTH_NAMES[d.getUTCMonth()];
+  const day = d.getUTCDate();
+  const year = d.getUTCFullYear();
+  const hours = d.getUTCHours();
+  const minutes = String(d.getUTCMinutes()).padStart(2, '0');
+  const ampm = hours >= 12 ? 'PM' : 'AM';
+  const displayHours = hours % 12 || 12;
+  return `${month} ${day}, ${year} ${displayHours}:${minutes} ${ampm} UTC`;
+}
+
+function formatInterval(interval: string): string {
+  const [start, end] = interval.split('/');
+  const formattedStart = start.startsWith('-') ? '-INF' : start;
+  const formattedEnd = end ? end : 'now';
+  return `${formattedStart}/${formattedEnd}`;
+}
+
+function handleCopyToClipboard(data: CompactionConfig | ReindexingRule[], label: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  copy(jsonValue, { format: 'text/plain' });
+  AppToaster.show({
+    message: `${label} copied to clipboard`,
+    intent: Intent.SUCCESS,
+  });
+}
+
+function handleDownloadJson(data: CompactionConfig | ReindexingRule[], filename: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  downloadFile(jsonValue, 'json', filename);
+}
+
+function getPartitionType(tuningConfig: Record<string, unknown> | undefined): string | undefined {
+  if (!tuningConfig) return undefined;
+  const partitionsSpec = tuningConfig.partitionsSpec;
+  if (partitionsSpec && typeof partitionsSpec === 'object' && partitionsSpec !== null) {
+    return (partitionsSpec as Record<string, unknown>).type as string | undefined;
+  }
+  return undefined;
+}
+
+interface IntervalDetailPanelProps {
+  interval: IntervalConfig;
+  onClose: () => void;
+}
+
+function IntervalDetailPanel({ interval, onClose }: IntervalDetailPanelProps) {
+  const [showFullConfig, setShowFullConfig] = useState(false);
+  const [showRawRules, setShowRawRules] = useState(false);
+  const { config } = interval;
+
+  const deletionRuleCount = interval.appliedRules.filter(r => r.type === 'deletion').length;
+  const metricsCount = config.metricsSpec?.length || 0;
+  const dimensionsCount = config.dimensionsSpec?.dimensions?.length || 0;
+  const projectionsCount = config.projections?.length || 0;
+
+  return (
+    <>
+      <Card className="interval-detail-panel">
+        <div className="detail-header">
+          <div>
+            <h3>Interval: {formatInterval(interval.interval)}</h3>
+          </div>
+          <Button
+            icon={IconNames.CROSS}
+            minimal
+            onClick={onClose}
+            aria-label="Close interval details"
+          />
+        </div>
+
+        <div className="detail-content">
+          <Tooltip
+            content="A high-level summary of the merged rule configuration for this interval — use View Full Configuration for complete details."
+            position="bottom"
+          >
+            <div className="config-summary-label">Effective Configuration</div>
+          </Tooltip>
+          <div className="config-badges">
+            {config.granularitySpec?.segmentGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.CALENDAR}>
+                Segment: {config.granularitySpec.segmentGranularity}
+              </Tag>
+            )}
+            {config.granularitySpec?.queryGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.TIME}>
+                Query: {config.granularitySpec.queryGranularity}
+              </Tag>
+            )}
+            {getPartitionType(config.tuningConfig) && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.SPLIT_COLUMNS}>
+                Partitioning: {getPartitionType(config.tuningConfig)}
+              </Tag>
+            )}
+            {metricsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CALCULATOR}>
+                {metricsCount} metric{metricsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {dimensionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TAG}>
+                {dimensionsCount} dimension{dimensionsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {projectionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CUBE}>
+                {projectionsCount} projection{projectionsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {deletionRuleCount > 0 && (
+              <Tag minimal intent={Intent.WARNING} icon={IconNames.TRASH}>
+                {deletionRuleCount} deletion clause{deletionRuleCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+          </div>
+
+          <div className="full-config-section">
+            <Button
+              icon={IconNames.CODE}
+              text="View Full Configuration"

Review Comment:
   Web console has the convention of doing sentence case for buttons and internal labels in general so this should be `"View full configuration"`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Supervisor UI component to view timeline of rules applied for a cascading reindexing supervisor (druid)

Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on PR #19051:
URL: https://github.com/apache/druid/pull/19051#issuecomment-3956695589

   @capistrant , I took the liberty to slightly update the title for clarity. Hope it seems less ambiguous now.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on PR #19051:
URL: https://github.com/apache/druid/pull/19051#issuecomment-4036640130

   @capistrant , is this PR ready for another round of review or should we hold off until the refactor PR #19106  is reviewed and merged?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "vogievetsky (via GitHub)" <gi...@apache.org>.
vogievetsky commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3244879086


##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);
+      const result = resp.data;
+      if (result && result.length > 0 && result[0].result) {
+        const maxTime = result[0].result.maxTime;
+        setQueriedMaxTime(maxTime);
+      } else {
+        AppToaster.show({
+          message: 'No data found in datasource',
+          intent: Intent.WARNING,
+        });
+      }
+    } catch (e) {
+      AppToaster.show({
+        message: `Failed to query max time: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+    } finally {
+      setQueryingMaxTime(false);
+    }
+  };
+
+  // Calculate effective end time if we have queried max time and skipOffsetFromLatest
+  let effectiveEndTime: Date | undefined;
+  if (queriedMaxTime && skipOffset && !skipOffset.isApplied) {
+    const period = skipOffset.period;
+    try {
+      const duration = new Duration(period);
+      effectiveEndTime = duration.shift(new Date(queriedMaxTime), Timezone.UTC, -1);
+    } catch (e) {
+      console.error('Failed to parse skip offset period:', period, e);
+      AppToaster.show({
+        message: `Invalid skip offset period format: ${period}`,
+        intent: Intent.WARNING,
+      });
+    }
+  }
+
+  // Display validation error if present
+  if (validationError) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Invalid Supervisor Configuration">
+          <p>
+            <strong>
+              The segment granularity rule definitions have created an illegal segment granularity
+              timeline.
+            </strong>
+          </p>
+          {validationError.errorType === 'INVALID_GRANULARITY_TIMELINE' &&
+            validationError.olderInterval && (
+              <>
+                <p>
+                  Segment granularity must stay the same or become <strong>coarser</strong> as data
+                  ages from present to past. Your configuration violates this constraint:
+                </p>
+                <ul>
+                  <li>
+                    <strong>Older interval</strong> (further in the past):{' '}
+                    <code>{formatInterval(validationError.olderInterval)}</code> has{' '}
+                    <strong>finer</strong> granularity:{' '}
+                    <Tag intent={Intent.PRIMARY}>{validationError.olderGranularity}</Tag>
+                  </li>
+                  <li>
+                    <strong>Newer interval</strong> (more recent):{' '}
+                    <code>{formatInterval(validationError.newerInterval!)}</code> has{' '}
+                    <strong>coarser</strong> granularity:{' '}
+                    <Tag intent={Intent.WARNING}>{validationError.newerGranularity}</Tag>
+                  </li>
+                </ul>
+                <p>
+                  <strong>To fix this:</strong> Adjust your segment granularity rules so that as
+                  time moves from present to past, the granularity either stays the same or gets
+                  coarser (e.g., HOUR → DAY → MONTH → YEAR).
+                </p>
+              </>
+            )}
+          {validationError.errorType !== 'INVALID_GRANULARITY_TIMELINE' && (
+            <p>{validationError.message}</p>
+          )}
+        </Callout>
+      </div>
+    );
+  }
+
+  if (intervals.length === 0) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.WARNING}>
+          No reindexing intervals found. This may indicate that the rule provider is not ready or no
+          rules are configured.
+        </Callout>
+      </div>
+    );
+  }
+
+  const selectedInterval =
+    selectedIntervalIndex !== undefined ? intervals[selectedIntervalIndex] : undefined;
+
+  return (
+    <div className="reindexing-timeline">
+      <div className="timeline-header">
+        <div className="header-info">
+          <strong>DataSource:</strong> {timelineData.dataSource}
+          <span className="spacer">|</span>
+          <Tooltip
+            content="The reference time used in conjunction with each rule's 'olderThan' attribute to calculate which intervals a rule should apply to."
+            position="bottom"
+          >
+            <strong className="help-hint">Reference Time:</strong>
+          </Tooltip>{' '}
+          {formatDateTimeUTC(referenceTime)}
+        </div>
+        {skipOffset && (
+          <div className="skip-offset-info">
+            {skipOffset.isApplied && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                Skip Offset: {skipOffset.type} ({skipOffset.period})
+              </Tag>
+            )}
+            {!skipOffset.isApplied && !queriedMaxTime && (
+              <>
+                <Tooltip
+                  content={
+                    `This supervisor is configured to skip compaction of any search interval that is covered by ` +
+                    `or overlaps the threshold of the latest timestamp in the data minus ${skipOffset.period}. ` +
+                    `However, the underlying segment data is not available in this preview, so the timeline does not ` +
+                    `reflect which intervals will be skipped during actual compaction.`
+                  }
+                  position="bottom"
+                >
+                  <Tag minimal intent={Intent.WARNING} icon={IconNames.WARNING_SIGN}>
+                    {skipOffset.type} ({skipOffset.period}): Not reflected in this preview
+                  </Tag>
+                </Tooltip>
+                <Button
+                  text="Query latest timestamp"
+                  icon={IconNames.REFRESH}
+                  small
+                  onClick={() => void handleQueryMaxTime()}
+                  loading={queryingMaxTime}
+                  className="query-button"
+                />
+              </>
+            )}
+            {!skipOffset.isApplied && queriedMaxTime && effectiveEndTime && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                {skipOffset.type} ({skipOffset.period}): Applied (latest:{' '}
+                {formatDateTimeUTC(queriedMaxTime)})
+              </Tag>
+            )}
+          </div>
+        )}
+      </div>
+
+      <Card className="timeline-bar-container">
+        <div className="timeline-bar" role="toolbar" aria-label="Reindexing timeline intervals">
+          {intervals.map((interval, idx) => {
+            const [start, end] = interval.interval.split('/');
+            const isSelected = selectedIntervalIndex === idx;
+
+            // Check if interval is skipped due to skip offset (either from API or from queried max time)
+            let isSkipped = interval.ruleCount === 0;
+            if (!isSkipped && effectiveEndTime) {
+              const intervalEnd = new Date(end);
+              isSkipped = intervalEnd > effectiveEndTime;
+            }
+
+            return (
+              <div
+                key={interval.interval}
+                className={`timeline-segment ${isSelected ? 'selected' : ''} ${
+                  isSkipped ? 'skipped' : ''
+                }`}
+                style={{
+                  backgroundColor: isSkipped ? SKIPPED_INTERVAL_COLOR : getIntervalColor(idx),
+                  flex: 1,
+                }}
+                role={isSkipped ? undefined : 'button'}
+                tabIndex={isSkipped ? undefined : 0}
+                aria-label={
+                  isSkipped
+                    ? `Skipped interval ${interval.interval}`
+                    : `Interval ${interval.interval} with ${interval.ruleCount} rule${
+                        interval.ruleCount !== 1 ? 's' : ''
+                      }`
+                }
+                aria-selected={isSelected}
+                onClick={() => !isSkipped && setSelectedIntervalIndex(idx)}
+                onKeyDown={e => {
+                  if (!isSkipped && (e.key === 'Enter' || e.key === ' ')) {
+                    e.preventDefault();
+                    setSelectedIntervalIndex(idx);
+                  }
+                }}
+                title={
+                  isSkipped
+                    ? `${interval.interval}\nSkipped (beyond skip offset)`
+                    : `${interval.interval}\n${interval.ruleCount} rule(s) applied`
+                }
+              >
+                <div className="segment-label">
+                  <div className="segment-date">{formatDateShort(start)}</div>
+                  <div className="segment-date">{formatDateShort(end)}</div>
+                  <div className="segment-rules">
+                    <Tag minimal intent={isSkipped ? Intent.DANGER : undefined}>
+                      {isSkipped
+                        ? 'skipped'
+                        : `${interval.ruleCount} rule${interval.ruleCount !== 1 ? 's' : ''}`}
+                    </Tag>
+                  </div>
+                </div>
+              </div>
+            );
+          })}
+        </div>
+        <div className="timeline-hint">Click on an interval to view its configuration details</div>
+      </Card>
+
+      {selectedInterval && selectedInterval.ruleCount > 0 && (
+        <IntervalDetailPanel
+          interval={selectedInterval}
+          onClose={() => setSelectedIntervalIndex(undefined)}
+        />
+      )}
+    </div>
+  );
+});
+
+function formatDateShort(isoDate: string): string {
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  const d = new Date(isoDate);
+  return `${UTC_MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
+}
+
+const UTC_MONTH_NAMES = [
+  'Jan',
+  'Feb',
+  'Mar',
+  'Apr',
+  'May',
+  'Jun',
+  'Jul',
+  'Aug',
+  'Sep',
+  'Oct',
+  'Nov',
+  'Dec',
+];
+
+function formatDateTimeUTC(isoDate: string): string {
+  // Handle start of time / very old dates
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  // Format using UTC methods to avoid local timezone shifting.
+  // date-fns format() uses the browser's local timezone, so we extract UTC
+  // components manually to ensure the displayed time is actually UTC.
+  const d = new Date(isoDate);
+  const month = UTC_MONTH_NAMES[d.getUTCMonth()];
+  const day = d.getUTCDate();
+  const year = d.getUTCFullYear();
+  const hours = d.getUTCHours();
+  const minutes = String(d.getUTCMinutes()).padStart(2, '0');
+  const ampm = hours >= 12 ? 'PM' : 'AM';
+  const displayHours = hours % 12 || 12;
+  return `${month} ${day}, ${year} ${displayHours}:${minutes} ${ampm} UTC`;
+}
+
+function formatInterval(interval: string): string {
+  const [start, end] = interval.split('/');
+  const formattedStart = start.startsWith('-') ? '-INF' : start;
+  const formattedEnd = end ? end : 'now';
+  return `${formattedStart}/${formattedEnd}`;
+}
+
+function handleCopyToClipboard(data: CompactionConfig | ReindexingRule[], label: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  copy(jsonValue, { format: 'text/plain' });
+  AppToaster.show({
+    message: `${label} copied to clipboard`,
+    intent: Intent.SUCCESS,
+  });
+}
+
+function handleDownloadJson(data: CompactionConfig | ReindexingRule[], filename: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  downloadFile(jsonValue, 'json', filename);
+}
+
+function getPartitionType(tuningConfig: Record<string, unknown> | undefined): string | undefined {
+  if (!tuningConfig) return undefined;
+  const partitionsSpec = tuningConfig.partitionsSpec;
+  if (partitionsSpec && typeof partitionsSpec === 'object' && partitionsSpec !== null) {
+    return (partitionsSpec as Record<string, unknown>).type as string | undefined;
+  }
+  return undefined;
+}
+
+interface IntervalDetailPanelProps {
+  interval: IntervalConfig;
+  onClose: () => void;
+}
+
+function IntervalDetailPanel({ interval, onClose }: IntervalDetailPanelProps) {
+  const [showFullConfig, setShowFullConfig] = useState(false);
+  const [showRawRules, setShowRawRules] = useState(false);
+  const { config } = interval;
+
+  const deletionRuleCount = interval.appliedRules.filter(r => r.type === 'deletion').length;
+  const metricsCount = config.metricsSpec?.length || 0;
+  const dimensionsCount = config.dimensionsSpec?.dimensions?.length || 0;
+  const projectionsCount = config.projections?.length || 0;
+
+  return (
+    <>
+      <Card className="interval-detail-panel">
+        <div className="detail-header">
+          <div>
+            <h3>Interval: {formatInterval(interval.interval)}</h3>
+          </div>
+          <Button
+            icon={IconNames.CROSS}
+            minimal
+            onClick={onClose}
+            aria-label="Close interval details"
+          />
+        </div>
+
+        <div className="detail-content">
+          <Tooltip
+            content="A high-level summary of the merged rule configuration for this interval — use View Full Configuration for complete details."
+            position="bottom"
+          >
+            <div className="config-summary-label">Effective Configuration</div>
+          </Tooltip>
+          <div className="config-badges">
+            {config.granularitySpec?.segmentGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.CALENDAR}>
+                Segment: {config.granularitySpec.segmentGranularity}
+              </Tag>
+            )}
+            {config.granularitySpec?.queryGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.TIME}>
+                Query: {config.granularitySpec.queryGranularity}
+              </Tag>
+            )}
+            {getPartitionType(config.tuningConfig) && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.SPLIT_COLUMNS}>
+                Partitioning: {getPartitionType(config.tuningConfig)}
+              </Tag>
+            )}
+            {metricsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CALCULATOR}>
+                {metricsCount} metric{metricsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {dimensionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TAG}>
+                {dimensionsCount} dimension{dimensionsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {projectionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CUBE}>
+                {projectionsCount} projection{projectionsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {deletionRuleCount > 0 && (
+              <Tag minimal intent={Intent.WARNING} icon={IconNames.TRASH}>
+                {deletionRuleCount} deletion clause{deletionRuleCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+          </div>
+
+          <div className="full-config-section">
+            <Button
+              icon={IconNames.CODE}
+              text="View Full Configuration"
+              intent={Intent.PRIMARY}
+              onClick={() => setShowFullConfig(true)}
+            />
+            <Button
+              icon={IconNames.PROPERTIES}
+              text={`View ${interval.ruleCount} Raw Rule${interval.ruleCount !== 1 ? 's' : ''}`}
+              intent={Intent.PRIMARY}
+              onClick={() => setShowRawRules(true)}
+            />
+          </div>
+        </div>
+      </Card>
+
+      <Dialog
+        isOpen={showFullConfig}
+        onClose={() => setShowFullConfig(false)}
+        title={
+          <Tooltip content={interval.interval} position="bottom">
+            <span>{formatInterval(interval.interval)}</span>
+          </Tooltip>
+        }
+        className="reindexing-config-dialog"
+        canOutsideClickClose
+      >
+        <div className="bp5-dialog-body">
+          <ConfigJsonViewer config={config} />
+        </div>
+        <div className="bp5-dialog-footer">
+          <div className="bp5-dialog-footer-actions">
+            <Button
+              text="Copy"
+              icon={IconNames.DUPLICATE}
+              intent={Intent.PRIMARY}
+              onClick={() => handleCopyToClipboard(config, 'Configuration')}
+            />
+            <Button
+              text="Download"
+              icon={IconNames.DOWNLOAD}
+              intent={Intent.PRIMARY}
+              onClick={() =>
+                handleDownloadJson(
+                  config,
+                  `reindexing-config-${interval.interval.replace(/\//g, '-')}.json`,
+                )
+              }
+            />

Review Comment:
   neither of the buttons should be primary. There should be a primary `Close` button instead.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "capistrant (via GitHub)" <gi...@apache.org>.
capistrant commented on PR #19051:
URL: https://github.com/apache/druid/pull/19051#issuecomment-4623295795

   https://github.com/apache/druid/pull/19511 is going to handle the API changes and @vogievetsky is going to tackle the UI


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3234378700


##########
web-console/src/dialogs/supervisor-table-action-dialog/supervisor-table-action-dialog.tsx:
##########
@@ -67,6 +69,16 @@ export const SupervisorTableActionDialog = React.memo(function SupervisorTableAc
       active: activeTab === 'history',
       onClick: () => setActiveTab('history'),
     },
+    ...(isCompactionSupervisor

Review Comment:
   [P3] Hide the timeline tab for non-cascading compaction supervisors
   
   This adds the Timeline tab for every supervisor ID that starts with `autocompact__`, but the new endpoint returns 400 unless the compaction supervisor template is `CascadingReindexingTemplate`. Existing inline-config compaction supervisors also use `autocompact__` IDs, so standard compaction supervisors now expose a tab that only shows an error. Gate the tab on the loaded supervisor spec/template type, or render a deliberate unavailable state instead of adding the tab solely from the ID prefix.



##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);

Review Comment:
   [P2] Compute skipOffsetFromLatest from the supervisor timeline
   
   The `Query latest timestamp` path bases the preview boundary on a broker timeBoundary `maxTime`, then subtracts the period in the browser. The actual cascading supervisor path applies `skipOffsetFromLatest` to the segment timeline end and then truncates to an interval granularity-aligned boundary, so row maxTime can be earlier than the segment end and straddling intervals are handled differently. For normal DAY/HOUR segments this can show intervals as skipped or active at the wrong boundary. Please derive the preview from segment metadata/server-side timeline logic, or mirror the same segment-end and granularity-alignment rules.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "capistrant (via GitHub)" <gi...@apache.org>.
capistrant commented on PR #19051:
URL: https://github.com/apache/druid/pull/19051#issuecomment-3960543722

   > Was trying out the embedded test in this PR to check out the timeline.
   > 
   > @capistrant , in the snapshot below, what does the "4 rules applied" mean? The widget below it shows only 2 items - a segment granularity and a deletion rule.
   > 
   > Maybe we should include an info popup for each of the chips. Also, the chip says `"1" deletion rule". When can there be more than 1 for a single interval?
   > 
   > <img alt="Screenshot 2026-02-25 at 12 50 41 PM" width="807" height="492" src="https://private-user-images.githubusercontent.com/18635897/554596525-8df48aa6-b54b-470a-a855-e0330c492bbb.png?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3NzIwMzczNDcsIm5iZiI6MTc3MjAzNzA0NywicGF0aCI6Ii8xODYzNTg5Ny81NTQ1OTY1MjUtOGRmNDhhYTYtYjU0Yi00NzBhLWE4NTUtZTAzMzBjNDkyYmJiLnBuZz9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNjAyMjUlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjYwMjI1VDE2MzA0N1omWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTRlODI3ZDZhMjVkYjE2ZTFlZjBmYjcyNzg4NDJlZjM2ZTcxZmM0NDQwMDUyZTc2NDc2MjQ2MzgxNTg1NTE1MDYmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0In0.boL_Iwu_IreHk7O7BkeJ_Q3UDtzh4iwmTSLlSIbc30E">
   
   4 rules applied means that the config created for the interval is made up of 4 different reindexing rules. In this case based on the test I assume you are running, it is
   * segmentGran rule
   * deletion rule
   * ioConfig rule
   * tuningConfig rule
   
   You could confirm by clicking the view raw rules button.
   
   I think this is a UX issue. Hand up, I don't have any experience curating a good UX :). If I had to guess what UX decision is best here, it is to remove the `N rules applied` chip. if someone really wants to see the explicit underlying rules they can click view raw rules.
   
   As for deletion rules, N deletion rules can apply to any given interval. They accumulate (unlike other rule types). Every deletion rule that applies a search interval will be combined together.
   * deleteWhere "countryName=france" olderThan P7D"
   * deleteWhere "countryName=italy" olderThan P14D"
   
   Any interval where both of those apply would have 2 deletion rules.
   
   The chips are intended to give very quick reference to what is in the config for the given search interval. They are not strictly tied to rules even. In my pictures you see metrics and dims in separate chips, but both belong to the same rule. So maybe the deletion rules chip should actually be like 2 deletion filters or 2 deletion clauses. I didn't know how valuable chips would be for tuningConfig and ioConfig so those are not surfaced, likely leading to your initial confusion. You'd have to view the config payload or the raw rules to see them.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3141586117


##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CascadingReindexingTemplate.java:
##########
@@ -262,6 +288,121 @@ private static boolean intervalEndsAfter(Interval interval, DateTime boundary)
     return interval.getEnd().isAfter(boundary);
   }
 
+  /**
+   * Generates a timeline view showing the search intervals and their associated reindexing
+   * configurations. This is useful for operators to understand how rules are applied across
+   * different time periods and to preview the effects of rule changes before they are applied.
+   *
+   * @param referenceTime the reference time to use for computing rule periods (typically DateTime.now())
+   * @return a view of the reindexing timeline with intervals and their configs
+   */
+  public ReindexingTimelineView getReindexingTimelineView(DateTime referenceTime)
+  {
+    if (!ruleProvider.isReady()) {
+      LOG.info(
+          "Rule provider [%s] is not ready, returning empty timeline for dataSource[%s]",
+          ruleProvider.getType(),
+          dataSource
+      );
+      return new ReindexingTimelineView(dataSource, referenceTime, null, Collections.emptyList(), null);
+    }
+
+    List<IntervalPartitioningInfo> searchIntervals;
+    try {
+      searchIntervals = generateAlignedSearchIntervals(referenceTime);
+    }
+    catch (SegmentGranularityTimelineValidationException e) {
+      return createValidationErrorView(
+          e,
+          referenceTime,
+          "INVALID_GRANULARITY_TIMELINE",
+          e.getOlderInterval().toString(),
+          e.getOlderGranularity().toString(),
+          e.getNewerInterval().toString(),
+          e.getNewerGranularity().toString()
+      );
+    }
+    catch (IAE e) {
+      return createValidationErrorView(
+          e,
+          referenceTime,
+          "VALIDATION_ERROR",
+          null,
+          null,
+          null,
+          null
+      );
+    }
+
+    if (searchIntervals.isEmpty()) {
+      LOG.warn("No search intervals generated for dataSource[%s]", dataSource);
+      return new ReindexingTimelineView(dataSource, referenceTime, null, Collections.emptyList(), null);
+    }
+
+    // Calculate effective end time based on skip offset
+    DateTime effectiveEndTime = referenceTime;
+    ReindexingTimelineView.SkipOffsetInfo skipOffsetInfo = null;
+
+    if (skipOffsetFromNow != null) {
+      effectiveEndTime = referenceTime.minus(skipOffsetFromNow);
+      skipOffsetInfo = new ReindexingTimelineView.SkipOffsetInfo(
+          "skipOffsetFromNow",
+          skipOffsetFromNow,
+          true,
+          effectiveEndTime,
+          null
+      );
+    } else if (skipOffsetFromLatest != null) {
+      // skipOffsetFromLatest requires actual timeline data, so we can't apply it in preview mode
+      skipOffsetInfo = new ReindexingTimelineView.SkipOffsetInfo(
+          "skipOffsetFromLatest",
+          skipOffsetFromLatest,
+          false,
+          null,
+          "Requires actual segment timeline data"
+      );
+    }
+
+    // Build configs for each interval
+    List<ReindexingTimelineView.IntervalConfig> intervalConfigs = new ArrayList<>();
+    for (IntervalPartitioningInfo intervalInfo : searchIntervals) {
+      Interval searchInterval = intervalInfo.getInterval();
+
+      // Check if interval extends past skip offset
+      if (intervalEndsAfter(searchInterval, effectiveEndTime)) {
+        // Include in timeline, but indicate skipped by applying no rules.
+        intervalConfigs.add(new ReindexingTimelineView.IntervalConfig(
+            searchInterval,
+            0,
+            null,
+            Collections.emptyList()
+        ));
+        continue;
+      }
+
+      InlineSchemaDataSourceCompactionConfig.Builder builder = createBaseBuilder();
+      ReindexingConfigBuilder configBuilder = new ReindexingConfigBuilder(
+          ruleProvider,
+          searchInterval,
+          referenceTime,
+          searchIntervals,
+          null

Review Comment:
   P2 Timeline preview drops template tuningConfig
   
   getReindexingTimelineView builds each interval config with a ReindexingConfigBuilder whose baseTuningConfig is null, while createCompactionJobs passes the template's tuningConfig into the same builder. Any cascading supervisor with static tuning settings such as maxRowsInMemory, splitHintSpec, maxNumConcurrentSubTasks, indexSpecForIntermediatePersists, or retry/chat settings will have those settings in the actual compaction jobs but not in the new reindexingTimeline API response or downloaded UI config. This makes the preview/API incompatible with the real effective config. Pass tuningConfig here as createCompactionJobs does, and add a test that a non-partitionsSpec tuning field survives in the timeline view.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Cascading Reindexing Supervisor UI component fore viewing timeline of rule applications (druid)

Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r2850470824


##########
indexing-service/src/test/java/org/apache/druid/indexing/compact/CascadingReindexingTemplateTest.java:
##########
@@ -1507,6 +1516,323 @@
     );
   }
 
+  /**
+   * Comprehensive test covering:
+   * - Multiple intervals with different segment granularities
+   * - All rule types (segment gran, data schema, deletion, tuning, IO)
+   * - Non-segment-gran rules triggering interval splitting
+   * - Applied rules tracking with correct rule types in each interval
+   * - Full DataSourceCompactionConfig generation
+   * - Rule count accuracy
+   */
+  @Test
+  public void test_getReindexingTimelineView_comprehensive()
+  {
+    DateTime referenceTime = DateTimes.of("2025-02-01T00:00:00Z");
+
+    // Create rules with various periods to test interval generation and splitting
+    ReindexingSegmentGranularityRule segGran7d = new ReindexingSegmentGranularityRule(
+        "seg-gran-7d",
+        null,
+        Period.days(7),
+        Granularities.HOUR
+    );
+
+    ReindexingSegmentGranularityRule segGran30d = new ReindexingSegmentGranularityRule(
+        "seg-gran-30d",
+        null,
+        Period.days(30),
+        Granularities.DAY
+    );
+
+    // Data schema rule at P15D (will split the HOUR interval)
+    ReindexingDataSchemaRule dataSchema15d = new ReindexingDataSchemaRule(
+        "data-schema-15d",
+        null,
+        Period.days(15),
+        new UserCompactionTaskDimensionsConfig(null),
+        new AggregatorFactory[]{new CountAggregatorFactory("count")},
+        Granularities.MINUTE,
+        true,
+        null
+    );
+
+    // Deletion rules at different periods
+    ReindexingDeletionRule deletion10d = new ReindexingDeletionRule(
+        "deletion-10d",
+        null,
+        Period.days(10),
+        new EqualityFilter("country", ColumnType.STRING, "US", null),
+        null
+    );
+
+    ReindexingDeletionRule deletion20d = new ReindexingDeletionRule(
+        "deletion-20d",
+        null,
+        Period.days(20),
+        new EqualityFilter("device", ColumnType.STRING, "mobile", null),
+        null
+    );
+
+    // Tuning and IO rules
+    ReindexingTuningConfigRule tuning7d = new ReindexingTuningConfigRule(
+        "tuning-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskQueryTuningConfig(
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null
+        )
+    );
+
+    ReindexingIOConfigRule io7d = new ReindexingIOConfigRule(
+        "io-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskIOConfig(true)
+    );
+
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()
+                                                                  .segmentGranularityRules(List.of(segGran7d, segGran30d))
+                                                                  .dataSchemaRules(List.of(dataSchema15d))
+                                                                  .deletionRules(List.of(deletion10d, deletion20d))
+                                                                  .tuningConfigRules(List.of(tuning7d))
+                                                                  .ioConfigRules(List.of(io7d))
+                                                                  .build();
+
+    CascadingReindexingTemplate template = new CascadingReindexingTemplate(
+        "testDS",
+        null,
+        null,
+        provider,
+        null,
+        null,
+        null,
+        null,
+        Granularities.DAY
+    );
+
+    ReindexingTimelineView timeline = template.getReindexingTimelineView(referenceTime);
+
+    // Verify basic timeline properties
+    Assertions.assertEquals("testDS", timeline.getDataSource());
+    Assertions.assertEquals(referenceTime, timeline.getReferenceTime());
+    Assertions.assertNull(timeline.getValidationError());
+    Assertions.assertNull(timeline.getSkipOffset());
+
+    // Verify we have multiple intervals (splitting should occur)
+    Assertions.assertTrue(timeline.getIntervals().size() >= 2, "Expected at least 2 intervals");
+
+    // Verify each interval has correct structure
+    for (ReindexingTimelineView.IntervalConfig intervalConfig : timeline.getIntervals()) {
+      Assertions.assertNotNull(intervalConfig.getInterval());
+      Assertions.assertTrue(intervalConfig.getRuleCount() > 0, "Rule count should be > 0");
+      Assertions.assertNotNull(intervalConfig.getConfig());
+      Assertions.assertNotNull(intervalConfig.getAppliedRules());
+      Assertions.assertEquals(
+          intervalConfig.getRuleCount(),
+          intervalConfig.getAppliedRules().size(),
+          "Applied rules size should match rule count"
+      );
+
+      // Verify config has expected components
+      DataSourceCompactionConfig config = intervalConfig.getConfig();
+      Assertions.assertNotNull(config.getGranularitySpec(), "Should have granularity spec");
+      Assertions.assertNotNull(config.getGranularitySpec().getSegmentGranularity(), "Should have segment granularity");
+
+      // Verify appliedRules contain expected rule types
+      boolean hasTuningRule = intervalConfig.getAppliedRules().stream()
+                                            .anyMatch(r -> r instanceof ReindexingTuningConfigRule);
+      boolean hasIORule = intervalConfig.getAppliedRules().stream()
+                                        .anyMatch(r -> r instanceof ReindexingIOConfigRule);
+      boolean hasDataSchemaRule = intervalConfig.getAppliedRules().stream()
+                                                .anyMatch(r -> r instanceof ReindexingDataSchemaRule);
+      boolean hasDeletionRule = intervalConfig.getAppliedRules().stream()
+                                              .anyMatch(r -> r instanceof ReindexingDeletionRule);

Review Comment:
   ## Unread local variable
   
   Variable 'boolean hasDeletionRule' is never read.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/10831)



##########
indexing-service/src/test/java/org/apache/druid/indexing/compact/CascadingReindexingTemplateTest.java:
##########
@@ -1507,6 +1516,323 @@
     );
   }
 
+  /**
+   * Comprehensive test covering:
+   * - Multiple intervals with different segment granularities
+   * - All rule types (segment gran, data schema, deletion, tuning, IO)
+   * - Non-segment-gran rules triggering interval splitting
+   * - Applied rules tracking with correct rule types in each interval
+   * - Full DataSourceCompactionConfig generation
+   * - Rule count accuracy
+   */
+  @Test
+  public void test_getReindexingTimelineView_comprehensive()
+  {
+    DateTime referenceTime = DateTimes.of("2025-02-01T00:00:00Z");
+
+    // Create rules with various periods to test interval generation and splitting
+    ReindexingSegmentGranularityRule segGran7d = new ReindexingSegmentGranularityRule(
+        "seg-gran-7d",
+        null,
+        Period.days(7),
+        Granularities.HOUR
+    );
+
+    ReindexingSegmentGranularityRule segGran30d = new ReindexingSegmentGranularityRule(
+        "seg-gran-30d",
+        null,
+        Period.days(30),
+        Granularities.DAY
+    );
+
+    // Data schema rule at P15D (will split the HOUR interval)
+    ReindexingDataSchemaRule dataSchema15d = new ReindexingDataSchemaRule(
+        "data-schema-15d",
+        null,
+        Period.days(15),
+        new UserCompactionTaskDimensionsConfig(null),
+        new AggregatorFactory[]{new CountAggregatorFactory("count")},
+        Granularities.MINUTE,
+        true,
+        null
+    );
+
+    // Deletion rules at different periods
+    ReindexingDeletionRule deletion10d = new ReindexingDeletionRule(
+        "deletion-10d",
+        null,
+        Period.days(10),
+        new EqualityFilter("country", ColumnType.STRING, "US", null),
+        null
+    );
+
+    ReindexingDeletionRule deletion20d = new ReindexingDeletionRule(
+        "deletion-20d",
+        null,
+        Period.days(20),
+        new EqualityFilter("device", ColumnType.STRING, "mobile", null),
+        null
+    );
+
+    // Tuning and IO rules
+    ReindexingTuningConfigRule tuning7d = new ReindexingTuningConfigRule(
+        "tuning-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskQueryTuningConfig(
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null
+        )
+    );
+
+    ReindexingIOConfigRule io7d = new ReindexingIOConfigRule(
+        "io-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskIOConfig(true)
+    );
+
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()
+                                                                  .segmentGranularityRules(List.of(segGran7d, segGran30d))
+                                                                  .dataSchemaRules(List.of(dataSchema15d))
+                                                                  .deletionRules(List.of(deletion10d, deletion20d))
+                                                                  .tuningConfigRules(List.of(tuning7d))
+                                                                  .ioConfigRules(List.of(io7d))
+                                                                  .build();
+
+    CascadingReindexingTemplate template = new CascadingReindexingTemplate(
+        "testDS",
+        null,
+        null,
+        provider,
+        null,
+        null,
+        null,
+        null,
+        Granularities.DAY
+    );
+
+    ReindexingTimelineView timeline = template.getReindexingTimelineView(referenceTime);
+
+    // Verify basic timeline properties
+    Assertions.assertEquals("testDS", timeline.getDataSource());
+    Assertions.assertEquals(referenceTime, timeline.getReferenceTime());
+    Assertions.assertNull(timeline.getValidationError());
+    Assertions.assertNull(timeline.getSkipOffset());
+
+    // Verify we have multiple intervals (splitting should occur)
+    Assertions.assertTrue(timeline.getIntervals().size() >= 2, "Expected at least 2 intervals");
+
+    // Verify each interval has correct structure
+    for (ReindexingTimelineView.IntervalConfig intervalConfig : timeline.getIntervals()) {
+      Assertions.assertNotNull(intervalConfig.getInterval());
+      Assertions.assertTrue(intervalConfig.getRuleCount() > 0, "Rule count should be > 0");
+      Assertions.assertNotNull(intervalConfig.getConfig());
+      Assertions.assertNotNull(intervalConfig.getAppliedRules());
+      Assertions.assertEquals(
+          intervalConfig.getRuleCount(),
+          intervalConfig.getAppliedRules().size(),
+          "Applied rules size should match rule count"
+      );
+
+      // Verify config has expected components
+      DataSourceCompactionConfig config = intervalConfig.getConfig();
+      Assertions.assertNotNull(config.getGranularitySpec(), "Should have granularity spec");
+      Assertions.assertNotNull(config.getGranularitySpec().getSegmentGranularity(), "Should have segment granularity");
+
+      // Verify appliedRules contain expected rule types
+      boolean hasTuningRule = intervalConfig.getAppliedRules().stream()
+                                            .anyMatch(r -> r instanceof ReindexingTuningConfigRule);
+      boolean hasIORule = intervalConfig.getAppliedRules().stream()
+                                        .anyMatch(r -> r instanceof ReindexingIOConfigRule);
+      boolean hasDataSchemaRule = intervalConfig.getAppliedRules().stream()
+                                                .anyMatch(r -> r instanceof ReindexingDataSchemaRule);

Review Comment:
   ## Unread local variable
   
   Variable 'boolean hasDataSchemaRule' is never read.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/10830)



##########
indexing-service/src/test/java/org/apache/druid/indexing/compact/CascadingReindexingTemplateTest.java:
##########
@@ -1507,6 +1516,323 @@
     );
   }
 
+  /**
+   * Comprehensive test covering:
+   * - Multiple intervals with different segment granularities
+   * - All rule types (segment gran, data schema, deletion, tuning, IO)
+   * - Non-segment-gran rules triggering interval splitting
+   * - Applied rules tracking with correct rule types in each interval
+   * - Full DataSourceCompactionConfig generation
+   * - Rule count accuracy
+   */
+  @Test
+  public void test_getReindexingTimelineView_comprehensive()
+  {
+    DateTime referenceTime = DateTimes.of("2025-02-01T00:00:00Z");
+
+    // Create rules with various periods to test interval generation and splitting
+    ReindexingSegmentGranularityRule segGran7d = new ReindexingSegmentGranularityRule(
+        "seg-gran-7d",
+        null,
+        Period.days(7),
+        Granularities.HOUR
+    );
+
+    ReindexingSegmentGranularityRule segGran30d = new ReindexingSegmentGranularityRule(
+        "seg-gran-30d",
+        null,
+        Period.days(30),
+        Granularities.DAY
+    );
+
+    // Data schema rule at P15D (will split the HOUR interval)
+    ReindexingDataSchemaRule dataSchema15d = new ReindexingDataSchemaRule(
+        "data-schema-15d",
+        null,
+        Period.days(15),
+        new UserCompactionTaskDimensionsConfig(null),
+        new AggregatorFactory[]{new CountAggregatorFactory("count")},
+        Granularities.MINUTE,
+        true,
+        null
+    );
+
+    // Deletion rules at different periods
+    ReindexingDeletionRule deletion10d = new ReindexingDeletionRule(
+        "deletion-10d",
+        null,
+        Period.days(10),
+        new EqualityFilter("country", ColumnType.STRING, "US", null),
+        null
+    );
+
+    ReindexingDeletionRule deletion20d = new ReindexingDeletionRule(
+        "deletion-20d",
+        null,
+        Period.days(20),
+        new EqualityFilter("device", ColumnType.STRING, "mobile", null),
+        null
+    );
+
+    // Tuning and IO rules
+    ReindexingTuningConfigRule tuning7d = new ReindexingTuningConfigRule(
+        "tuning-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskQueryTuningConfig(
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null,
+            null
+        )
+    );
+
+    ReindexingIOConfigRule io7d = new ReindexingIOConfigRule(
+        "io-7d",
+        null,
+        Period.days(7),
+        new UserCompactionTaskIOConfig(true)
+    );
+
+    ReindexingRuleProvider provider = InlineReindexingRuleProvider.builder()
+                                                                  .segmentGranularityRules(List.of(segGran7d, segGran30d))
+                                                                  .dataSchemaRules(List.of(dataSchema15d))
+                                                                  .deletionRules(List.of(deletion10d, deletion20d))
+                                                                  .tuningConfigRules(List.of(tuning7d))
+                                                                  .ioConfigRules(List.of(io7d))
+                                                                  .build();
+
+    CascadingReindexingTemplate template = new CascadingReindexingTemplate(
+        "testDS",
+        null,
+        null,
+        provider,
+        null,
+        null,
+        null,
+        null,
+        Granularities.DAY
+    );
+
+    ReindexingTimelineView timeline = template.getReindexingTimelineView(referenceTime);
+
+    // Verify basic timeline properties
+    Assertions.assertEquals("testDS", timeline.getDataSource());
+    Assertions.assertEquals(referenceTime, timeline.getReferenceTime());
+    Assertions.assertNull(timeline.getValidationError());
+    Assertions.assertNull(timeline.getSkipOffset());
+
+    // Verify we have multiple intervals (splitting should occur)
+    Assertions.assertTrue(timeline.getIntervals().size() >= 2, "Expected at least 2 intervals");
+
+    // Verify each interval has correct structure
+    for (ReindexingTimelineView.IntervalConfig intervalConfig : timeline.getIntervals()) {
+      Assertions.assertNotNull(intervalConfig.getInterval());
+      Assertions.assertTrue(intervalConfig.getRuleCount() > 0, "Rule count should be > 0");
+      Assertions.assertNotNull(intervalConfig.getConfig());
+      Assertions.assertNotNull(intervalConfig.getAppliedRules());
+      Assertions.assertEquals(
+          intervalConfig.getRuleCount(),
+          intervalConfig.getAppliedRules().size(),
+          "Applied rules size should match rule count"
+      );
+
+      // Verify config has expected components
+      DataSourceCompactionConfig config = intervalConfig.getConfig();
+      Assertions.assertNotNull(config.getGranularitySpec(), "Should have granularity spec");
+      Assertions.assertNotNull(config.getGranularitySpec().getSegmentGranularity(), "Should have segment granularity");
+
+      // Verify appliedRules contain expected rule types
+      boolean hasTuningRule = intervalConfig.getAppliedRules().stream()
+                                            .anyMatch(r -> r instanceof ReindexingTuningConfigRule);
+      boolean hasIORule = intervalConfig.getAppliedRules().stream()
+                                        .anyMatch(r -> r instanceof ReindexingIOConfigRule);
+      boolean hasDataSchemaRule = intervalConfig.getAppliedRules().stream()
+                                                .anyMatch(r -> r instanceof ReindexingDataSchemaRule);
+      boolean hasDeletionRule = intervalConfig.getAppliedRules().stream()
+                                              .anyMatch(r -> r instanceof ReindexingDeletionRule);
+      boolean hasSegmentGranRule = intervalConfig.getAppliedRules().stream()
+                                                 .anyMatch(r -> r instanceof ReindexingSegmentGranularityRule);

Review Comment:
   ## Unread local variable
   
   Variable 'boolean hasSegmentGranRule' is never read.
   
   [Show more details](https://github.com/apache/druid/security/code-scanning/10832)



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on PR #19051:
URL: https://github.com/apache/druid/pull/19051#issuecomment-3957341904

   Was trying out the embedded test in this PR to check out the timeline.
   
   @capistrant , in the snapshot below, what does the "4 rules applied" mean?
   The widget below it shows only 2 items - a segment granularity and a deletion rule.
   
   Maybe we should include an info popup for each of the chips.
   Also, the chip says `"1" deletion rule". When can there be more than 1 for a single interval?
   
   <img width="807" height="492" alt="Screenshot 2026-02-25 at 12 50 41 PM" src="https://github.com/user-attachments/assets/8df48aa6-b54b-470a-a855-e0330c492bbb" />
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "FrankChen021 (via GitHub)" <gi...@apache.org>.
FrankChen021 commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3227002963


##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CascadingReindexingTemplate.java:
##########
@@ -312,6 +338,121 @@ private static boolean intervalEndsAfter(Interval interval, DateTime boundary)
     return interval.getEnd().isAfter(boundary);
   }
 
+  /**
+   * Generates a timeline view showing the search intervals and their associated reindexing
+   * configurations. This is useful for operators to understand how rules are applied across
+   * different time periods and to preview the effects of rule changes before they are applied.
+   *
+   * @param referenceTime the reference time to use for computing rule periods (typically DateTime.now())
+   * @return a view of the reindexing timeline with intervals and their configs
+   */
+  public ReindexingTimelineView getReindexingTimelineView(DateTime referenceTime)
+  {
+    if (!ruleProvider.isReady()) {
+      LOG.info(
+          "Rule provider [%s] is not ready, returning empty timeline for dataSource[%s]",
+          ruleProvider.getType(),
+          dataSource
+      );
+      return new ReindexingTimelineView(dataSource, referenceTime, null, Collections.emptyList(), null);
+    }
+
+    List<IntervalPartitioningInfo> searchIntervals;
+    try {
+      searchIntervals = generateAlignedSearchIntervals(referenceTime);
+    }
+    catch (SegmentGranularityTimelineValidationException e) {
+      return createValidationErrorView(
+          e,
+          referenceTime,
+          "INVALID_GRANULARITY_TIMELINE",
+          e.getOlderInterval().toString(),
+          e.getOlderGranularity().toString(),
+          e.getNewerInterval().toString(),
+          e.getNewerGranularity().toString()
+      );
+    }
+    catch (IAE e) {
+      return createValidationErrorView(
+          e,
+          referenceTime,
+          "VALIDATION_ERROR",
+          null,
+          null,
+          null,
+          null
+      );
+    }
+
+    if (searchIntervals.isEmpty()) {
+      LOG.warn("No search intervals generated for dataSource[%s]", dataSource);
+      return new ReindexingTimelineView(dataSource, referenceTime, null, Collections.emptyList(), null);
+    }
+
+    // Calculate effective end time based on skip offset
+    DateTime effectiveEndTime = referenceTime;
+    ReindexingTimelineView.SkipOffsetInfo skipOffsetInfo = null;
+
+    if (skipOffsetFromNow != null) {
+      effectiveEndTime = referenceTime.minus(skipOffsetFromNow);
+      skipOffsetInfo = new ReindexingTimelineView.SkipOffsetInfo(
+          "skipOffsetFromNow",
+          skipOffsetFromNow,
+          true,
+          effectiveEndTime,
+          null
+      );
+    } else if (skipOffsetFromLatest != null) {
+      // skipOffsetFromLatest requires actual timeline data, so we can't apply it in preview mode
+      skipOffsetInfo = new ReindexingTimelineView.SkipOffsetInfo(
+          "skipOffsetFromLatest",
+          skipOffsetFromLatest,
+          false,
+          null,
+          "Requires actual segment timeline data"
+      );
+    }
+
+    // Build configs for each interval
+    List<ReindexingTimelineView.IntervalConfig> intervalConfigs = new ArrayList<>();
+    for (IntervalPartitioningInfo intervalInfo : searchIntervals) {
+      Interval searchInterval = intervalInfo.getInterval();
+
+      // Check if interval extends past skip offset
+      if (intervalEndsAfter(searchInterval, effectiveEndTime)) {

Review Comment:
   [P2] Timeline marks partially compacted intervals as skipped
   
   createCompactionJobs now truncates an interval that crosses the skip-offset boundary and still creates jobs for the older aligned subrange, but getReindexingTimelineView still returns ruleCount 0/config null for any interval whose end is after effectiveEndTime. For skipOffsetFromNow, and for the console's skipOffsetFromLatest preview after querying maxTime, the UI will show an interval as fully skipped even though the supervisor will compact part of it. Please mirror the truncation/splitting behavior in the timeline view so the preview matches actual job generation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "vogievetsky (via GitHub)" <gi...@apache.org>.
vogievetsky commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3244928937


##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);
+      const result = resp.data;
+      if (result && result.length > 0 && result[0].result) {
+        const maxTime = result[0].result.maxTime;
+        setQueriedMaxTime(maxTime);
+      } else {
+        AppToaster.show({
+          message: 'No data found in datasource',
+          intent: Intent.WARNING,
+        });
+      }
+    } catch (e) {
+      AppToaster.show({
+        message: `Failed to query max time: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+    } finally {
+      setQueryingMaxTime(false);
+    }
+  };
+
+  // Calculate effective end time if we have queried max time and skipOffsetFromLatest
+  let effectiveEndTime: Date | undefined;
+  if (queriedMaxTime && skipOffset && !skipOffset.isApplied) {
+    const period = skipOffset.period;
+    try {
+      const duration = new Duration(period);
+      effectiveEndTime = duration.shift(new Date(queriedMaxTime), Timezone.UTC, -1);
+    } catch (e) {
+      console.error('Failed to parse skip offset period:', period, e);
+      AppToaster.show({
+        message: `Invalid skip offset period format: ${period}`,
+        intent: Intent.WARNING,
+      });
+    }
+  }
+
+  // Display validation error if present
+  if (validationError) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Invalid Supervisor Configuration">
+          <p>
+            <strong>
+              The segment granularity rule definitions have created an illegal segment granularity
+              timeline.
+            </strong>
+          </p>
+          {validationError.errorType === 'INVALID_GRANULARITY_TIMELINE' &&
+            validationError.olderInterval && (
+              <>
+                <p>
+                  Segment granularity must stay the same or become <strong>coarser</strong> as data
+                  ages from present to past. Your configuration violates this constraint:
+                </p>
+                <ul>
+                  <li>
+                    <strong>Older interval</strong> (further in the past):{' '}
+                    <code>{formatInterval(validationError.olderInterval)}</code> has{' '}
+                    <strong>finer</strong> granularity:{' '}
+                    <Tag intent={Intent.PRIMARY}>{validationError.olderGranularity}</Tag>
+                  </li>
+                  <li>
+                    <strong>Newer interval</strong> (more recent):{' '}
+                    <code>{formatInterval(validationError.newerInterval!)}</code> has{' '}
+                    <strong>coarser</strong> granularity:{' '}
+                    <Tag intent={Intent.WARNING}>{validationError.newerGranularity}</Tag>
+                  </li>
+                </ul>
+                <p>
+                  <strong>To fix this:</strong> Adjust your segment granularity rules so that as
+                  time moves from present to past, the granularity either stays the same or gets
+                  coarser (e.g., HOUR → DAY → MONTH → YEAR).
+                </p>
+              </>
+            )}
+          {validationError.errorType !== 'INVALID_GRANULARITY_TIMELINE' && (
+            <p>{validationError.message}</p>
+          )}
+        </Callout>
+      </div>
+    );
+  }
+
+  if (intervals.length === 0) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.WARNING}>
+          No reindexing intervals found. This may indicate that the rule provider is not ready or no
+          rules are configured.
+        </Callout>
+      </div>
+    );
+  }
+
+  const selectedInterval =
+    selectedIntervalIndex !== undefined ? intervals[selectedIntervalIndex] : undefined;
+
+  return (
+    <div className="reindexing-timeline">
+      <div className="timeline-header">
+        <div className="header-info">
+          <strong>DataSource:</strong> {timelineData.dataSource}
+          <span className="spacer">|</span>
+          <Tooltip
+            content="The reference time used in conjunction with each rule's 'olderThan' attribute to calculate which intervals a rule should apply to."
+            position="bottom"
+          >
+            <strong className="help-hint">Reference Time:</strong>
+          </Tooltip>{' '}
+          {formatDateTimeUTC(referenceTime)}
+        </div>
+        {skipOffset && (
+          <div className="skip-offset-info">
+            {skipOffset.isApplied && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                Skip Offset: {skipOffset.type} ({skipOffset.period})
+              </Tag>
+            )}
+            {!skipOffset.isApplied && !queriedMaxTime && (
+              <>
+                <Tooltip
+                  content={
+                    `This supervisor is configured to skip compaction of any search interval that is covered by ` +
+                    `or overlaps the threshold of the latest timestamp in the data minus ${skipOffset.period}. ` +
+                    `However, the underlying segment data is not available in this preview, so the timeline does not ` +
+                    `reflect which intervals will be skipped during actual compaction.`
+                  }
+                  position="bottom"
+                >
+                  <Tag minimal intent={Intent.WARNING} icon={IconNames.WARNING_SIGN}>
+                    {skipOffset.type} ({skipOffset.period}): Not reflected in this preview
+                  </Tag>
+                </Tooltip>
+                <Button
+                  text="Query latest timestamp"
+                  icon={IconNames.REFRESH}
+                  small
+                  onClick={() => void handleQueryMaxTime()}
+                  loading={queryingMaxTime}
+                  className="query-button"
+                />
+              </>
+            )}
+            {!skipOffset.isApplied && queriedMaxTime && effectiveEndTime && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                {skipOffset.type} ({skipOffset.period}): Applied (latest:{' '}
+                {formatDateTimeUTC(queriedMaxTime)})
+              </Tag>
+            )}
+          </div>
+        )}
+      </div>
+
+      <Card className="timeline-bar-container">
+        <div className="timeline-bar" role="toolbar" aria-label="Reindexing timeline intervals">
+          {intervals.map((interval, idx) => {
+            const [start, end] = interval.interval.split('/');
+            const isSelected = selectedIntervalIndex === idx;
+
+            // Check if interval is skipped due to skip offset (either from API or from queried max time)
+            let isSkipped = interval.ruleCount === 0;
+            if (!isSkipped && effectiveEndTime) {
+              const intervalEnd = new Date(end);
+              isSkipped = intervalEnd > effectiveEndTime;
+            }
+
+            return (
+              <div
+                key={interval.interval}
+                className={`timeline-segment ${isSelected ? 'selected' : ''} ${
+                  isSkipped ? 'skipped' : ''
+                }`}
+                style={{
+                  backgroundColor: isSkipped ? SKIPPED_INTERVAL_COLOR : getIntervalColor(idx),
+                  flex: 1,
+                }}
+                role={isSkipped ? undefined : 'button'}
+                tabIndex={isSkipped ? undefined : 0}
+                aria-label={
+                  isSkipped
+                    ? `Skipped interval ${interval.interval}`
+                    : `Interval ${interval.interval} with ${interval.ruleCount} rule${
+                        interval.ruleCount !== 1 ? 's' : ''
+                      }`
+                }
+                aria-selected={isSelected}
+                onClick={() => !isSkipped && setSelectedIntervalIndex(idx)}
+                onKeyDown={e => {
+                  if (!isSkipped && (e.key === 'Enter' || e.key === ' ')) {
+                    e.preventDefault();
+                    setSelectedIntervalIndex(idx);
+                  }
+                }}
+                title={
+                  isSkipped
+                    ? `${interval.interval}\nSkipped (beyond skip offset)`
+                    : `${interval.interval}\n${interval.ruleCount} rule(s) applied`
+                }
+              >
+                <div className="segment-label">
+                  <div className="segment-date">{formatDateShort(start)}</div>
+                  <div className="segment-date">{formatDateShort(end)}</div>
+                  <div className="segment-rules">
+                    <Tag minimal intent={isSkipped ? Intent.DANGER : undefined}>
+                      {isSkipped
+                        ? 'skipped'
+                        : `${interval.ruleCount} rule${interval.ruleCount !== 1 ? 's' : ''}`}
+                    </Tag>
+                  </div>
+                </div>
+              </div>
+            );
+          })}
+        </div>
+        <div className="timeline-hint">Click on an interval to view its configuration details</div>
+      </Card>
+
+      {selectedInterval && selectedInterval.ruleCount > 0 && (
+        <IntervalDetailPanel
+          interval={selectedInterval}
+          onClose={() => setSelectedIntervalIndex(undefined)}
+        />
+      )}
+    </div>
+  );
+});
+
+function formatDateShort(isoDate: string): string {
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  const d = new Date(isoDate);
+  return `${UTC_MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
+}
+
+const UTC_MONTH_NAMES = [
+  'Jan',
+  'Feb',
+  'Mar',
+  'Apr',
+  'May',
+  'Jun',
+  'Jul',
+  'Aug',
+  'Sep',
+  'Oct',
+  'Nov',
+  'Dec',
+];
+
+function formatDateTimeUTC(isoDate: string): string {
+  // Handle start of time / very old dates
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  // Format using UTC methods to avoid local timezone shifting.
+  // date-fns format() uses the browser's local timezone, so we extract UTC
+  // components manually to ensure the displayed time is actually UTC.
+  const d = new Date(isoDate);
+  const month = UTC_MONTH_NAMES[d.getUTCMonth()];
+  const day = d.getUTCDate();
+  const year = d.getUTCFullYear();
+  const hours = d.getUTCHours();
+  const minutes = String(d.getUTCMinutes()).padStart(2, '0');
+  const ampm = hours >= 12 ? 'PM' : 'AM';
+  const displayHours = hours % 12 || 12;
+  return `${month} ${day}, ${year} ${displayHours}:${minutes} ${ampm} UTC`;
+}
+
+function formatInterval(interval: string): string {
+  const [start, end] = interval.split('/');
+  const formattedStart = start.startsWith('-') ? '-INF' : start;
+  const formattedEnd = end ? end : 'now';
+  return `${formattedStart}/${formattedEnd}`;
+}
+
+function handleCopyToClipboard(data: CompactionConfig | ReindexingRule[], label: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  copy(jsonValue, { format: 'text/plain' });
+  AppToaster.show({
+    message: `${label} copied to clipboard`,
+    intent: Intent.SUCCESS,
+  });
+}
+
+function handleDownloadJson(data: CompactionConfig | ReindexingRule[], filename: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  downloadFile(jsonValue, 'json', filename);
+}
+
+function getPartitionType(tuningConfig: Record<string, unknown> | undefined): string | undefined {
+  if (!tuningConfig) return undefined;
+  const partitionsSpec = tuningConfig.partitionsSpec;
+  if (partitionsSpec && typeof partitionsSpec === 'object' && partitionsSpec !== null) {
+    return (partitionsSpec as Record<string, unknown>).type as string | undefined;
+  }
+  return undefined;
+}
+
+interface IntervalDetailPanelProps {
+  interval: IntervalConfig;
+  onClose: () => void;
+}
+
+function IntervalDetailPanel({ interval, onClose }: IntervalDetailPanelProps) {
+  const [showFullConfig, setShowFullConfig] = useState(false);
+  const [showRawRules, setShowRawRules] = useState(false);
+  const { config } = interval;
+
+  const deletionRuleCount = interval.appliedRules.filter(r => r.type === 'deletion').length;
+  const metricsCount = config.metricsSpec?.length || 0;
+  const dimensionsCount = config.dimensionsSpec?.dimensions?.length || 0;
+  const projectionsCount = config.projections?.length || 0;
+
+  return (
+    <>
+      <Card className="interval-detail-panel">
+        <div className="detail-header">
+          <div>
+            <h3>Interval: {formatInterval(interval.interval)}</h3>
+          </div>
+          <Button
+            icon={IconNames.CROSS}
+            minimal
+            onClick={onClose}
+            aria-label="Close interval details"
+          />
+        </div>
+
+        <div className="detail-content">
+          <Tooltip
+            content="A high-level summary of the merged rule configuration for this interval — use View Full Configuration for complete details."
+            position="bottom"
+          >
+            <div className="config-summary-label">Effective Configuration</div>
+          </Tooltip>
+          <div className="config-badges">
+            {config.granularitySpec?.segmentGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.CALENDAR}>
+                Segment: {config.granularitySpec.segmentGranularity}
+              </Tag>
+            )}
+            {config.granularitySpec?.queryGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.TIME}>
+                Query: {config.granularitySpec.queryGranularity}
+              </Tag>
+            )}
+            {getPartitionType(config.tuningConfig) && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.SPLIT_COLUMNS}>
+                Partitioning: {getPartitionType(config.tuningConfig)}
+              </Tag>
+            )}
+            {metricsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CALCULATOR}>
+                {metricsCount} metric{metricsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {dimensionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TAG}>
+                {dimensionsCount} dimension{dimensionsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {projectionsCount > 0 && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.CUBE}>
+                {projectionsCount} projection{projectionsCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+            {deletionRuleCount > 0 && (
+              <Tag minimal intent={Intent.WARNING} icon={IconNames.TRASH}>
+                {deletionRuleCount} deletion clause{deletionRuleCount !== 1 ? 's' : ''}
+              </Tag>
+            )}
+          </div>
+
+          <div className="full-config-section">
+            <Button
+              icon={IconNames.CODE}
+              text="View Full Configuration"
+              intent={Intent.PRIMARY}
+              onClick={() => setShowFullConfig(true)}
+            />
+            <Button
+              icon={IconNames.PROPERTIES}
+              text={`View ${interval.ruleCount} Raw Rule${interval.ruleCount !== 1 ? 's' : ''}`}
+              intent={Intent.PRIMARY}
+              onClick={() => setShowRawRules(true)}
+            />
+          </div>
+        </div>
+      </Card>
+
+      <Dialog
+        isOpen={showFullConfig}
+        onClose={() => setShowFullConfig(false)}
+        title={
+          <Tooltip content={interval.interval} position="bottom">
+            <span>{formatInterval(interval.interval)}</span>
+          </Tooltip>
+        }
+        className="reindexing-config-dialog"
+        canOutsideClickClose
+      >
+        <div className="bp5-dialog-body">
+          <ConfigJsonViewer config={config} />
+        </div>
+        <div className="bp5-dialog-footer">
+          <div className="bp5-dialog-footer-actions">
+            <Button
+              text="Copy"
+              icon={IconNames.DUPLICATE}
+              intent={Intent.PRIMARY}
+              onClick={() => handleCopyToClipboard(config, 'Configuration')}
+            />
+            <Button
+              text="Download"
+              icon={IconNames.DOWNLOAD}
+              intent={Intent.PRIMARY}
+              onClick={() =>
+                handleDownloadJson(
+                  config,
+                  `reindexing-config-${interval.interval.replace(/\//g, '-')}.json`,
+                )
+              }
+            />
+          </div>
+        </div>
+      </Dialog>
+
+      <Dialog
+        isOpen={showRawRules}
+        onClose={() => setShowRawRules(false)}
+        title={
+          <Tooltip
+            content={`${interval.appliedRules.length} rules for ${interval.interval}`}
+            position="bottom"
+          >
+            <span>Rules for {formatInterval(interval.interval)}</span>
+          </Tooltip>
+        }
+        className="reindexing-config-dialog"
+        canOutsideClickClose
+      >
+        <div className="bp5-dialog-body">
+          <ConfigJsonViewer config={interval.appliedRules} isRulesList />
+        </div>
+        <div className="bp5-dialog-footer">
+          <div className="bp5-dialog-footer-actions">
+            <Button
+              text="Copy"
+              icon={IconNames.DUPLICATE}
+              intent={Intent.PRIMARY}
+              onClick={() => handleCopyToClipboard(interval.appliedRules, 'Rules')}
+            />
+            <Button
+              text="Download"
+              icon={IconNames.DOWNLOAD}
+              intent={Intent.PRIMARY}
+              onClick={() =>
+                handleDownloadJson(
+                  interval.appliedRules,
+                  `reindexing-rules-${interval.interval.replace(/\//g, '-')}.json`,
+                )
+              }
+            />
+          </div>
+        </div>
+      </Dialog>
+    </>
+  );
+}
+
+interface ConfigJsonViewerProps {
+  config: CompactionConfig | ReindexingRule[];
+  isRulesList?: boolean;
+}
+
+function ConfigJsonViewer({ config, isRulesList }: ConfigJsonViewerProps) {
+  let jsonValue: string;
+
+  if (isRulesList && Array.isArray(config)) {
+    // Group rules by type for better readability
+    const rulesByType: Record<string, ReindexingRule[]> = {};
+    config.forEach((rule: ReindexingRule) => {
+      const type = getRuleTypeName(rule);

Review Comment:
   I don't like that we are creating fake JSONs with custom names in them. There is a general rule of thumb in the console (that I am just realizing) that all JSON shown to the user should correspond to something in the Druid API. Here I suggest we redesign this dialog, maybe adding several JSON fields.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Cascading Reindexing Supervisor UI component fore viewing timeline of rule applications (druid)

Posted by "kfaraz (via GitHub)" <gi...@apache.org>.
kfaraz commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r2850758460


##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CascadingReindexingTemplate.java:
##########
@@ -217,6 +243,118 @@ private static boolean intervalEndsAfter(Interval interval, DateTime boundary)
     return interval.getEnd().isAfter(boundary);
   }
 
+  /**
+   * Generates a timeline view showing the search intervals and their associated reindexing
+   * configurations. This is useful for operators to understand how rules are applied across
+   * different time periods and to preview the effects of rule changes before they are applied.
+   *
+   * @param referenceTime the reference time to use for computing rule periods (typically DateTime.now())
+   * @return a view of the reindexing timeline with intervals and their configs
+   */
+  public ReindexingTimelineView getReindexingTimelineView(DateTime referenceTime)

Review Comment:
   I feel like this method should not live here as it kind of pollutes the template definition.
   
   Either have the timeline be built using a static method like `ReindexingTimelineView.fromTemplate(template, referenceTime)` or have a separate builder class altogether.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "capistrant (via GitHub)" <gi...@apache.org>.
capistrant commented on PR #19051:
URL: https://github.com/apache/druid/pull/19051#issuecomment-4043285890

   > @capistrant , is this PR ready for another round of review or should we hold off until the refactor PR #19106  is reviewed and merged?
   
   Can probably hold off for now until the rule refactor is done 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "capistrant (via GitHub)" <gi...@apache.org>.
capistrant commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r2853932220


##########
indexing-service/src/main/java/org/apache/druid/indexing/compact/CascadingReindexingTemplate.java:
##########
@@ -217,6 +243,118 @@ private static boolean intervalEndsAfter(Interval interval, DateTime boundary)
     return interval.getEnd().isAfter(boundary);
   }
 
+  /**
+   * Generates a timeline view showing the search intervals and their associated reindexing
+   * configurations. This is useful for operators to understand how rules are applied across
+   * different time periods and to preview the effects of rule changes before they are applied.
+   *
+   * @param referenceTime the reference time to use for computing rule periods (typically DateTime.now())
+   * @return a view of the reindexing timeline with intervals and their configs
+   */
+  public ReindexingTimelineView getReindexingTimelineView(DateTime referenceTime)

Review Comment:
   hmm. I wonder about how we'd manage to re-use a lot of the underlying private implementation details that are quite convoluted (unfortunately). Like creating the base timeline from segment gran rules and what not is all shared between the timeline creation and the task creation. I agree that it feels a little weird here, but I didn't know how else to approach it without either duping a lot of internal logic or exposing it to both somehow. will keep thinking though



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "capistrant (via GitHub)" <gi...@apache.org>.
capistrant closed pull request #19051: feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor
URL: https://github.com/apache/druid/pull/19051


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org


Re: [PR] feat: Add Supervisor UI component to view timeline of rules applied by a cascading reindexing supervisor (druid)

Posted by "vogievetsky (via GitHub)" <gi...@apache.org>.
vogievetsky commented on code in PR #19051:
URL: https://github.com/apache/druid/pull/19051#discussion_r3244854180


##########
web-console/src/components/reindexing-timeline/reindexing-timeline.tsx:
##########
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { Button, Callout, Card, Dialog, Intent, Tag, Tooltip } from '@blueprintjs/core';
+import { IconNames } from '@blueprintjs/icons';
+import { Duration, Timezone } from 'chronoshift';
+import copy from 'copy-to-clipboard';
+import * as JSONBig from 'json-bigint-native';
+import React, { useState } from 'react';
+import AceEditor from 'react-ace';
+
+import { useQueryManager } from '../../hooks';
+import { Api, AppToaster } from '../../singletons';
+import { downloadFile } from '../../utils';
+import { Loader } from '../loader/loader';
+
+import './reindexing-timeline.scss';
+
+const TIMELINE_INTERVAL_COLORS = [
+  '#5C7080', // gray
+  '#738694', // light gray
+  '#8A9BA8', // lighter gray
+  '#394B59', // dark gray
+  '#4A5568', // medium dark gray
+  '#6B7E91', // medium gray
+  '#2F343C', // darker gray
+];
+
+const SKIPPED_INTERVAL_COLOR = 'rgba(219, 55, 55, 0.15)';
+const JSON_VIEWER_HEIGHT = '500px';
+
+function getIntervalColor(index: number): string {
+  return TIMELINE_INTERVAL_COLORS[index % TIMELINE_INTERVAL_COLORS.length];
+}
+
+interface ReindexingTimelineProps {
+  supervisorId: string;
+}
+
+interface GranularitySpec {
+  segmentGranularity?: string;
+  queryGranularity?: string;
+  rollup?: boolean;
+}
+
+interface CompactionConfig {
+  granularitySpec?: GranularitySpec;
+  metricsSpec?: Record<string, unknown>[];
+  dimensionsSpec?: {
+    dimensions?: Record<string, unknown>[];
+  };
+  projections?: Record<string, unknown>[];
+  transformSpec?: Record<string, unknown>;
+  tuningConfig?: Record<string, unknown>;
+}
+
+interface ReindexingRule {
+  type: string;
+  id?: string;
+  olderThan?: string;
+}
+
+interface IntervalConfig {
+  interval: string;
+  ruleCount: number;
+  config: CompactionConfig;
+  appliedRules: ReindexingRule[];
+}
+
+interface SkipOffsetInfo {
+  type: string;
+  period: string;
+  isApplied: boolean;
+  effectiveEndTime?: string;
+  reason?: string;
+}
+
+interface ValidationError {
+  errorType: string;
+  message: string;
+  olderInterval?: string;
+  olderGranularity?: string;
+  newerInterval?: string;
+  newerGranularity?: string;
+}
+
+interface ReindexingTimelineData {
+  dataSource: string;
+  referenceTime: string;
+  skipOffset?: SkipOffsetInfo;
+  intervals: IntervalConfig[];
+  validationError?: ValidationError;
+}
+
+export const ReindexingTimeline = React.memo(function ReindexingTimeline(
+  props: ReindexingTimelineProps,
+) {
+  const { supervisorId } = props;
+  const [selectedIntervalIndex, setSelectedIntervalIndex] = useState<number | undefined>();
+  const [queriedMaxTime, setQueriedMaxTime] = useState<string | undefined>();
+  const [queryingMaxTime, setQueryingMaxTime] = useState(false);
+
+  const [timelineState] = useQueryManager<string, ReindexingTimelineData>({
+    query: supervisorId,
+    processQuery: async (supervisorId, signal) => {
+      const resp = await Api.instance.get<ReindexingTimelineData>(
+        `/druid/indexer/v1/supervisor/${Api.encodePath(supervisorId)}/reindexingTimeline`,
+        { signal },
+      );
+      return resp.data;
+    },
+  });
+
+  if (timelineState.loading) {
+    return <Loader />;
+  }
+
+  if (timelineState.error) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Error loading reindexing timeline">
+          {timelineState.getErrorMessage()}
+        </Callout>
+      </div>
+    );
+  }
+
+  const timelineData = timelineState.data;
+  if (!timelineData) {
+    return null;
+  }
+
+  const { intervals, skipOffset, referenceTime, validationError } = timelineData;
+
+  const handleQueryMaxTime = async () => {
+    setQueryingMaxTime(true);
+    try {
+      const query = {
+        queryType: 'timeBoundary',
+        dataSource: timelineData.dataSource,
+      };
+      const resp = await Api.instance.post('/druid/v2', query);
+      const result = resp.data;
+      if (result && result.length > 0 && result[0].result) {
+        const maxTime = result[0].result.maxTime;
+        setQueriedMaxTime(maxTime);
+      } else {
+        AppToaster.show({
+          message: 'No data found in datasource',
+          intent: Intent.WARNING,
+        });
+      }
+    } catch (e) {
+      AppToaster.show({
+        message: `Failed to query max time: ${e.message}`,
+        intent: Intent.DANGER,
+      });
+    } finally {
+      setQueryingMaxTime(false);
+    }
+  };
+
+  // Calculate effective end time if we have queried max time and skipOffsetFromLatest
+  let effectiveEndTime: Date | undefined;
+  if (queriedMaxTime && skipOffset && !skipOffset.isApplied) {
+    const period = skipOffset.period;
+    try {
+      const duration = new Duration(period);
+      effectiveEndTime = duration.shift(new Date(queriedMaxTime), Timezone.UTC, -1);
+    } catch (e) {
+      console.error('Failed to parse skip offset period:', period, e);
+      AppToaster.show({
+        message: `Invalid skip offset period format: ${period}`,
+        intent: Intent.WARNING,
+      });
+    }
+  }
+
+  // Display validation error if present
+  if (validationError) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.DANGER} title="Invalid Supervisor Configuration">
+          <p>
+            <strong>
+              The segment granularity rule definitions have created an illegal segment granularity
+              timeline.
+            </strong>
+          </p>
+          {validationError.errorType === 'INVALID_GRANULARITY_TIMELINE' &&
+            validationError.olderInterval && (
+              <>
+                <p>
+                  Segment granularity must stay the same or become <strong>coarser</strong> as data
+                  ages from present to past. Your configuration violates this constraint:
+                </p>
+                <ul>
+                  <li>
+                    <strong>Older interval</strong> (further in the past):{' '}
+                    <code>{formatInterval(validationError.olderInterval)}</code> has{' '}
+                    <strong>finer</strong> granularity:{' '}
+                    <Tag intent={Intent.PRIMARY}>{validationError.olderGranularity}</Tag>
+                  </li>
+                  <li>
+                    <strong>Newer interval</strong> (more recent):{' '}
+                    <code>{formatInterval(validationError.newerInterval!)}</code> has{' '}
+                    <strong>coarser</strong> granularity:{' '}
+                    <Tag intent={Intent.WARNING}>{validationError.newerGranularity}</Tag>
+                  </li>
+                </ul>
+                <p>
+                  <strong>To fix this:</strong> Adjust your segment granularity rules so that as
+                  time moves from present to past, the granularity either stays the same or gets
+                  coarser (e.g., HOUR → DAY → MONTH → YEAR).
+                </p>
+              </>
+            )}
+          {validationError.errorType !== 'INVALID_GRANULARITY_TIMELINE' && (
+            <p>{validationError.message}</p>
+          )}
+        </Callout>
+      </div>
+    );
+  }
+
+  if (intervals.length === 0) {
+    return (
+      <div className="reindexing-timeline">
+        <Callout intent={Intent.WARNING}>
+          No reindexing intervals found. This may indicate that the rule provider is not ready or no
+          rules are configured.
+        </Callout>
+      </div>
+    );
+  }
+
+  const selectedInterval =
+    selectedIntervalIndex !== undefined ? intervals[selectedIntervalIndex] : undefined;
+
+  return (
+    <div className="reindexing-timeline">
+      <div className="timeline-header">
+        <div className="header-info">
+          <strong>DataSource:</strong> {timelineData.dataSource}
+          <span className="spacer">|</span>
+          <Tooltip
+            content="The reference time used in conjunction with each rule's 'olderThan' attribute to calculate which intervals a rule should apply to."
+            position="bottom"
+          >
+            <strong className="help-hint">Reference Time:</strong>
+          </Tooltip>{' '}
+          {formatDateTimeUTC(referenceTime)}
+        </div>
+        {skipOffset && (
+          <div className="skip-offset-info">
+            {skipOffset.isApplied && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                Skip Offset: {skipOffset.type} ({skipOffset.period})
+              </Tag>
+            )}
+            {!skipOffset.isApplied && !queriedMaxTime && (
+              <>
+                <Tooltip
+                  content={
+                    `This supervisor is configured to skip compaction of any search interval that is covered by ` +
+                    `or overlaps the threshold of the latest timestamp in the data minus ${skipOffset.period}. ` +
+                    `However, the underlying segment data is not available in this preview, so the timeline does not ` +
+                    `reflect which intervals will be skipped during actual compaction.`
+                  }
+                  position="bottom"
+                >
+                  <Tag minimal intent={Intent.WARNING} icon={IconNames.WARNING_SIGN}>
+                    {skipOffset.type} ({skipOffset.period}): Not reflected in this preview
+                  </Tag>
+                </Tooltip>
+                <Button
+                  text="Query latest timestamp"
+                  icon={IconNames.REFRESH}
+                  small
+                  onClick={() => void handleQueryMaxTime()}
+                  loading={queryingMaxTime}
+                  className="query-button"
+                />
+              </>
+            )}
+            {!skipOffset.isApplied && queriedMaxTime && effectiveEndTime && (
+              <Tag minimal intent={Intent.SUCCESS} icon={IconNames.TICK}>
+                {skipOffset.type} ({skipOffset.period}): Applied (latest:{' '}
+                {formatDateTimeUTC(queriedMaxTime)})
+              </Tag>
+            )}
+          </div>
+        )}
+      </div>
+
+      <Card className="timeline-bar-container">
+        <div className="timeline-bar" role="toolbar" aria-label="Reindexing timeline intervals">
+          {intervals.map((interval, idx) => {
+            const [start, end] = interval.interval.split('/');
+            const isSelected = selectedIntervalIndex === idx;
+
+            // Check if interval is skipped due to skip offset (either from API or from queried max time)
+            let isSkipped = interval.ruleCount === 0;
+            if (!isSkipped && effectiveEndTime) {
+              const intervalEnd = new Date(end);
+              isSkipped = intervalEnd > effectiveEndTime;
+            }
+
+            return (
+              <div
+                key={interval.interval}
+                className={`timeline-segment ${isSelected ? 'selected' : ''} ${
+                  isSkipped ? 'skipped' : ''
+                }`}
+                style={{
+                  backgroundColor: isSkipped ? SKIPPED_INTERVAL_COLOR : getIntervalColor(idx),
+                  flex: 1,
+                }}
+                role={isSkipped ? undefined : 'button'}
+                tabIndex={isSkipped ? undefined : 0}
+                aria-label={
+                  isSkipped
+                    ? `Skipped interval ${interval.interval}`
+                    : `Interval ${interval.interval} with ${interval.ruleCount} rule${
+                        interval.ruleCount !== 1 ? 's' : ''
+                      }`
+                }
+                aria-selected={isSelected}
+                onClick={() => !isSkipped && setSelectedIntervalIndex(idx)}
+                onKeyDown={e => {
+                  if (!isSkipped && (e.key === 'Enter' || e.key === ' ')) {
+                    e.preventDefault();
+                    setSelectedIntervalIndex(idx);
+                  }
+                }}
+                title={
+                  isSkipped
+                    ? `${interval.interval}\nSkipped (beyond skip offset)`
+                    : `${interval.interval}\n${interval.ruleCount} rule(s) applied`
+                }
+              >
+                <div className="segment-label">
+                  <div className="segment-date">{formatDateShort(start)}</div>
+                  <div className="segment-date">{formatDateShort(end)}</div>
+                  <div className="segment-rules">
+                    <Tag minimal intent={isSkipped ? Intent.DANGER : undefined}>
+                      {isSkipped
+                        ? 'skipped'
+                        : `${interval.ruleCount} rule${interval.ruleCount !== 1 ? 's' : ''}`}
+                    </Tag>
+                  </div>
+                </div>
+              </div>
+            );
+          })}
+        </div>
+        <div className="timeline-hint">Click on an interval to view its configuration details</div>
+      </Card>
+
+      {selectedInterval && selectedInterval.ruleCount > 0 && (
+        <IntervalDetailPanel
+          interval={selectedInterval}
+          onClose={() => setSelectedIntervalIndex(undefined)}
+        />
+      )}
+    </div>
+  );
+});
+
+function formatDateShort(isoDate: string): string {
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  const d = new Date(isoDate);
+  return `${UTC_MONTH_NAMES[d.getUTCMonth()]} ${d.getUTCDate()}, ${d.getUTCFullYear()}`;
+}
+
+const UTC_MONTH_NAMES = [
+  'Jan',
+  'Feb',
+  'Mar',
+  'Apr',
+  'May',
+  'Jun',
+  'Jul',
+  'Aug',
+  'Sep',
+  'Oct',
+  'Nov',
+  'Dec',
+];
+
+function formatDateTimeUTC(isoDate: string): string {
+  // Handle start of time / very old dates
+  if (isoDate.startsWith('-')) {
+    return '-INF';
+  }
+
+  // Format using UTC methods to avoid local timezone shifting.
+  // date-fns format() uses the browser's local timezone, so we extract UTC
+  // components manually to ensure the displayed time is actually UTC.
+  const d = new Date(isoDate);
+  const month = UTC_MONTH_NAMES[d.getUTCMonth()];
+  const day = d.getUTCDate();
+  const year = d.getUTCFullYear();
+  const hours = d.getUTCHours();
+  const minutes = String(d.getUTCMinutes()).padStart(2, '0');
+  const ampm = hours >= 12 ? 'PM' : 'AM';
+  const displayHours = hours % 12 || 12;
+  return `${month} ${day}, ${year} ${displayHours}:${minutes} ${ampm} UTC`;
+}
+
+function formatInterval(interval: string): string {
+  const [start, end] = interval.split('/');
+  const formattedStart = start.startsWith('-') ? '-INF' : start;
+  const formattedEnd = end ? end : 'now';
+  return `${formattedStart}/${formattedEnd}`;
+}
+
+function handleCopyToClipboard(data: CompactionConfig | ReindexingRule[], label: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  copy(jsonValue, { format: 'text/plain' });
+  AppToaster.show({
+    message: `${label} copied to clipboard`,
+    intent: Intent.SUCCESS,
+  });
+}
+
+function handleDownloadJson(data: CompactionConfig | ReindexingRule[], filename: string): void {
+  const jsonValue = JSONBig.stringify(data, undefined, 2);
+  downloadFile(jsonValue, 'json', filename);
+}
+
+function getPartitionType(tuningConfig: Record<string, unknown> | undefined): string | undefined {
+  if (!tuningConfig) return undefined;
+  const partitionsSpec = tuningConfig.partitionsSpec;
+  if (partitionsSpec && typeof partitionsSpec === 'object' && partitionsSpec !== null) {
+    return (partitionsSpec as Record<string, unknown>).type as string | undefined;
+  }
+  return undefined;
+}
+
+interface IntervalDetailPanelProps {
+  interval: IntervalConfig;
+  onClose: () => void;
+}
+
+function IntervalDetailPanel({ interval, onClose }: IntervalDetailPanelProps) {
+  const [showFullConfig, setShowFullConfig] = useState(false);
+  const [showRawRules, setShowRawRules] = useState(false);
+  const { config } = interval;
+
+  const deletionRuleCount = interval.appliedRules.filter(r => r.type === 'deletion').length;
+  const metricsCount = config.metricsSpec?.length || 0;
+  const dimensionsCount = config.dimensionsSpec?.dimensions?.length || 0;
+  const projectionsCount = config.projections?.length || 0;
+
+  return (
+    <>
+      <Card className="interval-detail-panel">
+        <div className="detail-header">
+          <div>
+            <h3>Interval: {formatInterval(interval.interval)}</h3>
+          </div>
+          <Button
+            icon={IconNames.CROSS}
+            minimal
+            onClick={onClose}
+            aria-label="Close interval details"
+          />
+        </div>
+
+        <div className="detail-content">
+          <Tooltip
+            content="A high-level summary of the merged rule configuration for this interval — use View Full Configuration for complete details."
+            position="bottom"
+          >
+            <div className="config-summary-label">Effective Configuration</div>
+          </Tooltip>
+          <div className="config-badges">
+            {config.granularitySpec?.segmentGranularity && (
+              <Tag minimal intent={Intent.PRIMARY} icon={IconNames.CALENDAR}>

Review Comment:
   not shy about using `intent={Intent.PRIMARY}`!



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org