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.

fix(notebooks): align markdown converters (#67067)

Marius Andrad8cd3639a42b
diff --git a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
index 0d4fe53fa51b..d9a9dbccaa6f 100644
--- a/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
+++ b/ee/hogai/chat_agent/query_planner/test/test_toolkit.py
@@ -129,7 +129,10 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):
)
PropertyDefinition.objects.create(
- team=self.team, type=PropertyDefinition.Type.PERSON, name="email", property_type=PropertyType.String
+ team=self.team,
+ type=PropertyDefinition.Type.PERSON,
+ name="taxonomy_email",
+ property_type=PropertyType.String,
)
PropertyDefinition.objects.create(
team=self.team, type=PropertyDefinition.Type.PERSON, name="id", property_type=PropertyType.Numeric
@@ -140,19 +143,19 @@ class TestTaxonomyAgentToolkit(ClickhouseTestMixin, APIBaseTest):
with freeze_time(f"2024-01-01T00:{i}:00Z"):
_create_person(
distinct_ids=[id],
- properties={"email": f"{id}@example.com", "id": i},
+ properties={"taxonomy_email": f"{id}@example.com", "id": i},
team=self.team,
)
with freeze_time(f"2024-01-02T00:00:00Z"):
_create_person(
distinct_ids=["person25"],
- properties={"email": "[email protected]", "id": 25},
+ properties={"taxonomy_email": "[email protected]", "id": 25},
team=self.team,
)
self.assertIn(
- toolkit.retrieve_entity_property_values("person", "email"),
+ toolkit.retrieve_entity_property_values("person", "taxonomy_email"),
)
self.assertIn(
"1 more distinct value",
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index 840a04674c7e..4e6d0d573eee 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -1532,11 +1532,7 @@ export function escapeMarkdownLineStart(line: string): string {
}
function getCodeBlockFence(text: string): string {
- let longestRun = 0
- for (const line of text.split('\n')) {
- const run = line.trim().match(/^`+/)?.[0].length ?? 0
- longestRun = Math.max(longestRun, run)
- }
+ const longestRun = Math.max(0, ...Array.from(text.matchAll(/`+/g), (match) => match[0].length))
return '`'.repeat(Math.max(3, longestRun + 1))
}
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
index 3668315f2684..257bcd229171 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdownRoundTrip.test.ts
@@ -367,6 +367,17 @@ describe('markdown round trip', () => {
expect(serializeNode(node)).toEqual('````md\nExample:\n```js\nconst a = 1\n```\ndone\n````')
})
+ it('uses a longer fence for inline backtick runs inside code', () => {
+ const node: NotebookBlockNode = {
+ id: '',
+ type: 'code',
+ language: 'javascript',
+ text: 'console.log("```")',
+ }
+
+ expect(serializeNode(node)).toEqual('````javascript\nconsole.log("```")\n````')
+ })
+
it('round-trips code containing fence lines exactly', () => {
const codeText = '```\ninner\n```\n````\ndeeper\n````'
const document = makeDocument([
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
index 0220e1fcdd72..25172ac3c9ca 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.test.ts
@@ -388,6 +388,85 @@ after`)
| line1 line2 |`)
})
+ it('converts legacy markdown ast alias nodes without losing structure', () => {
+ const content: JSONContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'bullet_list',
+ content: [
+ {
+ type: 'list_item',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'first' }] }],
+ },
+ ],
+ },
+ {
+ type: 'ordered_list',
+ content: [
+ {
+ type: 'list_item',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'step' }] }],
+ },
+ ],
+ },
+ {
+ type: 'code_block',
+ attrs: { language: 'sql' },
+ content: [
+ { type: 'text', text: 'select 1' },
+ { type: 'hardBreak' },
+ { type: 'text', text: 'select 2' },
+ ],
+ },
+ {
+ type: 'table',
+ content: [
+ {
+ type: 'table_row',
+ content: [
+ {
+ type: 'table_header',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Metric' }] }],
+ },
+ {
+ type: 'table_cell',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Value' }] }],
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'callout',
+ attrs: { emoji: '!' },
+ content: [
+ {
+ type: 'paragraph',
+ content: [
+ { type: 'text', text: 'Heads', marks: [{ type: 'strong' }] },
+ { type: 'text', text: ' and ' },
+ { type: 'text', text: 'note', marks: [{ type: 'em' }] },
+ ],
+ },
+ ],
+ },
+ { type: 'ph-link', attrs: { href: 'https://app.posthog.com/cohorts/37958' } },
+ ],
+ }
+
+ const markdown = convertNotebookContentToMarkdown(content)
+
+ expect(markdown).toContain('- first')
+ expect(markdown).toContain('1. step')
+ expect(markdown).toContain('```sql\nselect 1\nselect 2\n```')
+ expect(markdown).toContain('| Metric | Value |')
+ expect(markdown).toContain('| --- | --- |')
+ expect(markdown).toContain('> ! **Heads** and *note*')
+ expect(markdown).toContain('[https://app.posthog.com/cohorts/37958](https://app.posthog.com/cohorts/37958)')
+ expect(parseMarkdownNotebook(markdown).errors).toEqual([])
+ })
+
it('produces markdown that parses without errors in the markdown notebook model', () => {
const content: JSONContent = {
type: 'doc',
diff --git a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
index b322507366d7..838364f40376 100644
--- a/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
+++ b/frontend/src/scenes/notebooks/Notebook/markdownNotebookV2.ts
@@ -69,6 +69,16 @@ export const NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Partial<Record<NotebookNodeType
[NotebookNodeType.SupportTickets]: 'SupportTickets',
}
+const RICH_CONTENT_NODE_TYPE_ALIASES: Record<string, string> = {
+ bullet_list: 'bulletList',
+ ordered_list: 'orderedList',
+ list_item: 'listItem',
+ code_block: 'codeBlock',
+ table_row: 'tableRow',
+ table_cell: 'tableCell',
+ table_header: 'tableHeader',
+}
+
export function isMarkdownNotebookContent(content: NotebookContentForMarkdownConversion): boolean {
return !!getMarkdownNotebookNode(content)
}
@@ -400,20 +410,22 @@ function serializeRichContentNode(
listDepth = 0,
options: NotebookMarkdownConversionOptions = {}
): string {
- if (node.type === 'text') {
+ const nodeType = getRichContentNodeType(node)
+
+ if (nodeType === 'text') {
return escapeMarkdownBlockLines(serializeInlineNode(node, options))
}
- if (node.type === 'heading') {
+ if (nodeType === 'heading') {
const level = typeof node.attrs?.level === 'number' ? Math.min(Math.max(node.attrs.level, 1), 6) : 1
return `${'#'.repeat(level)} ${serializeInlineContent(node.content, options)}`
}
- if (node.type === 'paragraph') {
+ if (nodeType === 'paragraph') {
return escapeMarkdownBlockLines(serializeInlineContent(node.content, options))
}
- if (node.type === 'blockquote') {
+ if (nodeType === 'blockquote') {
return (node.content ?? [])
.map((child) => serializeRichContentNode(child, listDepth, options))
.join('\n')
@@ -422,45 +434,53 @@ function serializeRichContentNode(
.join('\n')
}
- if (node.type === 'bulletList' || node.type === 'orderedList' || node.type === 'taskList') {
- return serializeList(node, node.type === 'orderedList', listDepth, options)
+ if (nodeType === 'bulletList' || nodeType === 'orderedList' || nodeType === 'taskList') {
+ return serializeList(node, nodeType === 'orderedList', listDepth, options)
}
- if (node.type === 'horizontalRule') {
+ if (nodeType === 'horizontalRule') {
return '---'
}
- if (node.type === 'codeBlock') {
+ if (nodeType === 'codeBlock') {
const language = typeof node.attrs?.language === 'string' ? node.attrs.language : ''
// Code text must stay verbatim (no inline escaping), and serializeNode picks a fence
// longer than any backtick run in the content
const text = (node.content ?? [])
- .map((child) => (child.type === 'hardBreak' ? '\n' : (child.text ?? '')))
+ .map((child) => (getRichContentNodeType(child) === 'hardBreak' ? '\n' : (child.text ?? '')))
.join('')
return serializeNode({ id: '', type: 'code', language: language || undefined, text })
}
- if (node.type === 'table') {
+ if (nodeType === 'table') {
return serializeTable(node, options)
}
- if (node.type === 'ph-text') {
+ if (nodeType === 'ph-text') {
return serializeLegacyTextNode(node)
}
- if (node.type === 'ph-insight') {
+ if (nodeType === 'ph-insight') {
return serializeLegacyInsightNode(node)
}
- if (node.type === 'ph-dashboard') {
+ if (nodeType === 'ph-dashboard') {
return serializeLegacyDashboardNode(node)
}
- if (node.type === 'query') {
+ if (nodeType === 'query') {
return serializeLegacyQueryNode(node)
}
- const markdownTagName = NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[node.type as NotebookNodeType]
+ if (nodeType === 'ph-link') {
+ return serializeLegacyLinkNode(node, options)
+ }
+
+ if (nodeType === 'callout') {
+ return serializeCalloutNode(node, options)
+ }
+
+ const markdownTagName = nodeType ? NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[nodeType as NotebookNodeType] : undefined
if (markdownTagName) {
return serializeNode({
id: '',
@@ -474,7 +494,7 @@ function serializeRichContentNode(
.map((child) => serializeRichContentNode(child, listDepth, options))
.filter(Boolean)
.join('\n\n')
- if (childMarkdown || !node.type) {
+ if (childMarkdown || !nodeType) {
return childMarkdown
}
@@ -526,6 +546,48 @@ function serializeLegacyQueryNode(node: JSONContent): string {
})
}
+function serializeLegacyLinkNode(node: JSONContent, options: NotebookMarkdownConversionOptions = {}): string {
+ const href = typeof node.attrs?.href === 'string' ? node.attrs.href : null
+ const sanitizedHref = href ? sanitizeNotebookLinkHref(href) : null
+ const label = serializeInlineContent(node.content, options).trim()
+
+ if (sanitizedHref) {
+ return `[${label || escapeInlineMarkdownText(sanitizedHref)}](${sanitizedHref})`
+ }
+
+ if (label) {
+ return label
+ }
+
+ if (href?.trim()) {
+ return escapeMarkdownBlockLines(escapeInlineMarkdownText(href.trim()))
+ }
+
+ return serializeUnknownRichContentNode(node)
+}
+
+function serializeCalloutNode(node: JSONContent, options: NotebookMarkdownConversionOptions = {}): string {
+ const body = (node.content ?? [])
+ .map((child) => serializeRichContentNode(child, 0, options))
+ .filter((block) => block.trim().length > 0)
+ .join('\n\n')
+ .trim()
+ const emoji =
+ typeof node.attrs?.emoji === 'string' && node.attrs.emoji.trim()
+ ? escapeInlineMarkdownText(node.attrs.emoji.trim())
+ : ''
+ const blockquoteBody = `${emoji}${emoji && body ? ' ' : ''}${body}`.trim()
+
+ if (!blockquoteBody) {
+ return serializeUnknownRichContentNode(node)
+ }
+
+ return blockquoteBody
+ .split('\n')
+ .map((line) => `> ${line}`)
+ .join('\n')
+}
+
function isNotebookObjectProp(value: NotebookPropValue | undefined): value is Record<string, NotebookPropValue> {
return !!value && typeof value === 'object' && !Array.isArray(value)
}
@@ -555,16 +617,18 @@ function serializeInlineContent(
}
function serializeInlineNode(node: JSONContent, options: NotebookMarkdownConversionOptions = {}): string {
- if (node.type === 'text') {
+ const nodeType = getRichContentNodeType(node)
+
+ if (nodeType === 'text') {
const isCodeText = (node.marks ?? []).some((mark) => mark.type === 'code')
// Literal `*`/`` ` ``/`[` in legacy text must not become formatting after the upgrade
const escapedText = isCodeText ? escapeCodeSpanText(node.text ?? '') : escapeInlineMarkdownText(node.text ?? '')
return applyMarks(escapedText, node.marks)
}
- if (node.type === 'hardBreak') {
+ if (nodeType === 'hardBreak') {
return '\n'
}
- if (node.type === NotebookNodeType.Mention) {
+ if (nodeType === NotebookNodeType.Mention) {
return serializeMentionNode(node, options)
}
return serializeInlineContent(node.content, options)
@@ -598,10 +662,10 @@ function applyMarks(text: string, marks: JSONContent['marks']): string {
function applyFormattingMarks(text: string, marks: JSONContent['marks']): string {
return (marks ?? []).reduce((markedText, mark) => {
- if (mark.type === 'bold') {
+ if (mark.type === 'bold' || mark.type === 'strong') {
return `**${markedText}**`
}
- if (mark.type === 'italic') {
+ if (mark.type === 'italic' || mark.type === 'em') {
return `*${markedText}*`
}
if (mark.type === 'underline') {
@@ -624,6 +688,10 @@ function applyFormattingMarks(text: string, marks: JSONContent['marks']): string
const LIST_NODE_TYPES = new Set(['bulletList', 'orderedList', 'taskList'])
const LIST_ITEM_NODE_TYPES = new Set(['listItem', 'taskItem'])
+function getRichContentNodeType(node: JSONContent): string | undefined {
+ return node.type ? (RICH_CONTENT_NODE_TYPE_ALIASES[node.type] ?? node.type) : undefined
+}
+
function serializeList(
node: JSONContent,
ordered: boolean,
@@ -642,7 +710,7 @@ function serializeList(
}
}
- const items = (node.content ?? []).filter((child) => LIST_ITEM_NODE_TYPES.has(child.type ?? ''))
+ const items = (node.content ?? []).filter((child) => LIST_ITEM_NODE_TYPES.has(getRichContentNodeType(child) ?? ''))
items.forEach((item, index) => {
const { listLines, trailingBlocks } = serializeListItem(item, ordered, depth, index, options)
pendingListLines.push(...listLines)
@@ -665,10 +733,13 @@ function serializeListItem(
): { listLines: string[]; trailingBlocks: string[] } {
const marker = ordered ? `${index + 1}.` : '-'
const children = item.content ?? []
- const firstParagraph = children.find((child) => child.type === 'paragraph')
- const nestedLists = children.filter((child) => LIST_NODE_TYPES.has(child.type ?? ''))
- const extraBlocks = children.filter((child) => child !== firstParagraph && !LIST_NODE_TYPES.has(child.type ?? ''))
- const checkbox = item.type === 'taskItem' ? (item.attrs?.checked ? '[x] ' : '[ ] ') : ''
+ const itemType = getRichContentNodeType(item)
+ const firstParagraph = children.find((child) => getRichContentNodeType(child) === 'paragraph')
+ const nestedLists = children.filter((child) => LIST_NODE_TYPES.has(getRichContentNodeType(child) ?? ''))
+ const extraBlocks = children.filter(
+ (child) => child !== firstParagraph && !LIST_NODE_TYPES.has(getRichContentNodeType(child) ?? '')
+ )
+ const checkbox = itemType === 'taskItem' ? (item.attrs?.checked ? '[x] ' : '[ ] ') : ''
// List lines cannot contain raw newlines in the markdown notebook model
const itemText = (firstParagraph ? serializeInlineContent(firstParagraph.content, options) : '').replace(
/\s*\n\s*/g,
@@ -691,14 +762,16 @@ function serializeListItem(
}
function serializeTable(node: JSONContent, options: NotebookMarkdownConversionOptions = {}): string {
- const rows = (node.content ?? []).filter((child) => child.type === 'tableRow')
+ const rows = (node.content ?? []).filter((child) => getRichContentNodeType(child) === 'tableRow')
if (!rows.length) {
return ''
}
const serializedRows = rows.map((row) =>
(row.content ?? [])
- .filter((cell) => cell.type === 'tableCell' || cell.type === 'tableHeader')
+ .filter(
+ (cell) => getRichContentNodeType(cell) === 'tableCell' || getRichContentNodeType(cell) === 'tableHeader'
+ )
.map((cell) =>
(cell.content ?? [])
.map((child) => serializeRichContentNode(child, 0, options))
diff --git a/posthog/admin/admins/notebook_markdown_migration_admin.py b/posthog/admin/admins/notebook_markdown_migration_admin.py
index ad9e7499511e..a184870683a4 100644
--- a/posthog/admin/admins/notebook_markdown_migration_admin.py
+++ b/posthog/admin/admins/notebook_markdown_migration_admin.py
@@ -13,6 +13,8 @@ from products.notebooks.backend.facade import api as notebooks_api
if TYPE_CHECKING:
from posthog.models import User
+DEFAULT_NOTEBOOK_MIGRATION_BATCH_SIZE = 100
+
class NotebookMarkdownMigrationForm(forms.Form):
team_id = forms.IntegerField(
@@ -25,6 +27,16 @@ class NotebookMarkdownMigrationForm(forms.Form):
initial=True,
help_text="Preview the notebooks that would be converted without saving anything.",
)
+ batch_size = forms.IntegerField(
+ required=False,
+ initial=DEFAULT_NOTEBOOK_MIGRATION_BATCH_SIZE,
+ min_value=1,
+ max_value=notebooks_api.MAX_NOTEBOOK_MIGRATION_BATCH_SIZE,
+ help_text=(
+ "Only process this many pending notebooks in one request. "
+ f"Use repeated batches for large scopes. Maximum {notebooks_api.MAX_NOTEBOOK_MIGRATION_BATCH_SIZE}."
+ ),
+ )
def notebook_markdown_migration_view(request: HttpRequest) -> HttpResponse:
@@ -58,11 +70,13 @@ def notebook_markdown_migration_run_view(request: HttpRequest) -> JsonResponse:
try:
team_id = _parse_team_id(payload.get("team_id"))
- dry_run = bool(payload.get("dry_run", True))
+ dry_run = _parse_bool(payload.get("dry_run", True))
+ batch_size = _parse_batch_size(payload.get("batch_size"))
result = notebooks_api.migrate_notebooks_to_markdown(
user=cast("User", request.user),
team_id=team_id,
dry_run=dry_run,
+ batch_size=batch_size,
)
except ValueError as err:
return JsonResponse({"error": str(err)}, status=400)
@@ -79,11 +93,37 @@ def _parse_team_id(raw_team_id: Any) -> int | None:
raise ValueError("Team id must be an integer")
+def _parse_batch_size(raw_batch_size: Any) -> int | None:
+ if raw_batch_size is None or raw_batch_size == "":
+ return DEFAULT_NOTEBOOK_MIGRATION_BATCH_SIZE
+ try:
+ batch_size = int(raw_batch_size)
+ except (TypeError, ValueError):
+ raise ValueError("Batch size must be an integer")
+ if batch_size < 1:
+ raise ValueError("Batch size must be at least 1")
+ if batch_size > notebooks_api.MAX_NOTEBOOK_MIGRATION_BATCH_SIZE:
+ raise ValueError(f"Batch size must be {notebooks_api.MAX_NOTEBOOK_MIGRATION_BATCH_SIZE} or less")
+ return batch_size
+
+
+def _parse_bool(raw_value: Any) -> bool:
+ if isinstance(raw_value, bool):
+ return raw_value
+ if isinstance(raw_value, str):
+ normalized_value = raw_value.strip().lower()
+ if normalized_value in ("true", "1", "yes", "on"):
+ return True
+ if normalized_value in ("false", "0", "no", "off"):
+ return False
+ raise ValueError("Dry run must be a boolean")
+
+
def _result_to_response(result: Any) -> dict[str, Any]:
data = asdict(result)
data["message"] = (
- f"Dry run found {result.converted} notebook(s) to convert."
+ f"Dry run previewed {result.converted} notebook(s) from this batch."
if result.dry_run
- else f"Converted {result.converted} notebook(s) to markdown."
+ else f"Converted {result.converted} notebook(s) to markdown. {result.pending_after} pending."
)
return data
diff --git a/posthog/templates/admin/notebook_markdown_migration.html b/posthog/templates/admin/notebook_markdown_migration.html
index d4a92bad4ebb..3d79f5e9d405 100644
--- a/posthog/templates/admin/notebook_markdown_migration.html
+++ b/posthog/templates/admin/notebook_markdown_migration.html
@@ -133,8 +133,13 @@
</label>
<p class="notebook-migration-help">{{ form.dry_run.help_text }}</p>
</div>
+ <div class="notebook-migration-row">
+ <label for="{{ form.batch_size.id_for_label }}">{{ form.batch_size.label }}</label>
+ {{ form.batch_size }}
+ <p class="notebook-migration-help">{{ form.batch_size.help_text }}</p>
+ </div>
<div class="notebook-migration-actions">
- <button type="submit" class="default" id="notebook-migration-submit">Run migration</button>
+ <button type="submit" class="default" id="notebook-migration-submit">Run batch</button>
</div>
</form>
<div id="notebook-migration-message" class="notebook-migration-message"></div>
@@ -149,6 +154,7 @@
const form = document.getElementById("notebook-migration-form")
const teamInput = document.getElementById("id_team_id")
const dryRunInput = document.getElementById("id_dry_run")
+ const batchSizeInput = document.getElementById("id_batch_size")
const refreshButton = document.getElementById("notebook-migration-refresh")
const submitButton = document.getElementById("notebook-migration-submit")
const status = document.getElementById("notebook-migration-status")
@@ -172,11 +178,14 @@
}
async function readJson(response) {
+ const responseText = await response.text()
const contentType = response.headers.get("content-type") || ""
if (!contentType.includes("application/json")) {
- throw new Error("Expected a JSON response from the migration endpoint.")
+ throw new Error(
+ `Migration endpoint returned HTTP ${response.status} instead of JSON.\n${responseText.slice(0, 500)}`
+ )
}
- return await response.json()
+ return JSON.parse(responseText)
}
function renderStats(data) {
@@ -246,6 +255,7 @@
body: JSON.stringify({
team_id: teamInput.value.trim(),
dry_run: dryRunInput.checked,
+ batch_size: batchSizeInput.value.trim(),
}),
})
const data = await readJson(response)
@@ -257,6 +267,9 @@
data.message,
`Total: ${data.total}`,
`Already converted: ${data.already_converted}`,
+ `Pending before batch: ${data.pending_before}`,
+ `Pending after batch: ${data.pending_after}`,
+ `Batch size: ${data.batch_size || "All pending"}`,
`${data.dry_run ? "Would convert" : "Converted"}: ${data.converted}`,
`Skipped: ${data.skipped}`,
`Errored: ${data.errored}`,
@@ -269,7 +282,7 @@
setMessage(String(error), true)
} finally {
submitButton.disabled = false
- submitButton.textContent = "Run migration"
+ submitButton.textContent = "Run batch"
}
})
diff --git a/products/batch_exports/backend/tests/management/test_backfill_batch_export_runs.py b/products/batch_exports/backend/tests/management/test_backfill_batch_export_runs.py
index 6454f9ae176d..1a0b4b2c73e7 100644
--- a/products/batch_exports/backend/tests/management/test_backfill_batch_export_runs.py
+++ b/products/batch_exports/backend/tests/management/test_backfill_batch_export_runs.py
@@ -395,9 +395,12 @@ def hour_window(hours_back: int) -> tuple[datetime, datetime]:
return REFERENCE_TIME - timedelta(hours=hours_back), REFERENCE_TIME
-def run_backfill_command(*args, stderr=None):
- """Run the backfill_batch_export_runs management command with --no-delay and --no-confirm."""
- call_command("backfill_batch_export_runs", *args, "--no-delay", "--no-confirm", stderr=stderr)
+def run_backfill_command(*args, stderr=None, no_delay=True):
+ """Run the backfill_batch_export_runs management command with --no-confirm."""
+ command_args = [*args, "--no-confirm"]
+ if no_delay:
+ command_args.append("--no-delay")
+ call_command("backfill_batch_export_runs", *command_args, stderr=stderr)
@pytest.mark.django_db
@@ -437,16 +440,16 @@ class TestBackfillCommand:
logging.warning("Schedule %s already deleted", export.id)
@pytest.mark.parametrize(
- "window_hours, covered_hour_offsets, expected_interval_end_offsets",
+ "window_hours, covered_hour_offsets, expected_interval_end_offsets, no_delay",
[
- pytest.param(2, [(0, 1)], [2], id="single_missing_interval"),
- pytest.param(6, [(0, 1), (5, 6)], [2, 3, 4, 5], id="merged_missing_intervals"),
- pytest.param(4, [(1, 2), (3, 4)], [1, 3], id="non_continuous_gaps"),
- pytest.param(3, [(0, 1), (1, 2), (2, 3)], [], id="fully_covered"),
+ pytest.param(2, [(0, 1)], [2], True, id="single_missing_interval"),
+ pytest.param(6, [(0, 1), (5, 6)], [2, 3, 4, 5], True, id="merged_missing_intervals"),
+ pytest.param(4, [(1, 2), (3, 4)], [1, 3], False, id="non_continuous_gaps"),
+ pytest.param(3, [(0, 1), (1, 2), (2, 3)], [], True, id="fully_covered"),
],
)
def test_backfill_triggers_expected_workflows(
- self, team, temporal, window_hours, covered_hour_offsets, expected_interval_end_offsets
+ self, team, temporal, window_hours, covered_hour_offsets, expected_interval_end_offsets, no_delay
):
export = create_noop_export_with_schedule(team, interval="hour")
start, end = hour_window(window_hours)
@@ -455,7 +458,10 @@ class TestBackfillCommand:
create_run(export, start + timedelta(hours=offset_start), start + timedelta(hours=offset_end))
run_backfill_command(
- f"--batch-export-id={export.id}", f"--start={start.isoformat()}", f"--end={end.isoformat()}"
+ f"--batch-export-id={export.id}",
+ f"--start={start.isoformat()}",
+ f"--end={end.isoformat()}",
+ no_delay=no_delay,
)
if expected_interval_end_offsets:
diff --git a/products/notebooks/backend/activity_logging.py b/products/notebooks/backend/activity_logging.py
index cdf44641d60a..83cb478fb54a 100644
--- a/products/notebooks/backend/activity_logging.py
+++ b/products/notebooks/backend/activity_logging.py
@@ -5,9 +5,10 @@ delete/restore hooks it registers at ready() without importing the API module
module-scope imports reach the kernel runtime and the tasks sandbox (modal SDK).
"""
+from datetime import datetime
from typing import Optional
-from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
+from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, log_activity
from posthog.models.user import User
from posthog.models.utils import UUIDT
@@ -22,9 +23,10 @@ def log_notebook_activity(
user: User,
was_impersonated: bool,
changes: Optional[list[Change]] = None,
-) -> None:
+ created_at: datetime | None = None,
+) -> ActivityLog | None:
short_id = str(notebook.short_id)
- log_activity(
+ log = log_activity(
organization_id=organization_id,
team_id=team_id,
user=user,
@@ -34,3 +36,7 @@ def log_notebook_activity(
activity=activity,
detail=Detail(changes=changes, short_id=short_id, name=notebook.title),
)
+ if log is not None and created_at is not None:
+ ActivityLog.objects.filter(pk=log.pk).update(created_at=created_at)
+ log.created_at = created_at
+ return log
diff --git a/products/notebooks/backend/facade/api.py b/products/notebooks/backend/facade/api.py
index 8e9858ba7216..99b345d5cd9d 100644
--- a/products/notebooks/backend/facade/api.py
+++ b/products/notebooks/backend/facade/api.py
@@ -23,6 +23,8 @@ if TYPE_CHECKING:
from posthog.models import User
from posthog.rbac.user_access_control import UserAccessControl
+MAX_NOTEBOOK_MIGRATION_BATCH_SIZE = markdown_migration.MAX_NOTEBOOK_MIGRATION_BATCH_SIZE
+
def _to_notebook_data(notebook: Notebook) -> contracts.NotebookData:
return contracts.NotebookData(
@@ -164,12 +166,14 @@ def migrate_notebooks_to_markdown(
user: "User",
team_id: int | None = None,
dry_run: bool = True,
+ batch_size: int | None = None,
max_previews: int = 5,
) -> contracts.MarkdownNotebookMigrationResult:
return markdown_migration.migrate_notebooks_to_markdown(
user=user,
team_id=team_id,
dry_run=dry_run,
+ batch_size=batch_size,
max_previews=max_previews,
)
diff --git a/products/notebooks/backend/facade/contracts.py b/products/notebooks/backend/facade/contracts.py
index 6f49c5c3e574..7b9e2dc468a5 100644
--- a/products/notebooks/backend/facade/contracts.py
+++ b/products/notebooks/backend/facade/contracts.py
@@ -82,8 +82,11 @@ class MarkdownNotebookMigrationResult:
dry_run: bool
team_id: int | None
+ batch_size: int | None
total: int
already_converted: int
+ pending_before: int
+ pending_after: int
converted: int
skipped: int
errored: int
diff --git a/products/notebooks/backend/markdown_conversion.py b/products/notebooks/backend/markdown_conversion.py
index 20fb5f749aee..a841247564b4 100644
--- a/products/notebooks/backend/markdown_conversion.py
+++ b/products/notebooks/backend/markdown_conversion.py
@@ -1,5 +1,6 @@
import re
import json
+import math
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import Any, cast
@@ -46,6 +47,16 @@ NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG: Mapping[str, str] = {
"ph-support-tickets": "SupportTickets",
}
+RICH_CONTENT_NODE_TYPE_ALIASES: Mapping[str, str] = {
+ "bullet_list": "bulletList",
+ "ordered_list": "orderedList",
+ "list_item": "listItem",
+ "code_block": "codeBlock",
+ "table_row": "tableRow",
+ "table_cell": "tableCell",
+ "table_header": "tableHeader",
+}
+
LIST_NODE_TYPES = {"bulletList", "orderedList", "taskList"}
LIST_ITEM_NODE_TYPES = {"listItem", "taskItem"}
_SERIALIZATION_OMIT = object()
@@ -72,6 +83,13 @@ def get_markdown_notebook_markdown(content: Any) -> str:
return markdown if isinstance(markdown, str) else ""
+def notebook_content_has_comment_marks(content: Any) -> bool:
+ normalized_content = _normalize_notebook_content_for_markdown_conversion(content)
+ if isinstance(normalized_content, str):
+ return False
+ return any(_collect_comment_mark_ids(node) for node in _content_list(normalized_content))
+
+
def build_markdown_notebook_content(markdown: str, node_id: str = MARKDOWN_NOTEBOOK_NODE_ID) -> JSONContent:
return {
"type": "doc",
@@ -179,6 +197,13 @@ def _content_list(content: JSONContent | str | None) -> list[JSONContent]:
return [node for node in nodes if isinstance(node, dict)] if isinstance(nodes, list) else []
+def _node_type(node: JSONContent) -> str | None:
+ node_type = node.get("type")
+ if not isinstance(node_type, str):
+ return None
+ return RICH_CONTENT_NODE_TYPE_ALIASES.get(node_type, node_type)
+
+
def _collect_comment_mark_ids(node: JSONContent) -> list[str]:
mark_ids: list[str] = []
@@ -203,7 +228,7 @@ def _serialize_rich_content_node(
options: NotebookMarkdownConversionOptions | None = None,
) -> str:
options = options or NotebookMarkdownConversionOptions()
- node_type = node.get("type")
+ node_type = _node_type(node)
if node_type == "text":
return escape_markdown_block_lines(_serialize_inline_node(node, options))
@@ -234,7 +259,7 @@ def _serialize_rich_content_node(
attrs = node.get("attrs")
language = attrs.get("language") if isinstance(attrs, dict) and isinstance(attrs.get("language"), str) else ""
text = "".join(
- "\n" if child.get("type") == "hardBreak" else str(child.get("text") or "") for child in _content_list(node)
+ "\n" if _node_type(child) == "hardBreak" else str(child.get("text") or "") for child in _content_list(node)
)
return _serialize_code_node(text, language or None)
@@ -253,6 +278,12 @@ def _serialize_rich_content_node(
if node_type == "query":
return _serialize_legacy_query_node(node)
+ if node_type == "ph-link":
+ return _serialize_legacy_link_node(node, options)
+
+ if node_type == "callout":
+ return _serialize_callout_node(node, options)
+
if isinstance(node_type, str) and node_type in NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG:
return _serialize_component_node(
NOTEBOOK_NODE_TYPE_TO_MARKDOWN_TAG[node_type],
@@ -302,6 +333,41 @@ def _serialize_legacy_query_node(node: JSONContent) -> str:
return _serialize_component_node("Query", props)
+def _serialize_legacy_link_node(node: JSONContent, options: NotebookMarkdownConversionOptions) -> str:
+ attrs = node.get("attrs")
+ href = attrs.get("href") if isinstance(attrs, dict) else None
+ sanitized_href = sanitize_notebook_link_href(href) if isinstance(href, str) else None
+ label = _serialize_inline_content(_content_list(node), options).strip()
+
+ if sanitized_href:
+ link_label = label or escape_inline_markdown_text(sanitized_href)
+ return f"[{link_label}]({sanitized_href})"
+
+ if label:
+ return label
+
+ if isinstance(href, str) and href.strip():
+ return escape_markdown_block_lines(escape_inline_markdown_text(href.strip()))
+
+ return _serialize_unknown_rich_content_node(node)
+
+
+def _serialize_callout_node(node: JSONContent, options: NotebookMarkdownConversionOptions) -> str:
+ attrs = node.get("attrs")
+ raw_emoji = attrs.get("emoji") if isinstance(attrs, dict) else None
+ emoji = raw_emoji.strip() if isinstance(raw_emoji, str) else ""
+ body = "\n\n".join(
+ block
+ for block in (_serialize_rich_content_node(child, 0, options) for child in _content_list(node))
+ if block.strip()
+ ).strip()
+ if emoji:
+ body = f"{escape_inline_markdown_text(emoji)} {body}".strip()
+ if not body:
+ return _serialize_unknown_rich_content_node(node)
+ return "\n".join(f"> {line}" for line in body.split("\n"))
+
+
def _serialize_unknown_rich_content_node(node: JSONContent) -> str:
attrs = _get_serializable_attrs(node.get("attrs") if isinstance(node.get("attrs"), dict) else None)
node_type = node.get("type")
@@ -320,7 +386,7 @@ def _serialize_inline_content(
def _serialize_inline_node(node: JSONContent, options: NotebookMarkdownConversionOptions | None = None) -> str:
options = options or NotebookMarkdownConversionOptions()
- node_type = node.get("type")
+ node_type = _node_type(node)
if node_type == "text":
marks = _mark_list(node)
@@ -373,9 +439,9 @@ def _apply_formatting_marks(text: str, marks: list[JSONContent]) -> str:
marked_text = text
for mark in marks:
mark_type = mark.get("type")
- if mark_type == "bold":
+ if mark_type in ("bold", "strong"):
marked_text = f"**{marked_text}**"
- elif mark_type == "italic":
+ elif mark_type in ("italic", "em"):
marked_text = f"*{marked_text}*"
elif mark_type == "underline":
marked_text = f"<u>{marked_text}</u>"
@@ -407,7 +473,7 @@ def _serialize_list(
blocks.append("\n".join(pending_list_lines))
pending_list_lines = []
- items = [child for child in _content_list(node) if child.get("type") in LIST_ITEM_NODE_TYPES]
+ items = [child for child in _content_list(node) if _node_type(child) in LIST_ITEM_NODE_TYPES]
for index, item in enumerate(items):
list_lines, trailing_blocks = _serialize_list_item(item, ordered, depth, index, options)
pending_list_lines.extend(list_lines)
@@ -428,15 +494,14 @@ def _serialize_list_item(
) -> tuple[list[str], list[str]]:
marker = f"{index + 1}." if ordered else "-"
children = _content_list(item)
- first_paragraph = next((child for child in children if child.get("type") == "paragraph"), None)
- nested_lists = [child for child in children if child.get("type") in LIST_NODE_TYPES]
+ item_type = _node_type(item)
+ first_paragraph = next((child for child in children if _node_type(child) == "paragraph"), None)
+ nested_lists = [child for child in children if _node_type(child) in LIST_NODE_TYPES]
extra_blocks = [
- child for child in children if child is not first_paragraph and child.get("type") not in LIST_NODE_TYPES
+ child for child in children if child is not first_paragraph and _node_type(child) not in LIST_NODE_TYPES
]
checked = item.get("attrs", {}).get("checked") if isinstance(item.get("attrs"), dict) else False
- checkbox = (
- "[x] " if item.get("type") == "taskItem" and checked else "[ ] " if item.get("type") == "taskItem" else ""
- )
+ checkbox = "[x] " if item_type == "taskItem" and checked else "[ ] " if item_type == "taskItem" else ""
item_text = re.sub(
r"\s*\n\s*", " ", _serialize_inline_content(_content_list(first_paragraph), options) if first_paragraph else ""
)
@@ -455,13 +520,13 @@ def _serialize_list_item(
def _serialize_table(node: JSONContent, options: NotebookMarkdownConversionOptions | None = None) -> str:
options = options or NotebookMarkdownConversionOptions()
- rows = [child for child in _content_list(node) if child.get("type") == "tableRow"]
+ rows = [child for child in _content_list(node) if _node_type(child) == "tableRow"]
if not rows:
return ""
serialized_rows: list[list[str]] = []
for row in rows:
- cells = [cell for cell in _content_list(row) if cell.get("type") in ("tableCell", "tableHeader")]
+ cells = [cell for cell in _content_list(row) if _node_type(cell) in ("tableCell", "tableHeader")]
serialized_cells: list[str] = []
for cell in cells:
cell_text = " ".join(_serialize_rich_content_node(child, 0, options) for child in _content_list(cell))
@@ -574,8 +639,22 @@ def _get_ordered_component_prop_entries(props: Mapping[str, NotebookPropValue])
def _serialize_prop_value(value: NotebookPropValue) -> str:
if isinstance(value, str):
- return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
- return "{" + json.dumps(value, ensure_ascii=False, separators=(",", ":")) + "}"
+ return _json_stringify(value)
+ return "{" + _json_stringify(value) + "}"
+
+
+def _json_stringify(value: NotebookPropValue) -> str:
+ return json.dumps(_normalize_json_numbers(value), ensure_ascii=False, separators=(",", ":"))
+
+
+def _normalize_json_numbers(value: NotebookPropValue) -> NotebookPropValue:
+ if isinstance(value, float) and math.isfinite(value) and value.is_integer():
+ return int(value)
+ if isinstance(value, list):
+ return [_normalize_json_numbers(item) for item in value]
+ if isinstance(value, dict):
+ return {key: _normalize_json_numbers(item) for key, item in value.items()}
+ return value
def _serialize_code_node(text: str, language: str | None = None) -> str:
@@ -597,7 +676,10 @@ def sanitize_notebook_link_href(href: str) -> str | None:
trimmed_href = href.strip()
if not re.match(r"^https?://\S+$", trimmed_href, flags=re.IGNORECASE):
return None
- parsed = urlparse(trimmed_href)
+ try:
+ parsed = urlparse(trimmed_href)
+ except ValueError:
+ return None
return trimmed_href if parsed.scheme in ("http", "https") and parsed.netloc else None
diff --git a/products/notebooks/backend/markdown_migration.py b/products/notebooks/backend/markdown_migration.py
index 9c5b01afa746..670b3fca68de 100644
--- a/products/notebooks/backend/markdown_migration.py
+++ b/products/notebooks/backend/markdown_migration.py
@@ -3,7 +3,6 @@ from typing import Any, cast
from django.db import transaction
from django.db.models import QuerySet
-from django.utils.timezone import now
from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import changes_between
@@ -22,10 +21,13 @@ from products.notebooks.backend.markdown_conversion import (
build_markdown_notebook_content,
convert_notebook_content_to_markdown,
is_markdown_notebook_content,
+ notebook_content_has_comment_marks,
)
from products.notebooks.backend.models import Notebook
from products.notebooks.backend.python_analysis import annotate_python_nodes
+MAX_NOTEBOOK_MIGRATION_BATCH_SIZE = 500
+
def get_markdown_notebook_migration_stats(team_id: int | None = None) -> MarkdownNotebookMigrationStats:
_validate_team_id(team_id)
@@ -40,8 +42,10 @@ def migrate_notebooks_to_markdown(
user: User,
team_id: int | None = None,
dry_run: bool = True,
+ batch_size: int | None = None,
max_previews: int = 5,
) -> MarkdownNotebookMigrationResult:
+ batch_size = _validate_batch_size(batch_size)
stats = get_markdown_notebook_migration_stats(team_id)
converted = 0
skipped = 0
@@ -49,7 +53,11 @@ def migrate_notebooks_to_markdown(
previews: list[MarkdownNotebookMigrationPreview] = []
errors: list[str] = []
- for notebook in _notebook_scope(team_id).select_related("team").order_by("team_id", "id").iterator(chunk_size=100):
+ queryset = _pending_notebook_scope(team_id).select_related("team").order_by("team_id", "id")
+ if batch_size is not None:
+ queryset = queryset[:batch_size]
+
+ for notebook in queryset.iterator(chunk_size=100):
if is_markdown_notebook_content(notebook.content):
skipped += 1
continue
@@ -76,17 +84,23 @@ def migrate_notebooks_to_markdown(
)
continue
- _convert_notebook(notebook, user=user, content=next_content, text_content=markdown)
- converted += 1
+ if _convert_notebook(notebook, user=user, content=next_content, text_content=markdown):
+ converted += 1
+ else:
+ skipped += 1
except Exception as err:
errored += 1
errors.append(f"{notebook.short_id}: {err}")
+ final_stats = stats if dry_run else get_markdown_notebook_migration_stats(team_id)
return MarkdownNotebookMigrationResult(
dry_run=dry_run,
team_id=team_id,
+ batch_size=batch_size,
total=stats.total,
already_converted=stats.converted,
+ pending_before=stats.pending,
+ pending_after=final_stats.pending,
converted=converted,
skipped=skipped,
errored=errored,
@@ -100,31 +114,41 @@ def _validate_team_id(team_id: int | None) -> None:
raise ValueError(f"Team {team_id} does not exist")
+def _validate_batch_size(batch_size: int | None) -> int | None:
+ if batch_size is None:
+ return None
+ if batch_size < 1:
+ raise ValueError("Batch size must be at least 1")
+ if batch_size > MAX_NOTEBOOK_MIGRATION_BATCH_SIZE:
+ raise ValueError(f"Batch size must be {MAX_NOTEBOOK_MIGRATION_BATCH_SIZE} or less")
+ return batch_size
+
+
def _notebook_scope(team_id: int | None) -> QuerySet[Notebook]:
queryset = Notebook.objects.all()
return queryset.filter(team_id=team_id) if team_id is not None else queryset
-def _convert_notebook(notebook: Notebook, *, user: User, content: dict[str, Any], text_content: str) -> None:
+def _pending_notebook_scope(team_id: int | None) -> QuerySet[Notebook]:
+ return _notebook_scope(team_id).exclude(content__content__0__type=markdown_collab.MARKDOWN_NOTEBOOK_NODE_TYPE)
+
+
+def _convert_notebook(notebook: Notebook, *, user: User, content: dict[str, Any], text_content: str) -> bool:
with transaction.atomic():
locked_notebook = Notebook.objects.select_for_update().select_related("team").get(pk=notebook.pk)
if is_markdown_notebook_content(locked_notebook.content):
- return
+ return False
before_update = Notebook.objects.get(pk=locked_notebook.pk)
annotated_content = annotate_python_nodes(content)
locked_notebook.content = annotated_content
locked_notebook.text_content = text_content
locked_notebook.version += 1
- locked_notebook.last_modified_at = now()
- locked_notebook.last_modified_by = user
locked_notebook.save(
update_fields=[
"content",
"text_content",
"version",
- "last_modified_at",
- "last_modified_by",
]
)
@@ -149,10 +173,15 @@ def _convert_notebook(notebook: Notebook, *, user: User, content: dict[str, Any]
user=user,
was_impersonated=False,
changes=changes,
+ created_at=before_update.last_modified_at,
)
+ return True
def _build_comment_replies_by_mark_id(notebook: Notebook) -> dict[str, list[Any]]:
+ if not notebook_content_has_comment_marks(notebook.content):
+ return {}
+
root_comments = list(
Comment.objects.filter(team_id=notebook.team_id, scope="Notebook", item_id=notebook.short_id)
.filter(deleted=False, source_comment_id__isnull=True)
diff --git a/products/notebooks/backend/test/test_markdown_migration.py b/products/notebooks/backend/test/test_markdown_migration.py
index 357a84892158..fe00267d8a64 100644
--- a/products/notebooks/backend/test/test_markdown_migration.py
+++ b/products/notebooks/backend/test/test_markdown_migration.py
@@ -1,6 +1,10 @@
+from datetime import timedelta
+
from posthog.test.base import BaseTest
from unittest.mock import patch
+from django.utils import timezone
+
from posthog.models import Organization, Team, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.comment import Comment
@@ -47,7 +51,24 @@ class TestNotebookMarkdownConversion(BaseTest):
},
{
"type": "query",
- "attrs": {"query": '{"kind":"HogQLQuery","query":"select 1"}', "view": True, "edit": False},
+ "attrs": {
+ "query": '{"kind":"HogQLQuery","query":"select 1"}',
+ "view": True,
+ "edit": False,
+ "chartSettings": {
+ "yAxis": [{"settings": {"formatting": {"decimalPlaces": 1.0, "threshold": 1.5}}}]
+ },
+ },
+ },
+ {
+ "type": "paragraph",
+ "content": [
+ {
+ "type": "text",
+ "text": "invalid link",
+ "marks": [{"type": "link", "attrs": {"href": "https://www.juheapi.com):≈"}}],
+ }
+ ],
},
],
}
@@ -65,8 +86,90 @@ class TestNotebookMarkdownConversion(BaseTest):
assert '<ref id="mark-1">** about activation**</ref>' in markdown
assert '<Comment ref="mark-1" replies={[]} />' in markdown
assert 'query={{"kind":"DataVisualizationNode","source":{"kind":"HogQLQuery","query":"select 1"}}}' in markdown
+ assert '"decimalPlaces":1' in markdown
+ assert '"decimalPlaces":1.0' not in markdown
+ assert '"threshold":1.5' in markdown
+ assert "invalid link" in markdown
+ assert "juheapi" not in markdown
assert "hideFilters" in markdown
+ def test_converts_legacy_markdown_ast_alias_nodes_without_losing_structure(self) -> None:
+ content = {
+ "type": "doc",
+ "content": [
+ {
+ "type": "bullet_list",
+ "content": [
+ {
+ "type": "list_item",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "first"}]}],
+ }
+ ],
+ },
+ {
+ "type": "ordered_list",
+ "content": [
+ {
+ "type": "list_item",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "step"}]}],
+ }
+ ],
+ },
+ {
+ "type": "code_block",
+ "attrs": {"language": "sql"},
+ "content": [
+ {"type": "text", "text": "select 1"},
+ {"type": "hardBreak"},
+ {"type": "text", "text": "select 2"},
+ ],
+ },
+ {
+ "type": "table",
+ "content": [
+ {
+ "type": "table_row",
+ "content": [
+ {
+ "type": "table_header",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Metric"}]}],
+ },
+ {
+ "type": "table_cell",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Value"}]}],
+ },
+ ],
+ }
+ ],
+ },
+ {
+ "type": "callout",
+ "attrs": {"emoji": "!"},
+ "content": [
+ {
+ "type": "paragraph",
+ "content": [
+ {"type": "text", "text": "Heads", "marks": [{"type": "strong"}]},
+ {"type": "text", "text": " and "},
+ {"type": "text", "text": "note", "marks": [{"type": "em"}]},
+ ],
+ }
+ ],
+ },
+ {"type": "ph-link", "attrs": {"href": "https://app.posthog.com/cohorts/37958"}},
+ ],
+ }
+
+ markdown = convert_notebook_content_to_markdown(content)
+
+ assert "- first" in markdown
+ assert "1. step" in markdown
+ assert "```sql\nselect 1\nselect 2\n```" in markdown
+ assert "| Metric | Value |" in markdown
+ assert "| --- | --- |" in markdown
+ assert "> ! **Heads** and *note*" in markdown
+ assert "[https://app.posthog.com/cohorts/37958](https://app.posthog.com/cohorts/37958)" in markdown
+
class TestNotebookMarkdownMigration(BaseTest):
def test_stats_count_all_notebooks_for_optional_team_scope(self) -> None:
@@ -105,6 +208,58 @@ class TestNotebookMarkdownMigration(BaseTest):
}
assert not ActivityLog.objects.filter(scope="Notebook", item_id=notebook.short_id).exists()
+ @patch("products.notebooks.backend.markdown_collab.publish_notebook_update")
+ def test_batches_dry_run_and_apply_without_processing_every_pending_notebook(self, mock_publish) -> None:
+ notebooks = [
+ Notebook.objects.create(
+ team=self.team,
+ title=f"Batch {index}",
+ content={
+ "type": "doc",
+ "content": [{"type": "paragraph", "content": [{"type": "text", "text": f"body {index}"}]}],
+ },
+ )
+ for index in range(3)
+ ]
+
+ dry_run_result = migrate_notebooks_to_markdown(user=self.user, team_id=self.team.id, dry_run=True, batch_size=2)
+ for notebook in notebooks:
+ notebook.refresh_from_db()
+
+ assert dry_run_result.converted == 2
+ assert dry_run_result.batch_size == 2
+ assert dry_run_result.pending_before == 3
+ assert dry_run_result.pending_after == 3
+ assert len(dry_run_result.previews) == 2
+ assert all(notebook.content["content"][0]["type"] != "ph-markdown-notebook" for notebook in notebooks)
+
+ with self.captureOnCommitCallbacks(execute=True):
+ first_apply_result = migrate_notebooks_to_markdown(
+ user=self.user, team_id=self.team.id, dry_run=False, batch_size=2
+ )
+
+ for notebook in notebooks:
+ notebook.refresh_from_db()
+
+ assert first_apply_result.converted == 2
+ assert first_apply_result.pending_before == 3
+ assert first_apply_result.pending_after == 1
+ assert sum(notebook.content["content"][0]["type"] == "ph-markdown-notebook" for notebook in notebooks) == 2
+
+ with self.captureOnCommitCallbacks(execute=True):
+ second_apply_result = migrate_notebooks_to_markdown(
+ user=self.user, team_id=self.team.id, dry_run=False, batch_size=2
+ )
+
+ for notebook in notebooks:
+ notebook.refresh_from_db()
+
+ assert second_apply_result.converted == 1
+ assert second_apply_result.pending_before == 1
+ assert second_apply_result.pending_after == 0
+ assert all(notebook.content["content"][0]["type"] == "ph-markdown-notebook" for notebook in notebooks)
+ assert mock_publish.call_count == 3
+
@patch("products.notebooks.backend.markdown_collab.publish_notebook_update")
def test_apply_converts_team_notebooks_and_logs_before_after_history(self, mock_publish) -> None:
rich_content = {
@@ -122,7 +277,16 @@ class TestNotebookMarkdownMigration(BaseTest):
}
],
}
- notebook = Notebook.objects.create(team=self.team, title="Convert me", content=rich_content, version=7)
+ original_modified_at = timezone.now() - timedelta(days=30)
+ original_modifier = self._create_user("[email protected]")
+ notebook = Notebook.objects.create(
+ team=self.team,
+ title="Convert me",
+ content=rich_content,
+ version=7,
+ last_modified_at=original_modified_at,
+ last_modified_by=original_modifier,
+ )
Comment.objects.create(
team=self.team,
scope="Notebook",
@@ -144,6 +308,8 @@ class TestNotebookMarkdownMigration(BaseTest):
other_notebook.refresh_from_db()
assert result.converted == 1
assert notebook.version == 8
+ assert notebook.last_modified_at == original_modified_at
+ assert notebook.last_modified_by_id == original_modifier.id
assert notebook.text_content is not None
assert "<Comment" in notebook.text_content
assert "keep this" in notebook.text_content
@@ -160,6 +326,9 @@ class TestNotebookMarkdownMigration(BaseTest):
assert changes_by_field["content"]["after"] == notebook.content
assert changes_by_field["version"]["before"] == 7
assert changes_by_field["version"]["after"] == 8
+ assert "last_modified_at" not in changes_by_field
+ assert "last_modified_by" not in changes_by_field
+ assert log.created_at == original_modified_at
mock_publish.assert_called_once_with(self.team.id, notebook.short_id, 8, diff=None)
def test_apply_scopes_mention_label_lookup_to_notebook_organization(self) -> None: