Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(workflows): show a batch run's own log on the run it belongs to (#101634)

Daniel Marchuka76b294a5870
diff --git a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.test.ts b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.test.ts
index 77ec381fb773..ce1dcac2ea5e 100644
--- a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.test.ts
+++ b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.test.ts
@@ -1,6 +1,11 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
import { dayjs } from 'lib/dayjs'
import { teamLogic } from 'scenes/teamLogic'
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
import { LogEntryLevel } from '~/types'
import {
@@ -8,6 +13,7 @@ import {
groupLogs,
LogEntry,
LogEntryParams,
+ logsViewerLogic,
toAbsoluteClickhouseTimestamp,
} from './logsViewerLogic'
@@ -201,4 +207,44 @@ describe('logsViewerLogic', () => {
expect(firstPage.replace('OFFSET 0', 'OFFSET 10')).toEqual(secondPage)
})
})
+
+ describe('disableUrlSync', () => {
+ beforeEach(() => {
+ useMocks({
+ post: {
+ '/api/environments/:team_id/query/': () => [200, { results: [] }],
+ },
+ })
+ initKeaTests()
+ })
+
+ it('neither writes its filters to the URL nor reads them back from it', async () => {
+ // Several viewers can mount on one scene with unprefixed params. A run-scoped viewer that
+ // took `search` from the URL would filter its own entries away on someone else's search.
+ const logic = logsViewerLogic({ sourceType: 'hog_flow', sourceId: 'flow-1', disableUrlSync: true })
+ logic.mount()
+ const before = { ...router.values.searchParams }
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ search: 'mine' })
+ }).toDispatchActions(['setFilters'])
+ expect(router.values.searchParams).toEqual(before)
+
+ router.actions.push(router.values.location.pathname, { search: 'theirs' })
+ expect(logic.values.filters.search).toBe('mine')
+ logic.unmount()
+ })
+
+ it('a viewer without the flag still follows the URL', async () => {
+ const logic = logsViewerLogic({ sourceType: 'hog_flow', sourceId: 'flow-1' })
+ logic.mount()
+ await expectLogic(logic, () => {
+ logic.actions.setFilters({ search: 'mine' })
+ }).toDispatchActions(['setFilters'])
+ expect(router.values.searchParams.search).toBe('mine')
+
+ router.actions.push(router.values.location.pathname, { search: 'theirs' })
+ expect(logic.values.filters.search).toBe('theirs')
+ logic.unmount()
+ })
+ })
})
diff --git a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
index 59b1fa624abe..1e3a17550890 100644
--- a/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
+++ b/frontend/src/scenes/hog-functions/logs/logsViewerLogic.tsx
@@ -37,6 +37,12 @@ export type LogsViewerLogicProps = {
groupByInstanceId?: boolean
searchGroups?: string[]
defaultFilters?: Partial<LogEntryParams>
+ /**
+ * Opt out of the shared `levels`, `search`, `date_from` and `date_to` URL params. Several viewers
+ * can mount on one scene and the params carry no prefix, so one viewer's filter would override
+ * another's `defaultFilters`.
+ */
+ disableUrlSync?: boolean
}
export type LogsViewerFilters = {
@@ -799,7 +805,10 @@ export const logsViewerLogic = kea<logsViewerLogicType>([
beforeUnmount(() => {
// Disposables handle cleanup automatically
}),
- actionToUrl(({ values }) => {
+ actionToUrl(({ values, props }) => {
+ if (props.disableUrlSync) {
+ return {}
+ }
const syncProperties = (
properties: Record<string, any>
): [string, Record<string, any>, Record<string, any>] => {
@@ -817,8 +826,11 @@ export const logsViewerLogic = kea<logsViewerLogicType>([
setIsGrouped: () => syncProperties({ grouped: values.isGrouped }),
}
}),
- urlToAction(({ actions, values }) => {
+ urlToAction(({ actions, values, props }) => {
const reactToTabChange = (_: any, search: Record<string, any>): void => {
+ if (props.disableUrlSync) {
+ return
+ }
Object.keys(search).forEach((key) => {
if (key in values.filters && search[key] !== values.filters[key as keyof LogsViewerFilters]) {
actions.setFilters({ [key]: search[key] })
diff --git a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
index 6bdfa13e7952..c284aabd6862 100644
--- a/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
+++ b/nodejs/src/cdp/consumers/cdp-cyclotron-worker-batch-resolve.consumer.ts
@@ -474,7 +474,7 @@ export class CdpCyclotronWorkerBatchResolve extends CdpConsumerBase<PluginsServe
private emitTruncationLog(state: BatchResolverState): void {
counterBatchHogFlowAudienceTruncated.labels({ hog_flow_id: state.hogFlowId }).inc()
- const message = `Audience reached the max cap of ${state.maxAudienceSize}, ${state.totalEnqueued} persons enqueued; the remainder did not receive this workflow.`
+ const message = `This batch reached its audience limit of ${state.maxAudienceSize}. The rest of the audience did not receive this workflow.`
logger.warn('⚠️', `${this.name} - audience truncated`, {
batchJobId: state.batchJobId,
totalEnqueued: state.totalEnqueued,
diff --git a/products/workflows/frontend/Workflows/BatchRunLog.tsx b/products/workflows/frontend/Workflows/BatchRunLog.tsx
new file mode 100644
index 000000000000..cc322113b820
--- /dev/null
+++ b/products/workflows/frontend/Workflows/BatchRunLog.tsx
@@ -0,0 +1,56 @@
+import { useValues } from 'kea'
+
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
+import { tagTypeForLevel } from 'scenes/hog-functions/logs/LogsViewer'
+import { logsViewerLogic } from 'scenes/hog-functions/logs/logsViewerLogic'
+
+/**
+ * What a batch run recorded about itself: an audience cut at the batch limit, a cancel, a resolver
+ * failure. These entries carry the batch job id as their instance, so they never appear in a
+ * person's row below. There are at most a few of them, so this is a list, not a log viewer, and
+ * it renders nothing at all for the common run that recorded nothing.
+ */
+export function BatchRunLog({ jobId, createdAt }: { jobId: string; createdAt: string }): JSX.Element | null {
+ // The viewer looks back seven days unless told otherwise, while these entries are kept for
+ // ninety. Without an anchor on the run's own date, every run older than a week reads as
+ // having recorded nothing.
+ const dateFrom = dayjs(createdAt).subtract(1, 'day').format('YYYY-MM-DD')
+
+ const { unGroupedLogs } = useValues(
+ logsViewerLogic({
+ logicKey: `batch-run-log-${jobId}`,
+ sourceType: 'hog_flow',
+ sourceId: jobId,
+ groupByInstanceId: false,
+ disableUrlSync: true,
+ defaultFilters: { instanceId: jobId, dateFrom },
+ })
+ )
+
+ if (unGroupedLogs.length === 0) {
+ return null
+ }
+
+ // The fetch is newest-first to match the viewer; the run reads in execution order.
+ const entries = [...unGroupedLogs].reverse()
+
+ return (
+ <div className="flex flex-col gap-2">
+ <span className="text-muted">Run log</span>
+ <div className="border rounded bg-surface-primary divide-y" data-attr="batch-run-log">
+ {entries.map((entry, index) => (
+ <div key={`${entry.rawTimestamp}-${index}`} className="flex items-start gap-3 px-3 py-2">
+ <span className="text-secondary whitespace-nowrap">
+ <TZLabel time={entry.timestamp} />
+ </span>
+ <LemonTag type={tagTypeForLevel(entry.level)}>{entry.level.toUpperCase()}</LemonTag>
+ <code className="whitespace-pre-wrap">{entry.message}</code>
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx b/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
index 98d5192c1bd6..521311b0a38c 100644
--- a/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
+++ b/products/workflows/frontend/Workflows/WorkflowBatchInvocations.tsx
@@ -20,6 +20,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { HogInvocations } from 'scenes/hog-functions/invocations/HogInvocations'
+import { BatchRunLog } from './BatchRunLog'
import { batchWorkflowJobsLogic } from './batchWorkflowJobsLogic'
import { OccurrencesList } from './hogflows/steps/components/OccurrencesList'
import {
@@ -108,6 +109,11 @@ function BatchRunHeader({ job, hogFlowId }: { job: HogFlowBatchJob; hogFlowId: s
)
}
+/**
+ * The table below lists one row per person the run reached. Anything the run itself recorded,
+ * such as an audience cut short at the batch limit, belongs to the run and to no person, so it
+ * has no row there. The run log above the table carries those entries.
+ */
function BatchRunInvocations({ job, hogFlowId }: { job: HogFlowBatchJob; hogFlowId: string }): JSX.Element {
const { workflow } = useValues(workflowLogic)
@@ -123,6 +129,7 @@ function BatchRunInvocations({ job, hogFlowId }: { job: HogFlowBatchJob; hogFlow
filters={Array.isArray(job.filters?.properties) ? job.filters.properties : []}
/>
</div>
+ <BatchRunLog jobId={job.id} createdAt={job.created_at} />
<div className="flex flex-col gap-2">
<HogInvocations
id={hogFlowId}